尝试调用刚刚为 ChatGPT 发布的 got-3.5-turbo API,但我收到错误请求错误?
var body = new
{
model = "gpt-3.5-turbo",
messages = data
};
string jsonMessage = JsonConvert.SerializeObject(body);
using (HttpClient client = new HttpClient())
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpRequestMessage requestMessage = new
HttpRequestMessage(HttpMethod.Post, "https://api.openai.com/v1/completions")
{
Content = new StringContent(jsonMessage, Encoding.UTF8, "application/json")
};
string api_key = PageExtension_CurrentUser.Community.CAIChatGPTAPIKey.Length > 30 ? PageExtension_CurrentUser.Community.CAIChatGPTAPIKey : Genesis.Generic.ReadAppSettingsValue("chatGPTAPIKey");
requestMessage.Headers.Add("Authorization", $"Bearer {api_key}");
HttpResponseMessage response = client.SendAsync(requestMessage).Result;
if (response.StatusCode == HttpStatusCode.OK)
{
string responseData = response.Content.ReadAsStringAsync().Result;
dynamic responseObj = JsonConvert.DeserializeObject(responseData);
string choices = responseObj.choices[0].text;
}
他们的 API 文档中有代码:
curl https://api.openai.com/v1/chat/completions \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer YOUR_API_KEY' \
-d '{
"model": "gpt-3.5-turbo",
"messages": [{"role": "user", "content": "Hello!"}]
}'
.. 这是另一个示例:
openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Who won the world series in 2020?"},
{"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
{"role": "user", "content": "Where was it played?"}
]
)
谁能看出我为什么会收到错误消息?
编辑:错误信息
{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Connection: keep-alive
Access-Control-Allow-Origin: *
Openai-Organization: user-lmjzqj7ba2bggaekkhr68aqn
Openai-Processing-Ms: 141
Openai-Version: 2020-10-01
Strict-Transport-Security: max-age=15724800; includeSubDomains
X-Request-Id: 9eddf8bb8dcc106ca11d44ad7f8bbecc
Date: Mon, 06 Mar 2023 12:49:46 GMT
Content-Length: 201
Content-Type: application/json
}}
{Method: POST, RequestUri: 'https://api.openai.com/v1/chat/completions', Version: 1.1, Content: System.Net.Http.StringContent, Headers:
{
Authorization: Bearer sk-ihUxxxxxxxxxxxxxxxxxx[JUST REMOVED MY API KEY]xxxxxxxxxxxxxxx
Content-Type: application/json; charset=utf-8
Content-Length: 79
}}
改变这个...
https://api.openai.com/v1/completions
...到这个。
https://api.openai.com/v1/chat/completions
改变这个...
string choices = responseObj.choices[0].text;
...到这个。
string choices = responseObj.choices[0].message;
Content-Type
header添加这个:
requestMessage.Headers.Add("Content-Type", "application/json");