pod 'Alamofire'
import Alamofire
//OpenAI
struct OpenAIConfiguration {
let apiKey: String
}
let configuration = OpenAIConfiguration(apiKey: "hage")
func generateTranslationPrompt(inputText: String) -> String {
let promptTemplate = "xxxxxしろや。: \(inputText)"
return promptTemplate
}
func callText(model: String,inputText: String, completion: @escaping (String?, Error?) -> Void) {
let prompt = generateTranslationPrompt(inputText: inputText)
let messages: [[String: Any]] = [
["role": "system", "content": "あなたはxxxxxです。"],
["role": "user", "content": prompt]
]
let parameters: [String: Any] = [
"model": model,
"messages": messages,
"temperature": 0.3,
"top_p": 1.0,
"frequency_penalty": 0.0,
"presence_penalty": 0.0
]
let headers: HTTPHeaders = [
"Authorization": "Bearer \(configuration.apiKey)"
]
AF.request("https://api.openai.com/v1/chat/completions", method: .post, parameters: parameters, encoding: JSONEncoding.default,
headers: headers).responseJSON { response in
switch response.result {
case .success(let value):
if let jsonResponse = value as? [String: Any],
let choices = jsonResponse["choices"] as? [[String: Any]],
let firstChoice = choices.first,
let message = firstChoice["message"] as? [String: Any],
let text = message["content"] as? String {
completion(text, nil)
} else {
completion(nil, NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "Failed to parse response"]))
}
case .failure(let error):
completion(nil, error)
}
}
}
そんで呼びたいところで使う
let orgString = "おはよう"
callText(model: "gpt-3.5-turbo",inputText: "\(orgString)") { (convertText, error) in
if let error = error {
print("Error1: \(error)")
} else if let convertText = convertText {
print("Translated text: \(convertText)")
}
}