sw1*_*456 1 php curl openai-api chatgpt-api
我正在尝试对新发布的模型执行 API 调用gpt-3.5-turbo
,并具有以下代码,该代码$query
应向 API 发送查询(通过变量),然后从 API 中提取响应消息的内容。
但我每次通话都收到空响应。有什么想法我做错了什么吗?
$ch = curl_init();
$query = "What is the capital city of England?";
$url = 'https://api.openai.com/v1/chat/completions';
$api_key = 'sk-**************************************';
$post_fields = [
"model" => "gpt-3.5-turbo",
"messages" => ["role" => "user","content" => $query],
"max_tokens" => 500,
"temperature" => 0.8
];
$header = [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_fields));
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
}
curl_close($ch);
$response = json_decode($result);
$response = $response->choices[0]->message[0]->content;
Run Code Online (Sandbox Code Playgroud)
您收到响应的原因NULL
是因为无法解析 JSON 正文。
您会收到以下错误:"We could not parse the JSON body of your request. (HINT: This likely means you aren't using your HTTP library correctly. The OpenAI API expects a JSON payload, but what was sent was not valid JSON. If you have trouble figuring out how to fix this, please send an email to support@openai.com and include any relevant code you'd like help with.)"
。
改变这个...
$post_fields = [
"model" => "gpt-3.5-turbo",
"messages" => ["role" => "user","content" => $query],
"max_tokens" => 12,
"temperature" => 0
];
Run Code Online (Sandbox Code Playgroud)
……对此。
$post_fields = array(
"model" => "gpt-3.5-turbo",
"messages" => array(
array(
"role" => "user",
"content" => $query
)
),
"max_tokens" => 12,
"temperature" => 0
);
Run Code Online (Sandbox Code Playgroud)
如果您在 CMD 中运行php test.php
,OpenAI API 将返回以下完成信息:
字符串(40)“
英国的首都是伦敦。”
测试.php
<?php
$ch = curl_init();
$url = 'https://api.openai.com/v1/chat/completions';
$api_key = 'sk-xxxxxxxxxxxxxxxxxxxx';
$query = 'What is the capital city of England?';
$post_fields = array(
"model" => "gpt-3.5-turbo",
"messages" => array(
array(
"role" => "user",
"content" => $query
)
),
"max_tokens" => 12,
"temperature" => 0
);
$header = [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_fields));
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
}
curl_close($ch);
$response = json_decode($result);
var_dump($response->choices[0]->message->content);
?>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6496 次 |
最近记录: |