We wrote a Swift library for the ChatGPT API Feel free to submit a pull request to help grow the library. The library is written in Swift and supports the following platforms: iOS, macOS, tvOS, and watchOS.
Well done! However, in a production environment, it could be instantly hacked with a MITM attack. To prevent this, support for SSL Pinning should be implemented
I am getting a nil result from generateChatCompletion. My API Key works fine if I use it in a curl command. I am using Xcode 14.3 on MacOS 13.2.1. Here is my code:
import Foundation
import OpenAIKit
let apiToken: String = "*******"
let organizationName: String = "*******"
let config = Configuration(
organizationId: apiToken,
apiKey: organizationName
)
public let openAI = OpenAI(config)
func getChatResponse(message: String) async -> String {
let chatMsg = ChatMessage(role: .user, content: message)
let chat = ChatParameters(model: "gpt-3.5-turbo", messages: [chatMsg])
var response = ""
let result = try? await openAI.generateChatCompletion(parameters: chat)
if let aiResult = result {
if let text = aiResult.choices.first?.message.content {
response = "Response: " + text }
else {
response = "Error"
}
} else { response = "Nada"}
return response
}
Thanks! I got it working. In the preceding snippet I had accidentally reversed the organizationId and apiKey. Doh!
I am using SwiftUI instead of UIKit, and SPM instead of CocoaPods, so I cannot strictly follow your example. What do you mean by the wrong request code?
For version 2.0 I plan to add context completion. If you like I can probably share my entire Xcode project, but for now here’s a snippet from my working 1.0 code, which only does basic Q&A chat:
func sendMessage(message: String) {
print("sendMessage->message: \(message)")
let chat: [ChatMessage] = [
ChatMessage(role: .system, content: "You are a helpful assistant."),
ChatMessage(role: .user, content: message)
]
Task {
var finalResponse = "No reply"
do {
let chatParameters = ChatParameters(model: "gpt-3.5-turbo", messages: chat)
let chatCompletion = try await openAI.generateChatCompletion(
parameters: chatParameters
)
self.responseText = chatCompletion.choices[0].message.content
if let reply = self.responseText {
finalResponse = reply
}
self.messageText = ""
print("sendMessage->finalResponse: \(finalResponse)")
withAnimation {
messages.append("[USER]" + message)
withAnimation {
messages.append(finalResponse)
}
}
} catch {
print("ERROR DETAILS - \(error)")
}
}
}