使用 Swift 访问 ChatGPT API
ChatGPTSwift
从 Swift 访问 ChatGPT“官方”API。适用于所有苹果平台。
支持的平台
- iOS/tvOS 15 及以上版本
- macOS 12 及更高版本
- 手表操作系统 8 及更高版本
Requirement
Register for API key from OpenAPI. Initialize with api key
let api = ChatGPTAPI(apiKey: "API_KEY")
Usage
There are 2 APIs: stream and normal
Stream
The server will stream data one by one until complete, the method which you can loop using For-Loop like so:AsyncThrowingStream
Task {
do {
let stream = try await api.sendMessageStream(text: "What is ChatGPT?")
for try await line in stream {
print(line)
}
} catch {
print(error.localizedDescription)
}
}
Normal
A normal HTTP request and response lifecycle. Server will send the complete text (it will take more time to response)
Task {
do {
let response = try await api.sendMessage(text: "What is ChatGPT?")
print(response)
} catch {
print(error.localizedDescription)
}
}