gpt4 book ai didi

php - OpenAI ChatGPT (GPT-3.5) API : How do I extract the message content from the response?

转载 作者:行者123 更新时间:2023-12-02 22:46:21 26 4
gpt4 key购买 nike

当收到来自 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 v4released于2023年8月16日发布,并且是对SDK的完全重写。除此之外,提取消息内容方面也发生了变化。请参阅 v3v4 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);

PHP 中的工作示例

如果您运行 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com