Search code examples
phpopenai-apichatgpt-api

OpenAI Chat Completions API: How do I extract the message content from the response?


When receiving a response from OpenAI's text-davinci-003 model, I was able to extract the text from the response with the following PHP code:

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

Here was the text-davinci-003 response code:

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

I am now trying to alter my code to work with the recently released gpt-3.5-turbo model which returns the response slightly differently:

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

My question is, how can I alter the code:

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

...so that it can grab the content of the response message?


Solution

  • Python:

    • If you have the OpenAI Python SDK <v1:

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

    • If you have the OpenAI Python SDK v1:

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

    Node.js:

    • If you have the OpenAI Node.js SDK v3:

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

    • If you have the OpenAI Node.js SDK v4:

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

    PHP:

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

    Working example in PHP

    If you run test.php, the OpenAI API will return the following completion:

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