Skip to content
Open
Changes from 2 commits
Commits
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
29 changes: 27 additions & 2 deletions Sources/OpenAISwift/OpenAISwift.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public enum OpenAIError: Error {

public class OpenAISwift {
fileprivate(set) var token: String?
fileprivate(set) var baseURL: String?
fileprivate let config: Config

/// Configuration object for the client
Expand All @@ -26,8 +27,9 @@ public class OpenAISwift {
let session:URLSession
}

public init(authToken: String, config: Config = Config()) {
public init(authToken: String, baseURL: String? = nil, config: Config = Config()) {
self.token = authToken
self.baseURL = baseURL
self.config = Config()
}
}
Expand Down Expand Up @@ -217,7 +219,8 @@ extension OpenAISwift {
}

private func prepareRequest<BodyType: Encodable>(_ endpoint: Endpoint, body: BodyType) -> URLRequest {
var urlComponents = URLComponents(url: URL(string: endpoint.baseURL())!, resolvingAgainstBaseURL: true)

var urlComponents = URLComponents(url: prepareBaseURL(endpoint), resolvingAgainstBaseURL: true)
urlComponents?.path = endpoint.path
var request = URLRequest(url: urlComponents!.url!)
request.httpMethod = endpoint.method
Expand All @@ -235,6 +238,28 @@ extension OpenAISwift {

return request
}

private func prepareBaseURL(_ endpoint: Endpoint) -> URL{

if var baseURL = baseURL, !baseURL.isEmpty {
// needs https:// for request
if baseURL.lowercased().hasPrefix("http://") {
// change http to https
baseURL = baseURL.replacingOccurrences(of: "http://", with: "https://", options: .caseInsensitive)
}
if !baseURL.lowercased().hasPrefix("https://") {
// add https:// prefix
baseURL = "https://" + baseURL
}
while baseURL.hasSuffix("/") {
baseURL.removeLast()
}
return URL(string: baseURL)!
}

return URL(string: endpoint.baseURL())!
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could do better with the force unwrapping like throw an assertion to the client?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It needs to look like https://api.openai.com. If not, throws an assertion error to let user know?


}
}

extension OpenAISwift {
Expand Down