PHP code example of losthost / simple-openai-agent

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

    

losthost / simple-openai-agent example snippets


use losthost\SimpleAI\SimpleAIAgent;

;

// Простой запрос
$answer = SimpleAIAgent::build($api_key)
    ->ask('Привет! Как дела?');

echo $answer;

$agent = SimpleAIAgent::build($api_key)
    ->setUserId('user123')
    ->setDialogId('chat1')
    ->setAgentName('помощник')
    ->setPrompt('Ты полезный ассистент');

// Сохраняет контекст в БД автоматически
$answer1 = $agent->ask('Как настроить почту?');
$answer2 = $agent->ask('А для телефона?'); // Помнит предыдущий разговор

// Авто-ретрай при ошибках
$answer = $agent->ask('Вопрос', function($ex) use ($agent) {
    if (str_contains($ex->getMessage(), 'timeout')) {
        return $agent->ask(); // ретрай
    }
    return "Извините, произошла ошибка";
});

// Один экземпляр - много агентов
$agent = SimpleAIAgent::build($api_key)
    ->setUserId('user123')
    ->setDialogId('chat1')
    ->setAgentName('техподдержка')
    ->setPrompt('Ты ассистент техподдержки')
    ->setAgentName('консультант')
    ->setPrompt('Ты финансовый консультант');

$answer1 = $agent->setAgentName('техподдержка')->ask('Проблема с WiFi');
$answer2 = $agent->setAgentName('консультант')->ask('Куда вложить деньги?');

DB::connect($host, $user, $pass, $database, $prefix);