Skip to content

janodevorg/OpenAIClient

Repository files navigation

Swift MIT license

OpenAIClient

Full implementation of the OpenAI API in Swift.

Installation

let package = Package(
    ...
    dependencies: [
        .package(url: "[email protected]:janodevorg/OpenAIClient.git", from: "2.0.0")
    ],
    targets: [
        .target(
            name: "...",
            dependencies: [
                .product(name: "OpenAIClient", package: "OpenAIClient")
            ]
        )
    ]
)

Usage

To configure the client:

let client = OpenAIClient(log: log).configure(apiKey: "API_KEY", companyKey: "ORGANIZATION_ID")

To request a completion:

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 request a streaming completion as an AsyncStream:

let request = CreateCompletionRequest(
    model: Model.davinci002.id,
    prompt: .string("hello there chatgpt!")
)
let stream = try client.streamingCompletion(request: request)
for await chunk in stream {
    print(chunk.map { $0.firstChoice }.joined())
}

To request a streaming completion:

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. Keep the streamClient instance alive while streaming results.

Example

Check Examples/SwiftAI for a CLI tool that uses swift-argument-parser. I only implemented completion and streaming completion but it was quite easy –now I’m wondering if I should go on or ask ChatGPT to do it.

Integration tests

The folder Tests/Integration 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 credentials in the terminal. This creates a file at Tests/Integration/Resources/credentials.json that is ignored by .gitignore:

{
    "apiKey": "sk-cafebabedeadbeef",
    "organizationId": "org-cafebabedeadbeef",
}

Links of interest

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.