Swiftpack.co - SwiftBeta/SwiftOpenAI as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by SwiftBeta.
SwiftBeta/SwiftOpenAI 1.2.0
OpenAI API build with Swift ❤️
⭐️ 64
🕓 1 week ago
iOS macOS
.package(url: "https://github.com/SwiftBeta/SwiftOpenAI.git", from: "1.2.0")

🧰 SwiftOpenAI (OpenaAI SDK)

Portada Build Status
Twitter Follow
Youtube Views YouTube Channel Subscribers
GitHub Stars GitHub Followers
Discord

Introduction

SwiftOpenAI is a (community-maintained) 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.

SwiftOpenAI Demo

⚙️ Installation

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.

Installation-1 Installation-2

💻 Usage

Using SwiftOpenAI` is simple and straightforward. Follow these steps to start interacting with OpenAI's API in your Swift project:

  1. Import SwiftOpenAI
  2. var openAI = SwiftOpenAI(apiKey: "YOUR-API-KEY")

Secure your API Key using a .plist

To use SwiftOpenAI safely without hardcoding your API key, follow these steps:

  • Create a .plist file: Add a new .plist file to your project, e.g., Config.plist.
  • Add your API Key: Inside Config.plist, add a new row with the Key OpenAI_API_Key and paste your API key in the Value field.
  • Load the API Key: Use the following code to load your API key from the .plist:
import Foundation
import SwiftOpenAI

struct Config {
    static var openAIKey: String {
        get {
            guard let filePath = Bundle.main.path(forResource: "Config", ofType: "plist") else {
                fatalError("Couldn't find file 'Config.plist'.")
            }
            let plist = NSDictionary(contentsOfFile: filePath)
            guard let value = plist?.object(forKey: "OpenAI_API_Key") as? String else {
                fatalError("Couldn't find key 'OpenAI_API_Key' in 'Config.plist'.")
            }
            return value
        }
    }
}

var openAI = SwiftOpenAI(apiKey: Config.openAIKey)

Audio Text To Speech

Generates audio from the input text.

do {
    let input = "Hello, I'm SwiftBeta, a developer who in his free time tries to teach through his blog swiftbeta.com and his YouTube channel. Now I'm adding the OpenAI API to transform this text into audio"
    let data = try await openAI.createSpeech(model: .tts(.tts1), 
                                             input: input,
                                             voice: .alloy,
                                             responseFormat: .mp3,
                                             speed: 1.0)

    if let filePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("speech.mp3"), let data {
        do {
            try data.write(to: filePath)
            print("Audio file saved: \(filePath)")
        } catch {
            print("Error savind Audio file: \(error)")
        }
    }
} catch {
    print(error.localizedDescription)
}

Audio Transcriptions

Transcribes audio into the input language.

let fileData = // Data fromyour video, audio, etc
let model: OpenAITranscriptionModelType = .whisper

do {
    for try await newMessage in try await openAI.createTranscription(model: model,
                                                                    file: fileData,
                                                                    language: "en",
                                                                    prompt: "",
                                                                    responseFormat: .mp3,
                                                                    temperature: 1.0) {
        print("Received Transcription \(newMessage)")
        await MainActor.run {
            isLoading = false
            transcription = newMessage.text
        }
    }
} catch {
    print(error.localizedDescription)
}

Models

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)")
}

Completions

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(.turbo), optionalParameters: optionalParameters)
    print(completions)
} catch {
    print("Error: \(error)")
}

ChatCompletions with Stream

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)")
}

ChatCompletions without Stream

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)")
}

Create Image with DALL·E 3

Given a prompt and/or an input image, the model will generate a new image.

do {
    let image = try await openAI.createImages(model: .dalle(.dalle3),
                                               prompt: prompt,
                                               numberOfImages: 1,
                                               size: .s1024)
    print(image)                                               
} catch {
    print("Error: \(error)")
}

Embeddings

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)")
}

Moderations

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)")
}

Code Examples using the API

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.

1

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)
                }
            }
        }
    }
}

Another example

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.

2

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)
                }
            }
        }
    }
}

📝 License

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.

📬 CONTACT INFORMATION

[email protected]

twitter.com/swiftbeta_

youtube.com/@swiftbeta

GitHub

link
Stars: 65
Last commit: 2 weeks ago
Advertisement: IndiePitcher.com - Cold Email Software for Startups

Related Packages

Release Notes

2 weeks ago

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