PHP code example of grnsv / neuron-gigachat

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

    

grnsv / neuron-gigachat example snippets


'gigachat' => [
    'client_id' => env('GIGACHAT_CLIENT_ID'),
    'client_secret' => env('GIGACHAT_CLIENT_SECRET'),
    'model' => env('GIGACHAT_MODEL', 'GigaChat'),
    'scope' => env('GIGACHAT_SCOPE', 'GIGACHAT_API_PERS'),
],

 declare(strict_types=1);

namespace App\Neuron\Agents;

use Illuminate\Contracts\Cache\Repository as CacheRepository;
use Illuminate\Contracts\Config\Repository as ConfigRepository;
use NeuronAI\Agent;
use NeuronAI\Providers\AIProviderInterface;
use NeuronAI\Providers\GigaChat\Config;
use NeuronAI\Providers\GigaChat\GigaChat;
use NeuronAI\SystemPrompt;

final class MyAgent extends Agent
{
    public function __construct(
        private readonly ConfigRepository $config,
        private readonly CacheRepository $cache,
    ) {}

    protected function provider(): AIProviderInterface
    {
        return new GigaChat(
            config: new Config(...$this->config->get('services.gigachat')),
            cache: $this->cache,
        );
    }

    public function instructions(): string
    {
        return (string) new SystemPrompt(
            background: ['Ты дружелюбный ИИ-агент.'],
        );
    }
}

protected function provider(): AIProviderInterface
{
    return new GigaChat(
        config: new Config(...$this->config->get('services.gigachat')),
        cache: $this->cache,
        // отключаем проверку сертификата
        verifyTLS: false,
    );
}

protected function provider(): AIProviderInterface
{
    return new GigaChat(
        config: new Config(...$this->config->get('services.gigachat')),
        cache: $this->cache,
        // сессия передается в заголовке `X-Session-ID`
        httpOptions: new HttpClientOptions(headers: ['X-Session-ID' => $this->getSessionId()]),
    );
}

// здесь ваш механизм хранения сессий
private function getSessionId(): string
{
    return $this->cache->remember(
        'my_agent:session_id',
        now()->endOfWeek(),
        fn (): string => (string) Str::uuid(),
    );
}



namespace App\Console\Commands;

use App\Neuron\Agents\MyAgent;
use Illuminate\Console\Command;
use NeuronAI\Chat\Messages\UserMessage;

final class TestAgent extends Command
{
    protected $signature = 'app:test-agent';
    protected $description = 'Test NeuronAI + GigaChat agent';

    public function handle(MyAgent $agent)
    {
        $response = $agent->chat(
            new UserMessage('Когда уже ИИ захватит этот мир?'),
        );

        $this->info($response->getContent());
    }
}



namespace App\Neuron\DTO;

use NeuronAI\StructuredOutput\SchemaProperty;

class Output
{
    #[SchemaProperty(description: 'Значение вероятности в процентах.', 

final class MyAgent extends Agent
{
    public function instructions(): string
    {
        return (string) new SystemPrompt(
            background: ['Ты специалист по правдоподобным предсказаниям. Даешь оценку вероятности события в процентах.'],
        );
    }

    protected function getOutputClass(): string
    {
        return Output::class;
    }
}

final class TestAgent extends Command
{
    public function handle(MyAgent $agent)
    {
        $response = $agent->structured(
            new UserMessage('Какова вероятность в процентах, что ИИ в этом году захватит мир?'),
        );

        $this->info(json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
    }
}
bash
php vendor/bin/neuron make:agent App\\Neuron\\Agents\\MyAgent
bash
php artisan make:command TestAgent