SwiftOpenAI
is a powerful and easy-to-use Swift SDK designed to seamlessly integrate with OpenAI's API
. The main goal of this SDK is to simplify the process of accessing and interacting with OpenAI's cutting-edge AI models, such as GPT-4, GPT-3, and future models, all within your Swift applications.
Open Xcode and open the Swift Package Manager
section, then paste the Github URL from this repository (Copy -> https://github.com/SwiftBeta/SwiftOpenAI.git) to install the Package in your project.
![]() |
![]() |
Using SwiftOpenAI` is simple and straightforward. Follow these steps to start interacting with OpenAI's API in your Swift project:
Import SwiftOpenAI
var openAI = SwiftOpenAI(apiKey: "YOUR-API-KEY")
List and describe the various models available in the API. You can refer to the Models documentation to understand what models are available and the differences between them.
do {
let modelList = try await openAI.listModels()
print(modelList)
} catch {
print("Error: \(error)")
}
Given a prompt, the model will return one or more predicted completions, and can also return the probabilities of alternative tokens at each position.
let prompt = "Once upon a time, in a land far, far away,"
let optionalParameters = CompletionsOptionalParameters(prompt: prompt, maxTokens: 50, temperature: 0.7, n: 1)
do {
let completions = try await openAI.completions(model: .gpt3_5(.text_davinci_003), optionalParameters: optionalParameters)
print(completions)
} catch {
print("Error: \(error)")
}
Given a chat conversation, the model will return a chat completion response.
let messages: [MessageChatGPT] = [
MessageChatGPT(text: "You are a helpful assistant.", role: .system),
MessageChatGPT(text: "Who won the world series in 2020?", role: .user)
]
let optionalParameters = ChatCompletionsOptionalParameters(temperature: 0.7, stream: true, maxTokens: 50)
do {
let stream = try await openAI.createChatCompletionsStream(model: .gpt4(.base), messages: messages, optionalParameters: optionalParameters)
for try await response in stream {
print(response)
}
} catch {
print("Error: \(error)")
}
Given a chat conversation, the model will return a chat completion response.
let messages: [MessageChatGPT] = [
MessageChatGPT(text: "You are a helpful assistant.", role: .system),
MessageChatGPT(text: "Who won the world series in 2020?", role: .user)
]
let optionalParameters = ChatCompletionsOptionalParameters(temperature: 0.7, maxTokens: 50)
do {
let chatCompletions = try await openAI.createChatCompletions(model: .gpt4(.base), messages: messages, optionalParameters: optionalParameters)
print(chatCompletions)
} catch {
print("Error: \(error)")
}
Given a prompt and an instruction, the model will return an edited version of the prompt.
let inputText = "The car have four weels."
let instruction = "Please correct any grammatical errors in the text."
do {
let edits = try await openAI.edits(model: .edit(.text_davinci_edit_001), input: inputText, instruction: instruction)
print(edits)
} catch {
print("Error: \(error)")
}
Given a prompt and/or an input image, the model will generate a new image.
do {
let images = try await openAI.createImages(prompt: prompt,
numberOfImages: 4,
size: .s1024)
print(images)
} catch {
print("Error: \(error)")
}
Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms.
let inputText = "Embeddings are a numerical representation of text."
do {
let embeddings = try await openAI.embeddings(model: .embedding(.text_embedding_ada_002), input: inputText)
print(embeddings)
} catch {
print("Error: \(error)")
}
Given a input text, outputs if the model classifies it as violating OpenAI's content policy.
let inputText = "Some potentially harmful or explicit content."
do {
let moderationResults = try await openAI.moderations(input: inputText)
print(moderationResults)
} catch {
print("Error: \(error)")
}
Here you have a full example using SwiftUI:
The createChatCompletions
method allows you to interact with the OpenAI API by generating chat-based completions. Provide the necessary parameters to customize the completions, such as model, messages, and other optional settings.
import SwiftUI
import SwiftOpenAI
struct ContentView: View {
var openAI = SwiftOpenAI(apiKey: "YOUR-API-KEY")
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundColor(.accentColor)
Text("Hello, world!")
}
.padding()
.onAppear {
Task {
do {
for try await newMessage in try await openAI.createChatCompletionsStream(model: .gpt3_5(.turbo),
messages: [.init(text: "Generate the Hello World in Swift for me", role: .user)],
optionalParameters: .init(stream: true)) {
print("New Message Received: \(newMessage) ")
}
} catch {
print(error)
}
}
}
}
}
The createChatCompletions
method allows you to interact with the OpenAI API by generating chat-based completions. Provide the necessary parameters to customize the completions, such as model, messages, and other optional settings.
import SwiftUI
import SwiftOpenAI
struct ContentView: View {
var openAI = SwiftOpenAI(apiKey: "YOUR-API-KEY")
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundColor(.accentColor)
Text("Hello, world!")
}
.padding()
.onAppear {
Task {
do {
let result = try await openAI.createChatCompletions(model: .gpt3_5(.turbo),
messages: [.init(text: "Generate the Hello World in Swift for me", role: .user)])
print(result)
} catch {
print(error)
}
}
}
}
}
MIT License
Copyright 2023 SwiftBeta
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
link |
Stars: 41 |
Last commit: 1 week ago |
Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics