Poxy OpenAI calls and remove OpenAI secrets from the app

This commit is contained in:
Thomas Ricouard 2023-12-09 10:58:42 +01:00
parent da6c5ed76c
commit 52208ab20e
2 changed files with 2 additions and 24 deletions

View file

@ -2,8 +2,6 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"> <plist version="1.0">
<dict> <dict>
<key>OPENAI_SECRET</key>
<string>NICE_TRY</string>
<key>DEEPL_SECRET</key> <key>DEEPL_SECRET</key>
<string>NICE_TRY_AGAIN</string> <string>NICE_TRY_AGAIN</string>
</dict> </dict>

View file

@ -1,30 +1,11 @@
import Foundation import Foundation
protocol OpenAIRequest: Encodable { protocol OpenAIRequest: Encodable {
var path: String { get }
var model: String { get } var model: String { get }
} }
extension OpenAIRequest {
var path: String {
"chat/completions"
}
}
public struct OpenAIClient { public struct OpenAIClient {
private let endpoint: URL = .init(string: "https://api.openai.com/v1/")! private let endpoint: URL = .init(string: "https://icecubesrelay.fly.dev/openai")!
private var APIKey: String {
if let path = Bundle.main.path(forResource: "Secret", ofType: "plist") {
let secret = NSDictionary(contentsOfFile: path)
return secret?["OPENAI_SECRET"] as? String ?? ""
}
return ""
}
private var authorizationHeaderValue: String {
"Bearer \(APIKey)"
}
private var encoder: JSONEncoder { private var encoder: JSONEncoder {
let encoder = JSONEncoder() let encoder = JSONEncoder()
@ -130,9 +111,8 @@ public struct OpenAIClient {
public func request(_ prompt: Prompt) async throws -> Response { public func request(_ prompt: Prompt) async throws -> Response {
do { do {
let jsonData = try encoder.encode(prompt.request) let jsonData = try encoder.encode(prompt.request)
var request = URLRequest(url: endpoint.appending(path: prompt.request.path)) var request = URLRequest(url: endpoint)
request.httpMethod = "POST" request.httpMethod = "POST"
request.setValue(authorizationHeaderValue, forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData request.httpBody = jsonData
let (result, _) = try await URLSession.shared.data(for: request) let (result, _) = try await URLSession.shared.data(for: request)