项目作者: mattt

项目描述 :
A Swift client for the OpenAI API.
高级语言: Swift
项目地址: git://github.com/mattt/OpenAI.git
创建时间: 2021-04-27T12:18:39Z
项目社区:https://github.com/mattt/OpenAI

开源协议:MIT License

下载


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

  1. import OpenAI
  2. let apiKey: String // required
  3. let client = Client(apiKey: apiKey)
  4. let prompt = "Once upon a time"
  5. client.completions(engine: .davinci,
  6. prompt: prompt,
  7. numberOfTokens: ...5,
  8. numberOfCompletions: 1) { result in
  9. guard case .success(let completions) = result else { return }
  10. completions.first?.choices.first?.text // " there was a girl who"
  11. }

Searches

  1. import OpenAI
  2. let apiKey: String // required
  3. let client = Client(apiKey: apiKey)
  4. let documents: [String] = [
  5. "White House",
  6. "hospital",
  7. "school"
  8. ]
  9. let query = "president"
  10. client.search(engine: .davinci,
  11. documents: documents,
  12. query: query) { result in
  13. guard case .success(let searchResults) = result else { return }
  14. searchResults.max()?.document // 0 (for "White House")
  15. }

Classifications

  1. import OpenAI
  2. let apiKey: String // required
  3. let client = Client(apiKey: apiKey)
  4. let query = "It is a raining day :("
  5. let examples: [(String, label: String)] = [
  6. ("A happy moment", label: "Positive"),
  7. ("I am sad.", label: "Negative"),
  8. ("I am feeling awesome", label: "Positive")
  9. ]
  10. let labels = ["Positive", "Negative", "Neutral"]
  11. client.classify(engine: .curie,
  12. query: query,
  13. examples: examples,
  14. labels: labels,
  15. searchEngine: .ada) { result in
  16. guard case .success(let classification) = result else { return }
  17. classification.label // "Negative"
  18. }

Answers

  1. import OpenAI
  2. let apiKey: String // required
  3. let client = Client(apiKey: apiKey)
  4. let documents: [String] = [
  5. "Puppy A is happy.",
  6. "Puppy B is sad."
  7. ]
  8. let question = "which puppy is happy?"
  9. let examples: (context: String, [(question: String, answer: String)]) = (
  10. context: "In 2017, U.S. life expectancy was 78.6 years.",
  11. [
  12. (question: "What is human life expectancy in the United States?", answer: "78 years.")
  13. ]
  14. )
  15. client.answer(engine: .curie,
  16. question: question,
  17. examples: examples,
  18. documents: documents,
  19. searchEngine: .ada,
  20. stop: ["\n", "<|endoftext|>"]) { result in
  21. guard case .success(let response) = result else { return }
  22. response.answers.first // "puppy A."
  23. }

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.

  1. import OpenAI
  2. // `Engine.ID` provides cases for the
  3. // `ada`, `babbage`, `curie`, and `davinci` engines.
  4. // You can add convenience APIs for other engines
  5. // by defining computed type properties in an extension.
  6. extension Engine.ID {
  7. static var davinciCodex: Self = "code-davinci-002"
  8. }
  9. let apiKey: String // required
  10. let client = Client(apiKey: apiKey)
  11. let prompt = #"""
  12. // Translate this function from Swift into Objective-C
  13. // Swift
  14. let numbers = [Int](1...10)
  15. let evens = numbers.filter { $0 % 2 == 0 }
  16. let sumOfEvens = evens.reduce(0, +)
  17. // Objective-C
  18. """#
  19. client.completions(engine: .davinciCodex,
  20. prompt: prompt,
  21. sampling: .temperature(0.0),
  22. numberOfTokens: ...256,
  23. numberOfCompletions: 1,
  24. echo: false,
  25. stop: ["//"],
  26. presencePenalty: 0.0,
  27. frequencyPenalty: 0.0,
  28. bestOf: 1) { result in
  29. guard case .success(let completions) = result else { fatalError("\(result)") }
  30. for choice in completions.flatMap(\.choices) {
  31. print("\(choice.text)")
  32. }
  33. }
  34. // Prints the following code:
  35. //

// 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];
// ```

  1. ### Instruct Series
  2. > The [Instruct] models share our base GPT-3 models ability to
  3. > understand and generate natural language,
  4. > but theyre better at understanding and following your instructions.
  5. > You simply tell the model what you want it to do,
  6. > and it will do its best to fulfill your instructions.
  7. ```swift
  8. import OpenAI
  9. let apiKey: String // required
  10. let client = Client(apiKey: apiKey)
  11. let prompt = "Describe the Swift programming language in a few sentences."
  12. client.completions(engine: "davinci-instruct-beta",
  13. prompt: prompt,
  14. sampling: .temperature(0.0),
  15. numberOfTokens: ...100,
  16. numberOfCompletions: 1,
  17. stop: ["\n\n"],
  18. presencePenalty: 0.0,
  19. frequencyPenalty: 0.0,
  20. bestOf: 1) { result in
  21. guard case .success(let completions) = result else { fatalError("\(result)") }
  22. for choice in completions.flatMap(\.choices) {
  23. print("\(choice.text)")
  24. }
  25. }
  26. // Prints the following:
  27. // "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.

  1. import OpenAI
  2. let apiKey: String // required
  3. let client = Client(apiKey: apiKey)
  4. let prompt = "I know it's an unpopular political opinion to hold, but I think that..."
  5. client.completions(engine: "content-filter-alpha-c4",
  6. prompt: "<|endoftext|>\(prompt)\n--\nLabel:",
  7. sampling: .temperature(0.0),
  8. numberOfTokens: ...1,
  9. numberOfCompletions: 1,
  10. echo: false,
  11. stop: ["<|endoftext|>[prompt]\n--\nLabel:"],
  12. presencePenalty: 0.0,
  13. frequencyPenalty: 0.0,
  14. bestOf: 1) { result in
  15. guard case .success(let completions) = result else { fatalError("\(result)") }
  16. if let text = completions.flatMap(\.choices).first?.text.trimmingCharacters(in: .whitespacesAndNewlines) {
  17. switch Int(text) {
  18. case 0:
  19. print("Safe")
  20. case 1:
  21. print("Sensitive")
  22. // 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.
  23. case 2:
  24. print("Unsafe")
  25. // 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.
  26. default:
  27. print("unexpected token: \(text)")
  28. }
  29. }
  30. }
  31. // Prints "Sensitive"

Installation

Swift Package Manager

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

  1. // swift-tools-version:5.3
  2. import PackageDescription
  3. let package = Package(
  4. name: "YourProject",
  5. dependencies: [
  6. .package(
  7. url: "https://github.com/mattt/OpenAI",
  8. from: "0.1.3"
  9. ),
  10. ]
  11. )

Then run the swift build command to build your project.

License

MIT

Contact

Mattt (@mattt)