PHP code example of pv-source / aivory

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

    

pv-source / aivory example snippets




use PvSource\Aivory\Client;
use PvSource\Aivory\LLM\Turn\Turn;

// Создаем клиент
$client = new Client(
    providerName: 'deepseek',
    auth: ['apiKey' => 'sk-your-api-key']
);

$provider = $client->getProvider();

// Отправляем запрос
$turn = Turn::query()
    ->withProvider($provider)
    ->setUserPrompt('Привет! Расскажи о PHP')
    ->setModel('deepseek-chat')
    ->setTemperature(0.7)
    ->send();

// Получаем ответ
$assistantMessage = $turn->getResponse()->getAssistant();
echo $assistantMessage->content;



use PvSource\Aivory\LLM\Turn\Request\ResponseFormat;

// Создаем ResponseFormat с использованием класса
$responseFormat = ResponseFormat::jsonSchema(
    schema: ['type' => MathSolution::class],
    name: 'math_solution',
    strict: true
);

$turn = Turn::query()
    ->withProvider($provider)
    ->setUserPrompt('Реши: 2 + 2 * 3')
    ->setModel('deepseek-chat')
    ->setResponseFormat($responseFormat)
    ->send();

// Автоматическое преобразование в типизированный объект
$mathSolution = $turn->getResponse()->getSchemaObjects();
echo $mathSolution->answer; // "8"

$client = new Client(
    providerName: 'deepseek',  // или 'openai'
    auth: ['apiKey' => 'sk-...'],
    httpClient: $customHttpClient  // опционально
);

$turn = Turn::query()
    ->withProvider($provider)
    ->setSystemPrompt('Ты помощник')
    ->setUserPrompt('Вопрос')
    ->setModel('deepseek-chat')
    ->setTemperature(0.7)
    ->setMaxTokens(1000)
    ->send();

class MathTurn extends Turn
{
    // Значения по умолчанию (как в Eloquent)
    protected static ?string $defaultSystemPrompt = 'Ты математик';
    protected static ?string $defaultModel = 'deepseek-chat';
    protected static ?float $defaultTemperature = 0.3;
    
    // Scope методы для разных режимов
    public static function scopeAdvancedSolver(TurnBuilder $builder): void
    {
        $builder->setIsThinking(true);
        $builder->setMaxTokens(2000);
    }
}

// Использование
$turn = MathTurn::query()
    ->withProvider($provider)
    ->advancedSolver()  // вызывает scopeAdvancedSolver()
    ->setUserPrompt('Реши задачу')
    ->send();

class MathSolution implements JsonSchemaInterface
{
    public function __construct(
        public string $answer,
        public array $steps = []
    ) {}
    
    public static function getJsonSchema(?array $rootSchema = null): array
    {
        $schema = [
            'type' => 'object',
            'properties' => [
                'answer' => ['type' => 'string'],
            ]
        ];
        
        // Адаптивная схема в зависимости от контекста
        if ($rootSchema['name'] === 'advanced_math_solution') {
            $schema['properties']['steps'] = [
                'type' => 'array',
                'items' => ['type' => MathStep::class]
            ];
        }
        
        return $schema;
    }
    
    public static function fromResponse(array $data): static
    {
        return new self(
            answer: $data['answer'],
            steps: array_map(
                fn($step) => MathStep::fromResponse($step),
                $data['steps'] ?? []
            )
        );
    }
}

$client = new Client('deepseek', ['apiKey' => 'sk-...']);

$client = new Client('openai', ['apiKey' => 'sk-...']);

$turn = Turn::query()
    ->setModel('deepseek-chat')
    ->setTemperature(0.7)           // 0.0-2.0
    ->setMaxTokens(2000)            // Максимум токенов
    ->setFrequencyPenalty(0.5)     // -2.0 до 2.0
    ->setPresencePenalty(0.3)      // -2.0 до 2.0
    ->setTopP(0.9)                  // 0.0-1.0
    ->setIsThinking(true)            // DeepSeek only
    ->setStop(['\n\n', 'END'])       // Стоп-последовательности
    ->setStream(false)               // Streaming
    ->setResponseFormat($format)     // JSON Schema или text
    ->send();

$response = $turn->getResponse();

// Получить сообщение от ассистента
$assistantMessage = $response->getAssistant();
echo $assistantMessage->content;

// Получить reasoning content (если включен thinking mode)
if ($assistantMessage->reasoningContent !== null) {
    echo $assistantMessage->reasoningContent;
}

// Получить типизированный объект (если использовался JSON Schema)
$mathSolution = $response->getSchemaObjects();

// Получить usage информацию
$rawBody = $response->getRawBody();
$usage = $rawBody['usage'];
echo "Токенов использовано: {$usage['total_tokens']}";

class CustomHttpClient implements HttpClientInterface
{
    public function sendRequest(RequestInterface $request): ResponseInterface
    {
        // Ваша реализация
    }
}

$client = new Client(
    'deepseek',
    ['apiKey' => 'sk-...'],
    new CustomHttpClient()
);