Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
97 commits
Select commit Hold shift + click to select a range
724eb17
Added ImageEdit and ImageVariations calls
MarkHoath Jul 16, 2023
0e02e20
Added Comments
MarkHoath Jul 16, 2023
71a6371
removed imageError
MarkHoath Jul 16, 2023
f5a33dc
Change Data to String for edits
MarkHoath Jul 16, 2023
7d764f5
Fixed Image and Mask to Strings not Data
MarkHoath Jul 16, 2023
92dc7e1
Add the correct formats for Edits and Variations
MarkHoath Jul 16, 2023
a14c801
Back to Data for the Data type!
MarkHoath Jul 16, 2023
3d0f485
Back to String (Data is base64 encoded)
MarkHoath Jul 16, 2023
019ccc4
prints added for debugging
MarkHoath Jul 16, 2023
3b9a97f
multipart forms
MarkHoath Jul 16, 2023
64a580c
DALLE...
MarkHoath Jul 16, 2023
99bab81
debugging
MarkHoath Jul 16, 2023
108fb24
Prompt Fix
MarkHoath Jul 16, 2023
51d8dca
getting closer
MarkHoath Jul 16, 2023
953abde
one more...
MarkHoath Jul 16, 2023
78fc069
syntax
MarkHoath Jul 16, 2023
5ef24fe
fixed empty prompt
MarkHoath Jul 16, 2023
45e1327
final code
MarkHoath Jul 16, 2023
10f7eee
removed old structs
MarkHoath Jul 16, 2023
f021d4e
Removal of Identifiable
MarkHoath Jul 18, 2023
6cc1202
Update README.md
tysonwil Jul 21, 2023
db672df
Add explicit codable implementation to ChatMessage
marcoboerner Jul 31, 2023
0e7ae8e
fix problem on linux
underthestars-zhy Aug 18, 2023
d850bf0
pr by @marcoboerner
underthestars-zhy Aug 18, 2023
8ac1303
Reduced requirement to iOS 13
laszlotuss Aug 19, 2023
71994c0
Fixed error 2, ChatMessage Codable breaks auth
laszlotuss Aug 19, 2023
2f33fcd
Restored old init, but flagged deprecated
laszlotuss Aug 19, 2023
2c57dad
Refactoring and documenting id property in ChatMessage
marcoboerner Aug 19, 2023
d772242
Adding custom init from rawValue to OpenAIModelType
marcoboerner Aug 19, 2023
dc23218
Add compatible OpenAI model types
marcoboerner Sep 1, 2023
068359d
Update README.md
a-elnajjar Sep 12, 2023
4886eb6
Update README.md
a-elnajjar Sep 13, 2023
8b8c03b
Update README.md
a-elnajjar Sep 14, 2023
75192ad
add more sense to readme, fix 400 error because of id
astrokin Oct 15, 2023
db66252
improve error handling
astrokin Oct 16, 2023
34b9686
Merge pull request #5 from MarkHoath/main
MarkHoath Nov 9, 2023
d278ce8
Merge pull request #6 from tysonwil/patch-1
MarkHoath Nov 9, 2023
d81f042
Merge pull request #7 from marcoboerner/main
MarkHoath Nov 9, 2023
89b0522
Merge pull request #11 from astrokin/fix_400
MarkHoath Nov 9, 2023
5da2edf
Merge pull request #10 from a-elnajjar/a-elnajjar-patch-1
MarkHoath Nov 9, 2023
e881e72
Merge pull request #9 from laszlotuss/main
MarkHoath Nov 9, 2023
8245a52
Merge pull request #8 from underthestars-zhy/main
MarkHoath Nov 9, 2023
7751058
Merge pull request #12 from Swift-Almanac/marcoboerner
MarkHoath Nov 9, 2023
0241654
Merge branch 'main' into astrokin
MarkHoath Nov 9, 2023
f021a49
Merge pull request #13 from Swift-Almanac/astrokin
MarkHoath Nov 9, 2023
2e8409e
Merge branch 'main' into underthestars-zhy
MarkHoath Nov 9, 2023
dd94ede
Merge pull request #14 from Swift-Almanac/underthestars-zhy
MarkHoath Nov 9, 2023
c6b4241
Merge branch 'main' into laszlotuss
MarkHoath Nov 9, 2023
4f46e4c
Merge pull request #15 from Swift-Almanac/laszlotuss
MarkHoath Nov 9, 2023
965b03b
Merge branch 'main' into a-einajar
MarkHoath Nov 9, 2023
b4af8d1
Merge pull request #16 from Swift-Almanac/a-einajar
MarkHoath Nov 9, 2023
20c005a
Merge branch 'main' into markhoath
MarkHoath Nov 9, 2023
b8a99dd
Merge pull request #17 from Swift-Almanac/markhoath
MarkHoath Nov 9, 2023
d5337d9
Merge branch 'main' into tysonwil
MarkHoath Nov 9, 2023
7f0a25a
Merge pull request #18 from Swift-Almanac/tysonwil
MarkHoath Nov 9, 2023
3f720f4
Fixed Identifiable and Compile Issue
MarkHoath Nov 9, 2023
65371e0
Merge pull request #19 from Swift-Almanac/ChatMessage
MarkHoath Nov 9, 2023
8516e41
Updates
MarkHoath Nov 10, 2023
cea73c3
Files Completed.
MarkHoath Nov 14, 2023
afce3df
Fine_tuning Completed.
MarkHoath Nov 14, 2023
c8cd977
Models Completed.
MarkHoath Nov 15, 2023
c32e033
changes to allow for Query Items and make Body Optional
MarkHoath Nov 15, 2023
0df40bf
Dev Conference beta
MarkHoath Nov 16, 2023
aaccbc4
Merge pull request #22 from Swift-Almanac/ChatMessage
MarkHoath Nov 16, 2023
5966e3c
Merge pull request #25 from Swift-Almanac/dev_conf_beta
MarkHoath Dec 23, 2023
b7b0166
Extend URL Session Time Interval
MarkHoath Jan 5, 2024
aa5dba2
Latest Updates - 8 Feb 2024
MarkHoath Feb 7, 2024
f2745a1
Merge pull request #26 from Swift-Almanac/ChatMessage
MarkHoath Feb 7, 2024
e3a9210
Removed All Legacy Code.
MarkHoath Feb 7, 2024
7123de9
defaults to gpt4turbo
MarkHoath Feb 7, 2024
eb33400
Added responseFormat for Chat Completions.
MarkHoath Feb 8, 2024
9144762
Response Format JSON
MarkHoath Feb 8, 2024
efa4bf4
asd
MarkHoath Feb 8, 2024
454d8b1
bugs
MarkHoath Feb 8, 2024
97cc7a9
asd
MarkHoath Feb 8, 2024
dd4836e
asd
MarkHoath Feb 8, 2024
9c409c9
change Def Model
MarkHoath Feb 8, 2024
d9296ab
no response
MarkHoath Feb 8, 2024
a0d8299
asd
MarkHoath Feb 8, 2024
de3ff36
asd
MarkHoath Feb 8, 2024
8bb1c2a
asd
MarkHoath Feb 8, 2024
e3c92bf
Paths need leading /
MarkHoath Feb 8, 2024
90a3742
ModelResult Created
MarkHoath Feb 8, 2024
ab2e0a3
asd
MarkHoath Feb 8, 2024
8507371
added GPT4Preview
MarkHoath Feb 9, 2024
6ecc8c1
asd
MarkHoath Feb 9, 2024
30971dc
gpt4 Default
MarkHoath Feb 9, 2024
30f70fb
asd
MarkHoath Feb 9, 2024
70889c1
Usage
MarkHoath Feb 9, 2024
7eb7714
asd
MarkHoath Feb 9, 2024
cdf1979
asd
MarkHoath Feb 9, 2024
4cb07f5
ResponseFormat Added
MarkHoath Feb 9, 2024
507cc62
remove print JSON
MarkHoath Feb 21, 2024
fc66fd3
asd
MarkHoath Mar 28, 2024
7f0e2d7
update new models - pre test
MarkHoath May 14, 2024
e244355
Update OpenAISwift.swift
MarkHoath Mar 9, 2025
29a63a4
Data Changes
MarkHoath Mar 9, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import PackageDescription

