PHP code example of blinq / openai

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

    

blinq / openai example snippets




use Blinq\LLM\Config\ApiConfig;
use Blinq\LLM\Entities\ChatMessage;
use Blinq\LLM\Client;

$config = new ApiConfig('openai', 'your-api-key');
$client = new Client($config);

// Set the system message. This is optional.
$client->setSystemMessage("You are a nice chatbot");

// User message
$client->chat("Hello, how are you?");

// Get the last message
$message = $client->getLastMessage();

echo $message->content; // Prints "I am fine, thank you. How are you?"

// Get the chat history
$history = $client->getHistory();

foreach ($history as $message) {
    echo $message->content;
}



use Blinq\LLM\Config\ApiConfig;
use Blinq\LLM\Entities\ChatStream;
use Blinq\LLM\Client;

$config = new ApiConfig('openai', 'your-api-key');
$client = new Client($config);

$client->addStreamHandler(function (ChatStream $stream) {
    // Handle the stream data
    echo $stream->getMessage()?->content; // Prints the partial message content
    
    // The $stream object has a 'done' property to check if the stream is done
    if ($stream->done) {
        // Do something when the stream is done
    }
});

$client->chat("Hello, how are you?", "user", ['stream' => true]);