PHP code example of haozi-team / chatgpt-php

1. Go to this page and download the library: Download haozi-team/chatgpt-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

haozi-team / chatgpt-php example snippets



use HaoZiTeam\ChatGPT\V1 as ChatGPTV1;

$chatGPT = new ChatGPTV1();
$chatGPT->addAccount('<your_access_token>');

$answers = $chatGPT->ask('Hello, how are you?');
foreach ($answers as $item) {
    print_r($item);
}
//Array(
//    'answer' => 'I am fine, thank you.',
//    'conversation_id' => '<uuid>',
//    'parent_id' => '<uuid>',
//    'model' => 'text-davinci-002-render-sha',
//    'account' => '0',
//)


use HaoZiTeam\ChatGPT\V1 as ChatGPTV1;

$chatGPT = new ChatGPTV1('https://chat.openai.com/backend-api/');


use HaoZiTeam\ChatGPT\V2 as ChatGPTV2;

$chatGPT = new ChatGPTV2('sk-<your_api_key>');
$chatGPT->addMessage('You are ChatGPT, a large language model trained by OpenAI. Answer as concisely as possible.', 'system');

$answers = $chatGPT->ask('Hello, how are you?');
foreach ($answers as $item) {
    print_r($item);
}


use HaoZiTeam\ChatGPT\V2 as ChatGPTV2;

$chatGPT = new ChatGPTV2('sk-<your_api_key>', 'https://api.openai.com/');


use HaoZiTeam\ChatGPT\V2 as ChatGPTV2;

$chatGPT = new ChatGPTV2('sk-<your_api_key>');
$chatGPT->addMessage('You are ChatGPT, a large language model trained by OpenAI. Answer as concisely as possible.', 'system');
$chatGPT->addMessage('Hello, how are you?', 'user');
$chatGPT->addMessage('I am fine, thank you.', 'assistant');

$answers = $chatGPT->ask('What did I ask you before?');
foreach ($answers as $item) {
    print_r($item);
}
//Array(
//    'answer' => 'Hello, how are you?',
//    'id' => 'cmpl-xxxxx',
//    'model' => 'gpt-3.5-turbo',
//    'usage' => [
//        "prompt_tokens": 9,
//        "completion_tokens": 12,
//        "total_tokens": 21,
//    ],
//)


use HaoZiTeam\ChatGPT\V2 as ChatGPTV2;

$chatGPT = new ChatGPTV2('sk-<your_api_key>');
$chatGPT->addMessage('You are ChatGPT, a large language model trained by OpenAI. Answer as concisely as possible.', 'system');

$answers = $chatGPT->ask('Hello, how are you?', null, true);// A Generator
foreach ($answers as $item) {
    print_r($item);
}