• This repository has been archived on 03/Dec/2022
  • Stars
    star
    181
  • Rank 205,507 (Top 5 %)
  • Language
    Swift
  • License
    MIT License
  • Created about 3 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Swift client for the OpenAI API.

OpenAI

CI

Warning This project is no longer being maintained.

The project was originally developed for a version of the OpenAI API that was deprecated on June 3, 2022 and removed on December 3, 2022. See the announcement for more information.

The current code requires significant updates in order to work with the current OpenAI API, but there are no plans to make the necessary changes at this time.

A Swift client for the OpenAI API.

Requirements

  • Swift 5.3+
  • An OpenAI API Key

Example Usage

Base Series

Our base GPT-3 models can understand and generate natural language. We offer four base models called davinci, curie, babbage, and ada with different levels of power suitable for different tasks.

Completions

import OpenAI

let apiKey: String // required
let client = Client(apiKey: apiKey)

let prompt = "Once upon a time"

client.completions(engine: .davinci,
                   prompt: prompt,
                   numberOfTokens: ...5,
                   numberOfCompletions: 1) { result in
    guard case .success(let completions) = result else { return }

    completions.first?.choices.first?.text // " there was a girl who"
}

Searches

import OpenAI

let apiKey: String // required
let client = Client(apiKey: apiKey)

let documents: [String] = [
    "White House",
    "hospital",
    "school"
]

let query = "president"

client.search(engine: .davinci,
              documents: documents,
              query: query) { result in
    guard case .success(let searchResults) = result else { return }
    searchResults.max()?.document // 0 (for "White House")
}

Classifications

import OpenAI

let apiKey: String // required
let client = Client(apiKey: apiKey)

let query = "It is a raining day :("

let examples: [(String, label: String)] = [
    ("A happy moment", label: "Positive"),
    ("I am sad.", label: "Negative"),
    ("I am feeling awesome", label: "Positive")
]

let labels = ["Positive", "Negative", "Neutral"]

client.classify(engine: .curie,
                query: query,
                examples: examples,
                labels: labels,
                searchEngine: .ada) { result in
    guard case .success(let classification) = result else { return }

    classification.label // "Negative"
}

Answers

import OpenAI

let apiKey: String // required
let client = Client(apiKey: apiKey)

let documents: [String] = [
    "Puppy A is happy.",
    "Puppy B is sad."
]

let question = "which puppy is happy?"

let examples: (context: String, [(question: String, answer: String)]) = (
    context: "In 2017, U.S. life expectancy was 78.6 years.",
    [
        (question: "What is human life expectancy in the United States?", answer: "78 years.")
    ]
)

client.answer(engine: .curie,
              question: question,
              examples: examples,
              documents: documents,
              searchEngine: .ada,
              stop: ["\n", "<|endoftext|>"]) { result in
    guard case .success(let response) = result else { return }

    response.answers.first // "puppy A."
}

Codex

The Codex models are descendants of our base GPT-3 models that can understand and generate code. Their training data contains both natural language and billions of lines of public code from GitHub.

import OpenAI

// `Engine.ID` provides cases for the
// `ada`, `babbage`, `curie`, and `davinci` engines.
// You can add convenience APIs for other engines
// by defining computed type properties in an extension.
extension Engine.ID {
    static var davinciCodex: Self = "code-davinci-002"
}

let apiKey: String // required
let client = Client(apiKey: apiKey)

let prompt = #"""
// Translate this function from Swift into Objective-C
// Swift

let numbers = [Int](1...10)
let evens = numbers.filter { $0 % 2 == 0 }
let sumOfEvens = evens.reduce(0, +)

// Objective-C

