Hey everyone! I’m trying to build a chat app using SwiftUI and OpenAI’s API. I’ve set up a REST API with Alamofire, but I’m running into some issues. When I send a POST request to the API, I get a 400 error. Here’s what I’ve tried so far:
Double-checked my API key
Tested with a cURL command (which worked fine)
Set up my SwiftUI view with a text field for user input and a list to display messages
My code looks something like this:
struct ChatView: View {
@State private var messages: [ChatMessage] = []
@State private var userInput = ""
func sendMessage() {
let params = ["prompt": userInput, "model": "gpt-3.5-turbo"]
NetworkManager.shared.post(url: "ai-api-endpoint", params: params) { result in
switch result {
case .success(let response):
// Handle success
case .failure(let error):
// Handle error
}
}
}
// View body here
}
Any ideas on what I might be doing wrong? I’m pretty new to working with APIs in Swift, so I might be missing something obvious. Thanks for any help!
Having worked extensively with OpenAI’s API in SwiftUI, I can offer some insights. Your approach is on the right track, but there are a few tweaks that could resolve your issue. Ensure you’re using the correct endpoint URL (https://api.openai.com/v1/chat/completions) and that your request body is properly formatted as JSON. Also, don’t forget to set the ‘Content-Type’ header to ‘application/json’ and include your API key in the ‘Authorization’ header.
One common pitfall is not handling the response correctly. The API returns a JSON object, so you’ll need to decode it. Consider using Codable for this:
struct APIResponse: Codable {
let choices: [Choice]
}
struct Choice: Codable {
let message: Message
}
struct Message: Codable {
let content: String
}
Then, in your success case, decode the response and update your UI accordingly. This should help you get your SwiftUI chat app up and running smoothly with OpenAI’s API.
I’ve been through similar struggles with OpenAI’s API in SwiftUI, and I think I might know what’s causing your 400 error. The issue likely lies in how you’re formatting the request body.
For OpenAI’s chat completion endpoint, they expect a specific JSON structure. Try modifying your sendMessage function like this:
func sendMessage() {
let messages = [
["role": "user", "content": userInput]
]
let params: [String: Any] = [
"model": "gpt-3.5-turbo",
"messages": messages
]
NetworkManager.shared.post(url: "https://api.openai.com/v1/chat/completions", params: params) { result in
// Handle result
}
}
Also, make sure you’re setting the correct headers:
yo finn, i’ve been there. make sure ur using the right endpoint (api.openai.com/v1/chat/completions) and format ur json properly. also, check ur headers - Content-Type should be application/json and dont forget ur API key in the Authorization header. if ur still stuck, hit me up and we can troubleshoot together!
I’ve implemented OpenAI’s API in SwiftUI recently, and I can share some insights. One crucial aspect often overlooked is error handling. Implement a robust error handling mechanism to catch and log specific API errors. This will help you pinpoint issues quickly.
Consider using a dedicated APIClient class to manage all API interactions. This centralizes your network logic and makes it easier to maintain. Also, implement request retrying with exponential backoff for intermittent failures.
For better performance, implement caching of API responses. This reduces unnecessary API calls and improves app responsiveness. SwiftUI’s @ObservableObject can be useful for managing and updating the chat state across your app.
Lastly, don’t forget to implement proper rate limiting to stay within OpenAI’s usage guidelines. This will help avoid potential account suspensions or unexpected bills.