我目前已经在swiftUI中使用Alamofire创建了一个REST API。该请求是指向以下URL的post方法:https://api.openai.com/v1/engines/text-davinci-002/completions,它基本上是向OpenAI API发送一个问题,并 * 假定 * 以JSON格式获得答案。我在OpenAI中创建了一个API密钥,并将其包含在我的代码中。
我面临的问题是,当获得输入时,我收到以下错误:Error: Response status code was unacceptable: 400.
我首先试图确定我的API密钥是否正确,它确实是正确的。我还试图看看一个cURL语句是否能工作来检查它是否是URL的错误。
我使用了以下cURL语句:
curl -X POST \
https://api.openai.com/v1/engines/text-davinci-002/completions \
-H 'Authorization: Bearer my-api-key' \
-H 'Content-Type: application/json' \
-d '{
"prompt": "What is quantum mechanics?",
"temperature": 0.7,
"max_tokens": 20,
"top_p": 1,
"frequency_penalty": 0,
"presence_penalty": 0
}'
它运行良好,并给了我一个正确的输出:
{"id":"cmpl-6hhWBlzZHrLtV4RKCtjL63CLoTvPi","object":"text_completion","created":1675873407,"model":"text-davinci-002","choices":[{"text":"\n\nQuantum mechanics is a branch of physics that studies the behavior of matter and energy in the","index":0,"logprobs":null,"finish_reason":"length"}],"usage":{"prompt_tokens":5,"completion_tokens":20,"total_tokens":25}}
如果有用的话,下面是我的代码:
//
// chat.swift
// titan
//
// Created by Refluent on 08/02/2023.
//
import SwiftUI
import Alamofire
struct Message: Hashable {
let sender: String
let content: String
}
struct OpenAIResponse: Decodable {
let completions: [Completion]
struct Completion: Decodable {
let text: String
}
}
struct chatView: View {
@State private var response: String = ""
@State private var messages: [Message] = []
@State private var userInput: String = ""
let apiKey = "my-api-key"
let model = "text-davinci-002"
var body: some View {
VStack {
Text("Response from OpenAI API:")
List(messages, id: \.self) { message in
Text("\(message.sender): \(message.content)")
}
TextField("Enter your question", text: $userInput)
.padding()
Button(action: {
self.sendRequest()
}) {
Text("Send")
}
}
}
func sendRequest() {
let headers: HTTPHeaders = ["Authorization": "Bearer \(apiKey)", "Content-Type": "application/json"]
let parameters: Parameters = ["prompt": userInput, "model": model]
messages.append(Message(sender: "Me", content: userInput))
userInput = ""
AF.request("https://api.openai.com/v1/engines/text-davinci-002/completions", method: .post, parameters: parameters, headers: headers)
.validate()
.responseDecodable(of: OpenAIResponse.self) { response in
switch response.result {
case .success(let value):
let text = value.completions[0].text
self.messages.append(Message(sender: "ChatGPT", content: text))
case .failure(let error):
self.messages.append(Message(sender: "ChatGPT", content: "Error: \(error.localizedDescription)"))
}
}
}
}
有关我的代码的更多上下文,请参阅:
我向this URL发送一个post请求,然后获取输出并将其保存在原始输入旁边的数组中,输入和输出随后显示为聊天。
有人知道为什么我会收到这个错误吗?我错过了代码中的关键部分吗?
提前谢谢你。
在阅读了评论之后,我意识到这并不是在Swift
中可以做的事情,所以我将在服务器端实现它。
1条答案
按热度按时间ukdjmx9f1#
您正在将
model
作为参数发送到引擎url(特定于模型)。请尝试发布到https://api.openai.com/v1/completions
。引擎特定的端点已被弃用,因此最好现在更新您的调用。