This library provides an
async/await API for access, so requires being compiled with Swift 5.5+.
Add this to your project with Swift Package Manager.
https://github.com/randombitsco/swift-openai-bitsfor the URL
Up to next major versionwith the current version value, or select
OpenAIBitstarget to your project.
dependencies: [ .package(url: "https://github.com/randombitsco/swift-openai-bits", from: "0.0.8"), ],
targets, add a dependency on the library to the relevant target:
.target( name: "MyTarget", dependencies: [ .product(name: "OpenAIBits", package: "swift-openai-bits"), ]),
Basic useage requires setting up a
Client instance, with an OpenAI API Key (and Organization key, if relevant):
import OpenAIBits let apiKey: String // your API key. Don't store this in code! let client = Client(apiKey: apiKey) // send a request to the API let result = try await client.call(...)
Completions are the core text generation call. Keep in mind it will use tokens from your account on every call.
let result = try await client.call(Completions( model: .text_davinci_002, prompt: "You complete", maxTokens: 50, temperature: 0.8 )) let choice = result.choices.first! print("Completion: \(choice.text)") print("[Used \(result.usage.totalTokens") tokens]")
Edits allow you to provide a starting
input and a an
instruction, and it will return a new result based on the input, modified according to the instruction.
let result = try await client.call(Edits( model: .text_davinci_002, input: """ We is going to the market. """, instruction: "Fix the grammar." )) let choice = result.choices.first! print("Edit: \(choice.text)") print("[Used \(result.usage.totalTokens") tokens]")
Along side the
Client is the
TokenEncoder. It is a
struct that can be used and reused, with two methods:
let encoder = TokenEncoder() let tokens: [Int] = encoder.encoder(text: "A sentence.") let text: String = encoder.decode(tokens: tokens) print("Tokens: \(tokens)") // Tokens: [32, 6827, 13] print("Text: \(text)") // Text: A sentence.