Swift OpenAI API请求:API密钥缺失解决方案
这段 Swift 代码试图向 OpenAI API 发送 POST 请求,以从 Davinci Codex 模型获取补全结果。但是,错误信息表明缺少 API 密钥。
要解决这个问题,您需要从 OpenAI 平台(https://platform.openai.com/account/api-keys)获取 API 密钥,并将其包含在请求头的'Authorization'字段中。更新后的代码如下所示:
let apiKey = 'YOUR_API_KEY'
let headers: HTTPHeaders = [
'Authorization': 'Bearer ' + apiKey,
'Content-Type': 'application/json'
]
let parameters: Parameters = [
'prompt': self.requestStr
]
AF.request('https://api.openai.com/v1/engines/davinci-codex/completions', method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).response(completionHandler: { response in
if let data = response.data {
do {
if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary {
// 处理 JSON 响应
print(json)
}
} catch {
// 处理错误
}
}
print('Response: (response)')
})
请确保将'YOUR_API_KEY'替换为您的实际 API 密钥。
原文地址: https://www.cveoy.top/t/topic/qm5s 著作权归作者所有。请勿转载和采集!