Swiftpack.co - dylanshine/openai-kit as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by dylanshine.
dylanshine/openai-kit 1.4.1
A community Swift package used to interact with the OpenAI API
⭐️ 322
🕓 12 hours ago
iOS macOS
.package(url: "https://github.com/dylanshine/openai-kit.git", from: "1.4.1")



OpenAIKit is a Swift package used to communicate with the OpenAI API.


Add the dependency to Package.swift:

dependencies: [
    .package(url: "https://github.com/dylanshine/openai-kit.git", from: "1.0.0")
targets: [
    .target(name: "App", dependencies: [
        .product(name: "OpenAIKit", package: "openai-kit"),

It is encouraged to use environment variables to inject the OpenAI API key, instead of hardcoding it in the source code.

# .env


⚠️ OpenAI strongly recommends developers of client-side applications proxy requests through a separate backend service to keep their API key safe. API keys can access and manipulate customer billing, usage, and organizational data, so it's a significant risk to expose them.

Create a OpenAIKit.Client using a httpClient and configuration.

var apiKey: String {

var organization: String {


let httpClient = HTTPClient(eventLoopGroupProvider: .createNew)
defer {
    // it's important to shutdown the httpClient after all requests are done, even if one failed. See: https://github.com/swift-server/async-http-client
    try? httpClient.syncShutdown()
let configuration = Configuration(apiKey: apiKey, organization: organization)

let openAIClient = OpenAIKit.Client(httpClient: httpClient, configuration: configuration)

Using the API

The OpenAIKit.Client implements a handful of methods to interact with the OpenAI API:

import OpenAIKit

let completion = try await openAIClient.completions.create(
    model: Model.GPT3.davinci,
    prompts: ["Write a haiku"]

What's Implemented

Error handling

If the request to the API failed for any reason an OpenAIKit.APIErrorResponse is thrown. Simply ensure you catch errors thrown like any other throwing function

do {
} catch let error as APIErrorResponse {


Stars: 332
Last commit: Yesterday
jonrohan Something's broken? Yell at me @ptrpavlik. Praise and feedback (and money) is also welcome.

Related Packages

Release Notes

OpenAIKit 1.4.1

Add GPT4 Support thanks to @ronaldmannak

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics