PHP code example of mathsgod / openai-chat

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

    

mathsgod / openai-chat example snippets


use OpenAI\Chat\System;

$system = new System($_ENV['OPENAI_API_KEY']);

echo $system->ask("Hello");


use OpenAI\Chat\Attributes\Tool;
use OpenAI\Chat\Attributes\Parameter;

#[Tool(description: 'Get the release date of iphone')]
function getIPhoneReleaseDate(#[Parameter("model of the phone")] string $model)
{
    return ["date" => "2022-09-14", "model" => $model];
}

$system->addTool(Closure::fromCallable("getIPhoneReleaseDate"));

echo $system->ask("When will iPhone 14 be released?");

class Controller
{
    public $price = "$799";

    #[Tool(description: 'Get the price of iphone')]
    public function getIPhonePrice(#[Parameter("model of the phone")] string $model)
    {
        return ["price" => $this->price, "model" => $model];
    }
}

$system->addTool(Closure::fromCallable([new Controller(), "getIPhonePrice"]));

echo $system->ask("What is the price and release date of iphone14?");



print_r($system->getUsages());


$stream = $system->askAsStream("What is the price and release date of iphone14?");

$stream->on('data', function ($data) {
    echo $data;
});