OpenAISwift

repository·main·Indexed 23 days ago

https://github.com/adamrushy/openaiswift

A community-maintained Swift library providing a wrapper around OpenAI HTTP APIs for iOS and macOS developers. It supports integration of Chat, Completions, DALL·E, and Embeddings, featuring methods such as sendChat, sendCompletion, sendImages, sendEdits, sendModeration, and sendEmbeddings with support for both completion handlers and Swift concurrency (async/await).

Tokens
1.5K
Snippets
8
Records
9
Agent score
33%

What's inside OpenAISwift

  1. Install OpenAISwift via Swift Package Manager

    main

    Add the following dependency to your Package.swift file or via the Xcode interface to integrate the library using Swift Package Manager (SPM).

    .package(url: "https://github.com/adamrushy/OpenAISwift.git", from: "1.2.0")
  2. Edit text with `sendEdits`

    main

    Use sendEdits to modify existing text based on a prompt and an instruction using async/await.

    do {
        let result = try await openAI.sendEdits(
            with: "Improve the tone of this text.",
            model: .feature(.davinci),               // optional `OpenAIModelType`
            input: "I am resigning!"
        )
        // use result
    } catch {
        // ...
    }
  3. Get embeddings with `sendEmbeddings`

    main

    Use sendEmbeddings to get a vector representation of a given input string using async/await.

    do {
        let result = try await openAI.sendEmbeddings(
            with: "The food was delicious and the waiter..."
        )
        // use result
    } catch {
        // ...
    }
  4. Generate images with `sendImages`

    main

    Use sendImages to generate an image based on a text prompt using DALL·E. This method uses a completion handler.

    openAI.sendImages(with: "A 3d render of a rocket ship", numImages: 1, size: .size1024) { result in // Result<OpenAI, OpenAIError>
        switch result {
        case .success(let success):
            print(success.data.first?.url ?? "")
        case .failure(let failure):
            print(failure.localizedDescription)
        }
    }
  5. Predict text completions with `sendCompletion`

    main

    Use sendCompletion to predict completions for input text. The library supports both completion handlers and Swift concurrency (async/await).

    Completion Handler Example:

    openAI.sendCompletion(with: "Hello how are you") { result in // Result<OpenAI, OpenAIError>
        switch result {
        case .success(let success):
            print(success.choices.first?.text ?? "")
        case .failure(let failure):
            print(failure.localizedDescription)
        }
    }

    Async/Await Example with parameters:

    do {
        let result = try await openAI.sendCompletion(
            with: "What's your favorite color?",
            model: .gpt3(.davinci), // optional `OpenAIModelType`
            maxTokens: 16,          // optional `Int?`
            temperature: 1          // optional `Double?`
        )
        // use result
    } catch {
        // ...
    }
  6. Moderate text with `sendModeration`

    main

    Use sendModeration to classify text for moderation purposes using async/await.

    do {
        let result = try await openAI.sendModeration(
            with: "Some harmful text...",
            model: .moderation(.latest)     // optional `OpenAIModelType`
        )
        // use result
    } catch {
        // ...
    }
  7. Get chat responses with `sendChat`

    main

    Use sendChat to interact with chat models like ChatGPT (GPT-3.5) or GPT-4. You must provide an array of ChatMessage objects representing the conversation history.

    Async/Await Example:

    do {
        let chat: [ChatMessage] = [
            ChatMessage(role: .system, content: "You are a helpful assistant."),
            ChatMessage(role: .user, content: "Who won the world series in 2020?"),
            ChatMessage(role: .assistant, content: "The Los Angeles Dodgers won the World Series in 2020."),
            ChatMessage(role: .user, content: "Where was it played?")
        ]
    
        let result = try await openAI.sendChat(with: chat)
        // use result
    } catch {
        // ...
    }

    Advanced parameters for sendChat:

    do {
        let chat: [ChatMessage] = [...]
    
        let result = try await openAI.sendChat(
            with: chat,
            model: .chat(.chatgpt),         // optional `OpenAIModelType`
            user: nil,                      // optional `String?`
            temperature: 1,                 // optional `Double?`
            topProbabilityMass: 1,          // optional `Double?`
            choices: 1,                     // optional `Int?`
            stop: nil,                      // optional `[String]?`
            maxTokens: nil,                 // optional `Int?`
            presencePenalty: nil,           // optional `Double?`
            frequencyPenalty: nil,           // optional `Double?`
            logitBias: nil                  // optional `[Int: Double]?`
        )
        // use result
    } catch {
        // ...
    }