PHP code example of sgraaf / chatgpt-php

1. Go to this page and download the library: Download sgraaf/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/ */

    

sgraaf / chatgpt-php example snippets


// initialize the client
$client = new ChatGPT\Client('YOUR_OPENAI_API_KEY');

// initialize the client
$client = new ChatGPT\Client('YOUR_OPENAI_API_KEY', system_message: 'You are a helpful assistant that translates English to French.');

// provide an instruction
$message = $client->chat('Who won the world series in 2020?');
var_dump($message);
// string(53) "The Los Angeles Dodgers won the World Series in 2020."

// continue the conversation
$message = $client->chat('Where was it played?');
var_dump($message);
// string(116) "The 2020 World Series was played in Arlington, Texas at the Globe Life Field, the home stadium of the Texas Rangers."

var_dump($client->messages);
// array(5) {
//   [0]=>
//   array(2) {
//     ["role"]=>
//     string(6) "system"
//     ["content"]=>
//     string(28) "You are a helpful assistant."
//   }
//   [1]=>
//   array(2) {
//     ["role"]=>
//     string(4) "user"
//     ["content"]=>
//     string(33) "Who won the world series in 2020?"
//   }
//   [2]=>
//   array(2) {
//     ["role"]=>
//     string(9) "assistant"
//     ["content"]=>
//     string(53) "The Los Angeles Dodgers won the World Series in 2020."
//   }
//   [3]=>
//   array(2) {
//     ["role"]=>
//     string(4) "user"
//     ["content"]=>
//     string(20) "Where was it played?"
//   }
//   [4]=>
//   array(2) {
//     ["role"]=>
//     string(9) "assistant"
//     ["content"]=>
//     string(116) "The 2020 World Series was played in Arlington, Texas at the Globe Life Field, the home stadium of the Texas Rangers."
//   }
// }

// clear the conversation history
$client->clear();

var_dump($client->messages);
// array(1) {
//   [0]=>
//   array(2) {
//     ["role"]=>
//     string(6) "system"
//     ["content"]=>
//     string(28) "You are a helpful assistant."
//   }
// }
bash
composer