Swift implementation of the OpenAI API partially generated from the OpenAI definition. All features implemented.
let package = Package(
...
dependencies: [
.package(url: "git@github.com:OpenAIClient/OpenAIClient.git", from: "1.0.0")
],
targets: [
.target(
name: "...",
dependencies: [
.product(name: "OpenAIClient", package: "OpenAIClient")
]
)
]
)
To configure the client:
let client = OpenAIClient(log: log)
client.configure(apiKey: "API_KEY", companyKey: "ORGANIZATION_ID")
To send a message:
let prompt = "hello there chatgpt!"
let response = try await client.completions(request: .init(model: Model.davinci003.id, prompt: .string(prompt)))
print("response: \(response.choices.first?.text)")
To send a message and receive a response with streaming:
let prompt = "hello there chatgpt!"
let streamClient = try client.streamingChatCompletion(
streamListener: { print("chunk \($0)") },
modelId: Model.gpt35turbo.id,
conversation: [ChatCompletionRequestMessage(role: .user, content: prompt)]
)
streamClient.start()
Call stop()
to stop streaming or wait until streamClient.state == .shutdown
.
The folder sources/integration-tests contains tests that make network calls. They are disabled by default because they need valid credentials and may alter data in your organization. I suggest you run them manually for debugging or to see this library in action.
To input your credentials run make keys
in the terminal. The resulting file will be ignored by .gitignore
.
OpenAI
Code used in this library
- CreateAPI - Code generator for OpenAPI definitions.
- Get - Network client used in the generated package.
- LDSwiftEventSource A Server Side Events client.
- Log - A minimal log utility.
- MultipartFormEncoder - MultipartFormEncoder by Sami Samhuri.
- OpenAIAPI - A Swift network client generated from the OpenAI OpenAPI definition.