作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
当收到来自 OpenAI 的 text-davinci-003
模型的响应时,我能够使用以下 PHP 代码从响应中提取文本:
$response = $response->choices[0]->text;
这是 text-davinci-003
响应代码:
{
"id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7",
"object": "text_completion",
"created": 1589478378,
"model": "text-davinci-003",
"choices": [
{
"text": "\n\nThis is indeed a test",
"index": 0,
"logprobs": null,
"finish_reason": "length"
}
],
"usage": {
"prompt_tokens": 5,
"completion_tokens": 7,
"total_tokens": 12
}
}
我现在正在尝试更改我的代码以使用最近发布的 gpt-3.5-turbo
模型,该模型返回的响应略有不同:
{
"id": "chatcmpl-123",
"object": "chat.completion",
"created": 1677652288,
"choices": [{
"index": 0,
"message": {
"role": "assistant",
"content": "\n\nHello there, how may I assist you today?",
},
"finish_reason": "stop"
}],
"usage": {
"prompt_tokens": 9,
"completion_tokens": 12,
"total_tokens": 21
}
}
我的问题是,如何更改代码:
$response = $response->choices[0]->text;
...这样它就可以抓取响应消息的内容?
最佳答案
Python:
print(response['choices'][0]['message']['content'])
NodeJS:
注意:OpenAI NodeJS SDK v4
为 released于2023年8月16日发布,并且是对SDK的完全重写。除此之外,提取消息内容方面也发生了变化。请参阅 v3
至 v4
migration guide .
• 如果您有 OpenAI NodeJS SDK v3
:
console.log(response.data.choices[0].message.content);
• 如果您有 OpenAI NodeJS SDK v4
:
console.log(response.choices[0].message.content);
PHP:
var_dump($response->choices[0]->message->content);
如果您运行 test.php
,OpenAI API 将返回以下完成信息:
string(40) "
The capital city of England is London."
test.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);
?>
关于php - OpenAI ChatGPT (GPT-3.5) API : How do I extract the message content from the response?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75613656/
我是一名优秀的程序员,十分优秀!