Skip to content

Commit 67fec27

Browse files
committed
Make MerchantGenerativeContentRemote
1 parent 9627c91 commit 67fec27

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import Foundation
2+
3+
/// Generative content remote that uses merchant's API key for OpenAI instead of Jetpack AI
4+
///
5+
public final class MerchantGenerativeContentRemote: GenerativeContentRemoteProtocol {
6+
private let apiKey: String
7+
8+
public init(apiKey: String) {
9+
self.apiKey = apiKey
10+
}
11+
12+
public func generateText(siteID: Int64,
13+
base: String,
14+
feature: GenerativeContentRemoteFeature,
15+
responseFormat: GenerativeContentRemoteResponseFormat) async throws -> String {
16+
let url = URL(string: "https://api.openai.com/v1/chat/completions")!
17+
var request = URLRequest(url: url)
18+
request.httpMethod = "POST"
19+
request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
20+
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
21+
22+
let parameters: [String: Any] = [
23+
"model": "gpt-4",
24+
"messages": [
25+
[
26+
"role": "user",
27+
"content": base
28+
]
29+
],
30+
"max_tokens": 1000,
31+
"temperature": 0.7
32+
]
33+
34+
request.httpBody = try JSONSerialization.data(withJSONObject: parameters)
35+
36+
let (data, _) = try await URLSession.shared.data(for: request)
37+
38+
guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
39+
let choices = json["choices"] as? [[String: Any]],
40+
let firstChoice = choices.first,
41+
let message = firstChoice["message"] as? [String: Any],
42+
let content = message["content"] as? String else {
43+
throw MerchantGenerativeContentRemoteError.invalidResponse
44+
}
45+
46+
return content.trimmingCharacters(in: .whitespacesAndNewlines)
47+
}
48+
49+
public func identifyLanguage(siteID: Int64,
50+
string: String,
51+
feature: GenerativeContentRemoteFeature) async throws -> String {
52+
let prompt = String(format: AIRequestPrompts.identifyLanguage, string)
53+
return try await generateText(siteID: siteID, base: prompt, feature: feature, responseFormat: .text)
54+
}
55+
56+
public func generateAIProduct(siteID: Int64,
57+
productName: String?,
58+
keywords: String,
59+
language: String,
60+
tone: String,
61+
currencySymbol: String,
62+
dimensionUnit: String?,
63+
weightUnit: String?,
64+
categories: [ProductCategory],
65+
tags: [ProductTag]) async throws -> AIProduct {
66+
// For now throw an error
67+
throw MerchantGenerativeContentRemoteError.notImplemented
68+
}
69+
}
70+
71+
private enum MerchantGenerativeContentRemoteError: Error {
72+
case notImplemented
73+
case invalidResponse
74+
}

0 commit comments

Comments
 (0)