I am using using OpenAISwift to work with chatGTP API, I am having an issue with the API that suddenly stopped working. Despite having a valid token and enough credit for API usage, I am not receiving any response from the API. I was previously using the default repo model, but it seems that many models have been shut down by OpenAI. I changed it to .chat (.chatgpt)
to use GPT-3 and also tested with the GPT-3 turbo model, but I still am not getting any data. This is a crucial issue for my AI-based app, and I would be grateful for any workaround. If it helps, here is my code.
@MainActor
class AIViewModel: ObservableObject {
private var client: OpenAISwift?
@Published var respnse = ""
@Published var isLoading = false
@Published var recievedError = false
init() { client = OpenAISwift(config: .makeDefaultOpenAI(apiKey: "sk-*******")) }
func ask(text: String) async {
isLoading = true
do {
let result = try await client?.sendCompletion(
with: text,
model: .chat(.chatgpt),
maxTokens: 200
)
let output = result?.choices?.first?.text.trimmingCharacters(in: .newlines) ?? "no answer"
//print(output)
self.respnse = output
} catch {
print(error.localizedDescription)
recievedError = true
}
isLoading = false
}
}
Your problem is probably due to using the OpenAI
legacy endpoint with completion (as mentioned already by Rok Benko)
Try this approach using the more up-to-date OpenAISwift
code from
Swift-Almanac OpenAISwift and with sendChat(...)
instead.
Working example code:
import Foundation
import SwiftUI
import OpenAISwift
struct ContentView: View {
@StateObject var model = AIViewModel()
var body: some View {
Text(model.respnse)
.task {
await model.ask(text: "say hello")
}
}
}
@MainActor
class AIViewModel: ObservableObject {
private let client: OpenAISwift
@Published var respnse = ""
@Published var isLoading = false
@Published var recievedError = false
init() {
self.client = OpenAISwift(config: .makeDefaultOpenAI(apiKey: "sk-xxxxx"))
}
func ask(text: String) async {
let chatArr = [ChatMessage(role: .user, content: text)]
do {
let results = try await client.sendChat(
with: chatArr,
model: .gpt4,
maxTokens: 200
)
print("-----> results: \(results)")
if let output = results.choices?.first,
let txt = output.message.content {
self.respnse = txt
print("\n-----> respnse: \(respnse)")
}
} catch {
print(error)
}
}
}