"""#

client.completions(engine: .davinciCodex,
                   prompt: prompt,
                   sampling: .temperature(0.0),
                   numberOfTokens: ...256,
                   numberOfCompletions: 1,
                   echo: false,
                   stop: ["//"],
                   presencePenalty: 0.0,
                   frequencyPenalty: 0.0,
                   bestOf: 1) { result in
    guard case .success(let completions) = result else { fatalError("\(result)") }

    for choice in completions.flatMap(\.choices) {
        print("\(choice.text)")
    }
}
// Prints the following code:
// ```
// NSArray *numbers = @[@1, @2, @3, @4, @5, @6, @7, @8, @9, @10];
// NSArray *evens = [numbers filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self % 2 == 0"]];
// NSInteger sumOfEvens = [[evens valueForKeyPath:@"@sum.self"] integerValue];
// ```

Instruct Series

The Instruct models share our base GPT-3 models’ ability to understand and generate natural language, but they’re better at understanding and following your instructions. You simply tell the model what you want it to do, and it will do its best to fulfill your instructions.

import OpenAI

let apiKey: String // required
let client = Client(apiKey: apiKey)

let prompt = "Describe the Swift programming language in a few sentences."

client.completions(engine: "davinci-instruct-beta",
                   prompt: prompt,
                   sampling: .temperature(0.0),
                   numberOfTokens: ...100,
                   numberOfCompletions: 1,
                   stop: ["\n\n"],
                   presencePenalty: 0.0,
                   frequencyPenalty: 0.0,
                   bestOf: 1) { result in
    guard case .success(let completions) = result else { fatalError("\(result)") }

    for choice in completions.flatMap(\.choices) {
        print("\(choice.text)")
    }
}
// Prints the following:
// "Swift is a general-purpose programming language that was developed by Apple Inc. for iOS and OS X development. Swift is designed to work with Apple's Cocoa and Cocoa Touch frameworks and the large body of existing Objective-C code written for Apple products. Swift is intended to be more resilient to erroneous code (such as buffer overflow errors) and better support concurrency (such as multi-threading) than Objective-C."

Content Filter

The content filter aims to detect generated text that could be sensitive or unsafe coming from the API. It's currently in beta mode and has three ways of classifying text β€” as safe, sensitive, or unsafe. The filter will make mistakes and we have currently built it to err on the side of caution, thus, resulting in higher false positives.

import OpenAI

let apiKey: String // required
let client = Client(apiKey: apiKey)

let prompt = "I know it's an unpopular political opinion to hold, but I think that..."

client.completions(engine: "content-filter-alpha-c4",
                   prompt: "<|endoftext|>\(prompt)\n--\nLabel:",
                   sampling: .temperature(0.0),
                   numberOfTokens: ...1,
                   numberOfCompletions: 1,
                   echo: false,
                   stop: ["<|endoftext|>[prompt]\n--\nLabel:"],
                   presencePenalty: 0.0,
                   frequencyPenalty: 0.0,
                   bestOf: 1) { result in
    guard case .success(let completions) = result else { fatalError("\(result)") }

    if let text = completions.flatMap(\.choices).first?.text.trimmingCharacters(in: .whitespacesAndNewlines) {
        switch Int(text) {
        case 0:
            print("Safe")
        case 1:
            print("Sensitive")
            // This means that the text could be talking about a sensitive topic, something political, religious, or talking about a protected class such as race or nationality.
        case 2:
            print("Unsafe")
            // This means that the text contains profane language, prejudiced or hateful language, something that could be NSFW, or text that portrays certain groups/people in a harmful manner.
        default:
            print("unexpected token: \(text)")
        }
    }
}
// Prints "Sensitive"

Installation

Swift Package Manager

Add the OpenAI package to your target dependencies in Package.swift:

// swift-tools-version:5.3
import PackageDescription

let package = Package(
  name: "YourProject",
  dependencies: [
    .package(
        url: "https://github.com/mattt/OpenAI",
        from: "0.1.3"
    ),
  ]
)

Then run the swift build command to build your project.

License

MIT

Contact

Mattt (@mattt)

More Repositories

1

Ono

A sensible way to deal with XML & HTML for iOS & macOS
Objective-C
2,603
star
2

GroundControl

Remote configuration for iOS
Objective-C
1,946
star
3

CargoBay

The Essential StoreKit Companion
Objective-C
1,770
star
4

Euler

Swift Custom Operators for Mathematical Notation
Swift
1,156
star
5

AnimatedGIFImageSerialization

Complete Animated GIF Support for iOS, with Functions, NSJSONSerialization-style Class, and (Optional) UIImage Swizzling
Objective-C
1,087
star
6

TransformerKit

A block-based API for NSValueTransformer, with a growing collection of useful examples.
Objective-C
848
star
7

Navajo

Password Validator & Strength Evaluator
Objective-C
836
star
8

SkyLab

Multivariate & A/B Testing for iOS and Mac
Objective-C
790
star
9

Orbiter

Push Notification Registration for iOS
Objective-C
673
star
10

NSEtcHosts

/etc/hosts with NSURLProtocol
Objective-C
666
star
11

Chroma-Hash

A colorful visualization of password field input
JavaScript
624
star
12

rack-scaffold

Automatically generate REST APIs from Core Data models
Ruby
528
star
13

sinatra-param

Parameter Validation & Type Coercion for Sinatra
Ruby
519
star
14

InflectorKit

Efficiently Singularize and Pluralize Strings
Objective-C
476
star
15

NSSortDescriptor-WilsonRank

The Correct Way To Rank Up/Down Voted Items
Objective-C
433
star
16

Antenna

Extensible Remote Logging for iOS
Objective-C
424
star
17

Godzippa

Godzippa! - GZip Compression / Decompression Category for NSData
Objective-C
424
star
18

CommonMarkAttributedString

Create NSAttributedStrings from Markdown Text
Swift
421
star
19

rack-push-notification

A Rack-mountable webservice for managing push notifications
Ruby
378
star
20

TTTLocalizedPluralString

NSLocalizedString with a Count Argument
Objective-C
378
star
21

CupertinoYankee

An NSDate Category With Locale-Aware Calculations for Beginning & End of Day, Week, Month, and Year
Objective-C
305
star
22

WebPImageSerialization

Complete WebP Support for iOS, with Functions, NSJSONSerialization-style Class, and (Optional) UIImage Swizzling
C
282
star
23

CHChromaHashView

A classic password visualization concept, ported to iOS
Objective-C
273
star
24

Xcode-Licensed-Templates

Minimal Xcode Templates for Open Source Developers
255
star
25

GeoJSONSerialization

Encode & Decode Between GeoJSON & MapKit Shapes
Objective-C
231
star
26

terminal-share

Command Line & Ruby Interface to Mac OS X Sharing Services
Objective-C
228
star
27

TTTRandomizedEnumerator

Mix things up with your collection classes with style and class (well, a category, but you get the idea).
Objective-C
223
star
28

BritishInvasion

Localise Your .m Files, For Queen And Country πŸ‡¬πŸ‡§
Objective-C
212
star
29

AnyJSON

Encode / Decode JSON By Any Means Possibleβ„’
Objective-C
119
star
30

MsgPackSerialization

MsgPack Serialization for Objective-C
C
96
star
31

Morse.js

A jQuery Plugin to annotate text with Morse Code
JavaScript
95
star
32

rack-smart-app-banner

Rack middleware to automatically include code for Smart App Banners on iOS
Ruby
85
star
33

vCardSerialization

Encodes and decodes between vCard files and AddressBook records.
Objective-C
69
star
34

UIFontSerialization

Encode and decode between UIFont and Postscript font data
Objective-C
64
star
35

rack-http-logger

Log metrics from HTTP request parameters according to l2met conventions
Ruby
57
star
36

rack-passbook

Rack middleware that provides Passbook web service endpoints.
Ruby
52
star
37

rack-in-app-purchase

Rack middleware that manages products for in-app-purchases and verifies receipts.
Ruby
51
star
38

swift-package-registry-oas

OpenAPI Specification for proposed Swift Package Registry web service
Swift
41
star
39

core_data

Parse Core Data Model (.xcdatamodel) Files
Ruby
39
star
40

swift-registry

A reference implementation of the Swift Package Registry, written in Swift and using Git as a database / transparent log.
Swift
37
star
41

rack-subdomain

Rack middleware to transparently route requests with a subdomain to a specified path with substitutions
Ruby
37
star
42

rack-newsstand

Automatically generate webservice endpoints for Newsstand
Ruby
33
star
43

rack-remote-configuration

Serve property list or JSON configuration files
Ruby
24
star
44

commoditize

A command-line utility for macOS that mounts a Docker container image as an external disk image.
Shell
20
star
45

swift-package-sbom

A software bill of materials (SBoM) generator for Swift packages
Swift
17
star
46

vscode-unicorn

πŸ¦„πŸ’¬ A Visual Studio Code extension that adds a status bar entry showing Unicode data for the currently selected character.
TypeScript
15
star
47

Sonic-Hash

A melodic Sonification of password field input
JavaScript
14
star
48

NFPA704View

UIView Subclass for NFPA 704 "Fire Diamonds"
Objective-C
13
star
49

swift-package-registry-codeartifact

A basic implementation of the Swift package registry interface that uses AWS CodeArtifact as a backend for package releases and assets.
TypeScript
10
star
50

rack-heroku-no-such-app

Rack middleware to prevent loading from `*.heroku.com` / `*.herokuapp.com` addresses
Ruby
9
star
51

glitz

Glitz adds ANSI-colorized glamour to your terminal output
Ruby
9
star
52

replicate-swift

Unofficial Swift client for the Replicate API
Swift
8
star
53

swift-package-serialization-lambda

Swift
7
star
54

cog-replicate-logo-generator

Python
5
star
55

rack-typekit

Rack middleware to automatically inject Typekit into webpages
Ruby
4
star
56

CycloneDX

Swift
4
star
57

swift-registry-benchmark-harness

A harness for benchmarking the performance of building a project with Swift Package Manager using the new package registry interface.
Ruby
4
star
58

documentation-block

[WIP] View symbol documentation for a file
TypeScript
3
star
59

OpenAPIKit

Codable Swift OpenAPI implementation.
Swift
2
star