adamrushy / openaiswift Goto Github PK
View Code? Open in Web Editor NEWThis is a wrapper library around the ChatGPT and OpenAI HTTP API
License: MIT License
This is a wrapper library around the ChatGPT and OpenAI HTTP API
License: MIT License
Hi Team,
I tried integrating the package and facing a decoding error in the response. Could some one please guide me
my code
`func getData(text: String, completion: @escaping ((Result<String, Error>) -> Void)) {
client?.sendCompletion(with: text) { result in
switch result {
case .success(let success):
if let atleastOneReply = success.choices.first?.text {
completion(.success(atleastOneReply))
}
case .failure(let failure):
print(failure.localizedDescription)
}
}
}`
I get this random error every 2-10 requests, and I cant figure out the reason why.
I think in the OpenAI file, the object should be optional
public struct OpenAI: Codable {
public let object: String
public let model: String?
public let choices: [Choice]
}
ie public let object: String?
Error is...
Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "object", intValue: nil),
Swift.DecodingError.Context(codingPath: [], debugDescription:
"No value associated with key CodingKeys(stringValue: "object", intValue: nil) ("object").", underlyingError: nil)))
Sorry Im not advanced enough to do a pull request and test etc.
I have this :
success(OpenAISwift.OpenAI(object: "text_completion", model: "text-davinci-003", choices: [OpenAISwift.Choice(text: "\n\nHi there! Nice to meet you.")]))
how to convert this into a string to have a text with the response in my main view ?
I have a working app using the 4k model. Is it possible to use OpenAI's gpt-3.5-turbo-16k model with this package?
(It's my first time posting an issue. Not sure if this belongs in issues.)
I finished developing my application with this package when I started asking the AI questions. I quickly realised, the AI did not remember past texts like the real ChatGPT, but I thought it was just a bug, so I continued asking.
I then asked it what it's name was, where it responded with Susan. Again, I thought it was just a bug so I continued asking. Finally, I asked it this:
Me: What company were you developed by?
AI: I was developed by Amazon Web Services (AWS) as part of their suite of cloud-based services.
I just wanted to make sure if this was true for others. If not, then I guess it has something to do with me.
Would love a library for solid Whisper support in swift, this would be nice addition to your Api :)
Command and Instruction can be structs without init and should have let properties as there is no need to mutate them
PROS:
When the answer tokens is very long, it can't show all the answers, how to continue answer?
This just started happening yesterday out of no where but I started getting an error for
let result = try await openAI.sendChat(with: chat) ---- >> Value of type 'OpenAISwift' has no member 'sendChat'
let chat: [ChatMessage] = [. ------ >>. Cannot find type 'ChatMessage' in scope
I can't seem to figure out why it's not working. Completions workout however.
Its not really an issue,
I should of done a pull request but figured it would get seen faster here,
was wandering about an update to support GPT 3.5 specifically gpt-3.5-turbo
its much quicker and cheaper and has training data up to sep 2021
I was going to update my own packages but would lose it when I update next
cheers
Used the API endpoint and getting 0 response on every search
let openAPI = OpenAISwift(authToken: "TOKEN")
override func viewDidLoad() {
super.viewDidLoad()
openAPI.sendCompletion(with: "dog") { result in
switch result {
case .success(let success):
if let atleastOneReply = success.choices.first?.text {
print(atleastOneReply)
}
case .failure(let failure):
print(failure.localizedDescription)
}
}
}
Got res
and has choices array which has 0 values
Just wanted to know does this support End user ID?
https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids
When trying to use this package to build a lambda using the swift-aws-lambda runtime approach, there is a step where you need to build the executable using docker. When exciting this command:
docker run \ ─╯
--rm \
--volume "$(pwd)/:/src" \
--workdir "/src/" \
swift:5.7.0-amazonlinux2 \
swift build --product OpenAIPoc -c release -Xswiftc -static-stdlib
I'm seeing the below issue:
/src/.build/checkouts/OpenAISwift/Sources/OpenAISwift/OpenAISwift.swift:45:95: error: cannot find type 'URLRequest' in scope
private func prepareRequest<BodyType: Encodable>(_ endpoint: Endpoint, body: BodyType) -> URLRequest {
^~~~~~~~~~
/src/.build/checkouts/OpenAISwift/Sources/OpenAISwift/OpenAISwift.swift:28:34: error: type 'URLSession' (aka 'AnyObject') has no member 'shared'
let session = URLSession.shared
~~~~~~~~~~ ^~~~~~
/src/.build/checkouts/OpenAISwift/Sources/OpenAISwift/OpenAISwift.swift:48:23: error: cannot find 'URLRequest' in scope
var request = URLRequest(url: urlComponents!.url!)
^~~~~~~~~~
By adding the below code to the OpenAI.swift - I think this problem would be alleviated.
#if canImport(FoundationNetworking) && canImport(FoundationXML)
import FoundationNetworking
import FoundationXML
#endif
Are you cool with me opening a PR to add this in?
Thanks!
The OpenAI Api allows you to optionally pass a temperature number value (defaults to 1) letting the model knowwhat sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.
The current version of OpenAISwift doesn't seem to allow this.
Can this be added as a pass through value? Similarly there are other values besides temperature that could be passed in optionally.
Whether to support text/event-stream
The latest release 1.3.0 (Zip File / Main etc) does not include the GPT4 support in the OpenAIModelType file.
Could this please be included and can the "Release" function be implemented in GitHub so we can download with Package Manager the latest release.
Hi,
I'm trying to develop an app and I have created a secret key by the OpenAI website and used the below code:
import SwiftUI
import OpenAISwift
struct MainView: View {
@State private var chatText: String = ""
let openAI = OpenAISwift(authToken: "MY SECRET KEY FROM THE OPENAI WEBSITE")
@State private var answers: [String] = []
private var isFormValid: Bool {
!chatText.isEmptyOrWhiteSpace
}
private func performSearch() {
openAI.sendCompletion(with: chatText, maxTokens: 500) { result in
switch result {
case .success(let success):
let answer = success.choices.first?.text.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
answers.append(answer)
case .failure(let failure):
print(failure)
}
}
}
var body: some View {
VStack {
List(answers, id: \.self) { answer in
Text(answer)
}
Spacer()
HStack {
TextField("Search...", text: $chatText)
.textFieldStyle(.roundedBorder)
Button {
// action
performSearch()
} label: {
Image(systemName: "paperplane.circle.fill")
.font(.title)
.rotationEffect(Angle(degrees: 45))
}.buttonStyle(.borderless)
.tint(.blue)
.disabled(!isFormValid)
}
}.padding()
}
}
struct MainView_Previews: PreviewProvider {
static var previews: some View {
MainView()
}
}
but it giving me couple of errors:
I cannot find the solution. Can you help me please?
Just noticed that these APIs were available:
https://platform.openai.com/docs/api-reference/images/create-edit
https://platform.openai.com/docs/api-reference/images/create-variation
Would be nice to have these added!
API of OpenAI is not public for all countries. And there're some project provide code for solving it. One of them is using proxy for apis. Such as: https://github.com/x-dr/chatgptProxyAPI
when requesting https://example.com
, It will jump to https://api.openai.com
by proxy.
private(set) customBaseURL
in OpenAISwift
OpenAISwift.prepareRequest()
where using Endpoint.baseURL()
In Endpoint.baseURL()
, I think It might be a static variable in Endpoint, because all cases in Endpoint need the same base url.
Is there a better way for implementing custom base url
OpenAI的接口不是对所有国家开放的,所以会有一些项目提供一些通过代理的方式解决了这个问题。例如 https://github.com/x-dr/chatgptProxyAPI
OpenSwift
中添加一个字段private(set) customBaseURL
OpenAISwift.prepareRequest()
中的关于Endpoint.baseURL()
的代码在Endpoint.baseURL()
中,所有枚举值都返回同一个URL(https://api.openai.com
),是不是设置成常量会更好一些。
是否有更好地方式来实现自定义API域名
Hi Guys, I am having an issue, I don't know if it related to the package but it probably is so here is my code
` // Send query to OpenAI
**openAI.send(prompt: query) { [weak self] (response, error) in**
guard let self = self else { return }
if let error = error {
print("Error: \(error.localizedDescription)")
self.startListening()
return
}
if let response = response {
// Use Text to Speech to speak response
let synthesizer = AVSpeechSynthesizer()
let utterance = AVSpeechUtterance(string: response.text)
synthesizer.speak(utterance)
}`
By the way the below Bugs are on this line "openAI.send(prompt: query) { [weak self] (response, error) in"
Bug 1: Unable to infer type of closure parameter 'error' in the current context
Bug 2: Unable to infer type of a closure parameter 'response' in the current context
Bug 3: Value of type 'OpenAI' has no member 'send'
Using a web browser, the conversation is "hold" in a single chat. In that case, answers can be related to older questions inside the "closed chat". Is where a chance to reach the same by using OpenAISwift?
It would be useful if the API Key could be entered on first execution and saved in UserDefaults for use on subsequent runs.
first of all im very impressed how easy this library to use! I have implemented this to my app in less than an hour! thank you so much for spending hundreds of hours to make this awesome!
i am new to this section and please delete if this is not the place to ask this but i am curious why the chats are not "remembered". if i ask a question then follow it with another question after, it never remembers even my previous message. is this feature will be supported here? or this is something not a concern at all?
I have it working if i ask it a short question it's great however if I ask something more complex e.g explain string theory to a 5 year old.. and the response is couple of paragraphs it just produces 75 characters
I am not using any parameters i have tried larger token number and different models but no look any advice be greatly appreciated.
I don't know if this happen to others, but mine is completely weird. Everything working fine yesterday but now even a "hi" message from me will get an article about world war or something really random.
It would be great to be able to manage the user's usage to limit any potential overage costs to the developer. Below is the struct needed to decode the usage object sent back from the API and a quick, maybe messy approach to storing the usage overtime.
Regardless of the second part, the first part alone would be super useful. Thanks.
struct Usage:Codable {
var prompt:Int
var completion:Int
var total:Int
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.prompt = try values.decode(Int.self, forKey: .prompt)
self.total = try values.decode(Int.self, forKey: .total)
self.completion = try values.decode(Int.self, forKey: .completion)
self.storeLocalUsage(usage:self)
}
enum CodingKeys: String, CodingKey {
case prompt = "prompt_tokens"
case completion = "completion_tokens"
case total = "total_tokens"
}
func storeLocalUsage(usage:Usage) {
var list = UserDefaults().string(forKey: "gpt_usage").components(separatedBy: ",") {
list.append(String(usage.completion))
UserDefaults().set(list.lazy.joined(separator: ","), forKey: "gpt_usage")
UserDefaults().synchronize()
}
}
}
Hi, thanks for great library!
I am wondering if there's a way to deal with 'The request timed out.' error which happens after a period of inactivity. Or is there a way to deactivate it?
Initialisation has changed from AuthKey to a Config parameter.
I have this error when my client iOS App requests from the OpenAI endpoint
▿ Result<OpenAI, OpenAIError>
▿ failure : OpenAIError
▿ decodingError : 1 element
▿ error : DecodingError
▿ keyNotFound : 2 elements
- .0 : CodingKeys(stringValue: "object", intValue: nil)
▿ .1 : Context
- codingPath : 0 elements
- debugDescription : "No value associated with key CodingKeys(stringValue: \"object\", intValue: nil) (\"object\")."
- underlyingError : nil
I check the source code of struct OpenAI. can we make change the object to optional?
the struct openAI should be like
public struct OpenAI<T: Payload>: Codable {
public let object: String?
public let model: String?
public let choices: [T]
}
Because in ios14 many api can not be called properly
It's in the documentation/README, but not in the code as far as I can see.
I have a use-case where I want to utilize URLSessionDelegate to keep track of the progress of data connections in detail.
The current design of OpenAISwift.swift
uses the dataTask(with:completionHandler:)
method of URLSession to perform data communication, but this method seems to bypass the various callbacks of URLSessionDelegate to completion handler. (refs)
I tried using OpenAISwift.Config
to specify my own URLSession, but in the end I could not get the URLSessionDelegate to work.
It would be nice if there was an interface that could support URLSessionDelegate (or its subprotocols), or an original callback mechanism that could keep track of the progress of data communication in detail.
is this repo steaming output support?
any sample code, please?
Can we add a feature to read the API key from Info.plist file in UIkit or iOS Target Properties switUI?
It would be convenient for users belonging to multiple organizations if the request header of the OpenAI API has an interface that allows users to assign an arbitrary Organization ID to the OpenAI-Organization
field.
https://platform.openai.com/docs/api-reference/requesting-organization
Getting the following when submitting a "sendChat"
▿ OpenAIError
▿ chatError : 1 element
▿ error : Payload
It looks like OpenAI is throwing an error because of the extra field.
Removing the Identifiable protocol and the id variable allows everything to run.
`/// A structure that represents a single message in a chat conversation.
public struct ChatMessage: Codable {
/// The role of the sender of the message.
public let role: ChatRole?
/// The content of the message.
public let content: String?
...
`
Thank you for the great library.
I was wondering how I can decode the errors and get the codes as in https://platform.openai.com/docs/guides/error-codes
hi,
Add Package
Xcode 13, ios 15
Error message:
Dependencies could not be resolved because 'OpenAISwift' contains incompatible tools version (5.7.0) and root depends on 'OpenAISwift' 1.0.0..<2.0.0.
Is this possible or planned?
sometimes it will throw an error:
decodingError(error: Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "object", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"object\", intValue: nil) (\"object\").", underlyingError: nil))) [request-id: CAB2D22B-D7D9-4F45-AF7C-9086A7F5471F]
Getting the following when submitting a "sendChat"
▿ OpenAIError
▿ chatError : 1 element
▿ error : Payload
- message : "Additional properties are not allowed ('id' was unexpected) - 'messages.0'"
- type : "invalid_request_error"
- param : nil
- code : nil
i tried to use the optional parameter in the sendChat function (eg. temperature, user etc.) , but the script don't accept these parameter except token and model.
The main page shows an API call for generating images using DALL-E but when I run the example given:
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)
}
}
it says OpenAISwift has no member 'sendImages'. Maybe I'm doing something wrong?
I updated the packages and the decoding error is now gone but when I make a request I get the following:
OpenAI<TextResult>(object: nil, model: nil, choices: nil, usage: nil, data: nil)
openAI.sendCompletion(with: chatText, maxTokens: 500) { result in
switch result {
case .success(let success):
// OpenAI<TextResult>(object: nil, model: nil, choices: nil, usage: nil, data: nil)
print(success)
The success contains all nil values.
Hi,
I've integrated OpenAISwift with SPM to my framework but when I try to archive my framework I get bunch of errors saying that "'ChatRole' is not a member type of class 'OpenAISwift.OpenAISwift'" for all OpenAISwift types (ChatError, Payload...).
If I do manual integration using source code it archives fine.
When I make successfully api call response back like this.
"success(OpenAISwift.OpenAI(object: "text_completion", model: "text-davinci-003", choices: [OpenAISwift.Choice(text: "ma\n\nShadows Of The Night\n\nThe night stretches long, ")]))"
that's my code
func aichange(){
openAPI.sendCompletion(with: "bana ingilizce şiir yaz", model: .gpt3(.davinci)) { result in // Result<OpenAI, OpenAIError>
// switch on result to get the response or error
if case let .success(response) = result {
if let firstChoice = response.choices.first {
print(result)
}
}
if case let .failure(error) = result {
print(error.localizedDescription) // Hata mesajını yazdırır
}
}
}
The text "ma\n\nShadows Of The Night\n\nThe night stretches long, "
Thank you for creating such a useful Swift Package.
It would be great if you could tweak your code by adding a simple property
, to allow for selecting the
number of choices
to the input of text sendCompletion()
, similar to what you already have for sendImages()
with numImages
.
This would mean:
in struct Command: Encodable
add let numChoices: Int
.
In extension OpenAISwift
add numChoices: Int = 1
to the end of sendCompletion(with prompt:...)
,
similarly for sendCompletion(with prompt:...) async
.
I feel that a formal pull request for such a minor update is not warranted.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.