php OpenAI聊天GPT(GPT-3.5)API:如何访问邮件内容?

yvt65v4c  于 2023-04-19  发布在  PHP
关注(0)|答案(1)|浏览(245)

当收到OpenAI的text-davinci-003模型的响应时,我能够使用以下PHP代码从响应中提取文本:

$response = $response->choices[0]->text;

以下是芬奇的回应代码:

{
  "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;

...这样它就可以抓取响应消息的内容?

eh57zj3b

eh57zj3b1#

Python:

print(response['choices'][0]['message']['content'])

NodeJS:

console.log(response.data.choices[0].message.content);

PHP:

var_dump($response->choices[0]->message->content);

PHP工作示例

如果运行test.php,OpenAI API将返回以下完成:
中文(简体)
英国的首都是伦敦。”

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);
?>

相关问题