let package = Package(
name: "OpenAISwift",
platforms: [.iOS(.v15), .macOS(.v10_15)],
platforms: [.iOS(.v13), .macOS(.v10_15)],
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
Expand Down
165 changes: 11 additions & 154 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,6 @@ You can use Swift Package Manager to integrate the library by adding the followi

`.package(url: "https://github.com/adamrushy/OpenAISwift.git", from: "1.2.0")`

### CocoaPods

[CocoaPods](https://cocoapods.org) is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate `OpenAISwift` into your Xcode project using CocoaPods, specify it in your `Podfile`:

```ruby
pod 'OpenAISwift'
```

### Manual

Copy the source files into your own project.
Expand All @@ -40,152 +32,17 @@ Import the framework in your project:

[Create an OpenAI API key](https://platform.openai.com/account/api-keys) and add it to your configuration:

`let openAI = OpenAISwift(authToken: "TOKEN")`

This framework supports Swift concurrency; each example below has both an async/await and completion handler variant.

### [Completions](https://platform.openai.com/docs/api-reference/completions)

Predict completions for input text.

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

This returns an `OpenAI` object containing the completions.

Other API parameters are also supported:

```swift
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 {
// ...
}
```

For a full list of supported models, see [OpenAIModelType.swift](https://github.com/adamrushy/OpenAISwift/blob/main/Sources/OpenAISwift/Models/OpenAIModelType.swift). For more information on the models see the [OpenAI API Documentation](https://beta.openai.com/docs/models).

### [Chat](https://platform.openai.com/docs/api-reference/chat)

Get responses to chat conversations through ChatGPT (aka GPT-3.5) and GPT-4 (in beta).

```swift
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 {
// ...
}
```

All API parameters are supported, except streaming message content before it is completed:

```swift
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]?` (see inline documentation)
)
// use result
} catch {
// ...
}
```

### [Images (DALL·E)](https://platform.openai.com/docs/api-reference/images/create)

Generate an image based on a prompt.

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

### [Edits](https://platform.openai.com/docs/api-reference/edits)

Edits text based on a prompt and an instruction.

```swift
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 {
// ...
}
```

### [Moderation](https://platform.openai.com/docs/api-reference/moderations)

Classifies text for moderation purposes (see OpenAI reference for more info).

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

### [Embeddings](https://platform.openai.com/docs/api-reference/embeddings)

Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms.(see OpenAI reference for more info).

```swift
do {
let result = try await openAI.sendEmbeddings(
with: "The food was delicious and the waiter..."
)
// use result
} catch {
// ...
}
```
let TOKEN = "sk-...... "

let openAI: OpenAISwift = OpenAISwift(config: OpenAISwift.Config.makeDefaultOpenAI(apiKey: "TOKEN"))


To follow [OpenAI requirements](https://platform.openai.com/docs/api-reference/authentication)

> Remember that your API key is a secret! Do not share it with others or expose it in any client-side code (browsers, apps). Production requests must be routed through your own backend server where your API key can be securely loaded from an environment variable or key management service.

and basic industrial safety you should not call OpenAI API directly.


## Contribute ❤️

Expand Down
15 changes: 15 additions & 0 deletions Sources/OpenAISwift/Extensions/Extensions.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
//
// File.swift
//
//
// Created by Mark Hoath on 15/11/2023.
//

import Foundation

extension Encodable {
func toDictionary() -> [String: Any]? {
guard let data = try? JSONEncoder().encode(self) else { return nil }
return (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)).flatMap { $0 as? [String: Any] }
}
}
69 changes: 69 additions & 0 deletions Sources/OpenAISwift/Models/AssistantObject.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
//
// File.swift
//
//
// Created by Mark Hoath on 15/11/2023.
//

import Foundation

public struct CodeInterpretorTool: Codable {
public let type: String
}

public struct RetrievalTool: Codable {
public let type: String
}

public struct ParamJSONObject: Codable {
public let properties: String
}

public struct FunctionObject: Codable {
public let description: String
public let name: String
public let parameters: ParamJSONObject
}

public struct FunctionTool: Codable {
public let type: String
public let function: FunctionObject
}

public struct Tools: Codable {
public let codeInterpretorTool: CodeInterpretorTool?
public let retrievalTool: RetrievalTool?
public let functionTool: FunctionTool?
}



public struct AssistantObject: Codable {
public let id: String
public let object: String
public let created_at: Int
public let name: String?
public let description: String?
public let model: String
public let instructions: String?
public let tools: [Tools]
public let file_ids: [String]
public let metadata: [String:String]
}

public struct AssistantBody: Codable {
public let model: String
public let name: String?
public let description: String?
public let instructions: String?
public let tools: [Tools]?
public let file_ids: [String]?
public let metadata: [String:String]?
}

public struct ListAssistantParams: Codable {
public let limit: Int?
public let order: String?
public let after: String?
public let before: String?
}
47 changes: 47 additions & 0 deletions Sources/OpenAISwift/Models/AudioObject.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
//
// File.swift
//
//
// Created by Mark Hoath on 14/11/2023.
//

import Foundation

public enum Voice: String, Codable {
case alloy, echo, fable, onyx, nova, shimmer
}

public enum AudioResponseFormat: String, Codable {
case mp3, opus, aac, flac
}

public enum TranscriptionResponseFormat: String, Codable {
case json, text, srt, verbose_json, vtt
}

public struct Audio: Encodable {
public let model: String
public let input: String
public let voice: Voice
public let response_format: AudioResponseFormat?
public let speed: Double?
}

public struct Transcription: Encodable {
public let file: String
public let model: String
public let language: String?
public let prompt: String?
public let response_format: TranscriptionResponseFormat?
public let temperature: Double?

}

public struct Translation: Encodable {
public let file: String
public let model: String
public let prompt: String?
public let response_format: TranscriptionResponseFormat?
public let temperature: Double?
}

Loading