feat: минимальная PHP-библиотека для чата с вызовом инструментов
- AiClient: любой OpenAI-совместимый /chat/completions (DeepSeek, OpenAI, Ollama, llama.cpp) - Agent: цикл function calling, история диалога, трассировка вызовов - Tool + ToolRegistry: инструмент = 4 метода, ошибки уходят модели текстом - ChatClient: интерфейс, чтобы подменять модель в тестах - инструменты: get_time, calculator (без eval), get_weather (open-meteo) - 4 примера и 18 тестов без сети - настройки в .env: AI_BASE_URL/AI_MODEL/AI_API_KEY/AI_VERIFY_SSL/AI_CAINFO
This commit is contained in:
commit
14fe8d8a5e
22 files changed
+2122
No files matched your search
+167
@@ -0,0 +1,167 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace AiSdk;
|
||||
|
||||
use AiSdk\Tools\CalculatorTool;
|
||||
use AiSdk\Tools\TimeTool;
|
||||
|
||||
/**
|
||||
* Диалог с моделью и цикл вызова инструментов.
|
||||
*
|
||||
* Ровно один публичный метод для работы:
|
||||
* $agent->ask('вопрос');
|
||||
*
|
||||
* Внутри: отправили вопрос -> модель попросила инструменты -> выполнили ->
|
||||
* отправили результаты -> получили ответ. И так до maxRounds.
|
||||
*/
|
||||
final class Agent
|
||||
{
|
||||
private const DEFAULT_SYSTEM_PROMPT = <<<'TXT'
|
||||
Ты — полезный ассистент. Отвечай кратко и по делу.
|
||||
Если для ответа нужен факт (время, расчёт, погода и т.п.), сначала вызови подходящий инструмент.
|
||||
Не выдумывай данные, которые можно получить инструментом.
|
||||
TXT;
|
||||
|
||||
/** @var list<array<string, mixed>> */
|
||||
private array $messages = [];
|
||||
|
||||
/** @var list<array{name: string, arguments: array<string, mixed>, output: string, ms: int}> */
|
||||
private array $trace = [];
|
||||
|
||||
private string $systemPrompt;
|
||||
|
||||
public function __construct(
|
||||
private readonly ChatClient $client,
|
||||
private readonly ToolRegistry $tools = new ToolRegistry(),
|
||||
string $systemPrompt = self::DEFAULT_SYSTEM_PROMPT,
|
||||
private readonly int $maxRounds = 5,
|
||||
) {
|
||||
$this->systemPrompt = $systemPrompt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Сменить системный промпт на ходу.
|
||||
*
|
||||
* Если диалог уже начат, обновляется первое system-сообщение — история
|
||||
* и инструменты при этом сохраняются. Если нет — промпт применится при
|
||||
* следующем ask().
|
||||
*/
|
||||
public function setSystemPrompt(string $systemPrompt): void
|
||||
{
|
||||
$this->systemPrompt = $systemPrompt;
|
||||
|
||||
if (($this->messages[0]['role'] ?? '') === 'system') {
|
||||
$this->messages[0]['content'] = $systemPrompt;
|
||||
}
|
||||
}
|
||||
|
||||
public function systemPrompt(): string
|
||||
{
|
||||
return $this->systemPrompt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Задать вопрос. История диалога сохраняется между вызовами.
|
||||
*/
|
||||
public function ask(string $question): string
|
||||
{
|
||||
if ($this->messages === []) {
|
||||
$this->messages[] = ['role' => 'system', 'content' => $this->systemPrompt];
|
||||
}
|
||||
|
||||
$this->messages[] = ['role' => 'user', 'content' => $question];
|
||||
|
||||
$result = $this->chat();
|
||||
$round = 0;
|
||||
|
||||
while ($result->hasToolCalls() && $round < $this->maxRounds) {
|
||||
$round++;
|
||||
|
||||
// Сообщение ассистента с tool_calls обязательно: иначе API
|
||||
// не примет следующие за ним tool-сообщения.
|
||||
$this->messages[] = $result->assistantMessage;
|
||||
|
||||
foreach ($result->toolCalls as $call) {
|
||||
$started = microtime(true);
|
||||
$output = $this->tools->execute($call['name'], $call['arguments']);
|
||||
|
||||
$this->trace[] = [
|
||||
'name' => $call['name'],
|
||||
'arguments' => $call['arguments'],
|
||||
'output' => $output,
|
||||
'ms' => (int) round((microtime(true) - $started) * 1000),
|
||||
];
|
||||
|
||||
$this->messages[] = [
|
||||
'role' => 'tool',
|
||||
'tool_call_id' => $call['id'],
|
||||
'content' => $output,
|
||||
];
|
||||
}
|
||||
|
||||
$result = $this->chat();
|
||||
}
|
||||
|
||||
// Модель зациклилась на инструментах — просим ответить без них.
|
||||
if ($result->hasToolCalls()) {
|
||||
$this->messages[] = [
|
||||
'role' => 'user',
|
||||
'content' => 'Лимит вызовов инструментов исчерпан. Ответь на вопрос без инструментов.',
|
||||
];
|
||||
|
||||
$result = $this->client->chat($this->messages, []);
|
||||
}
|
||||
|
||||
$text = $result->text !== '' ? $result->text : '(модель вернула пустой ответ)';
|
||||
$this->messages[] = ['role' => 'assistant', 'content' => $text];
|
||||
|
||||
return $text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Вся история диалога — удобно сохранить в БД или отдать в свой лог.
|
||||
*
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
return $this->messages;
|
||||
}
|
||||
|
||||
/**
|
||||
* Что реально вызывалось: имя, аргументы, результат, время.
|
||||
*
|
||||
* @return list<array{name: string, arguments: array<string, mixed>, output: string, ms: int}>
|
||||
*/
|
||||
public function trace(): array
|
||||
{
|
||||
return $this->trace;
|
||||
}
|
||||
|
||||
/**
|
||||
* Начать диалог заново.
|
||||
*/
|
||||
public function reset(): void
|
||||
{
|
||||
$this->messages = [];
|
||||
$this->trace = [];
|
||||
}
|
||||
|
||||
private function chat(): ChatResult
|
||||
{
|
||||
return $this->client->chat($this->messages, $this->tools->definitions());
|
||||
}
|
||||
|
||||
/**
|
||||
* Быстрый старт: агент с инструментами по умолчанию.
|
||||
*/
|
||||
public static function withDefaults(ChatClient $client): self
|
||||
{
|
||||
return new self(
|
||||
$client,
|
||||
(new ToolRegistry())->add(new TimeTool(), new CalculatorTool()),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace AiSdk;
|
||||
|
||||
/**
|
||||
* Клиент любого OpenAI-совместимого /chat/completions.
|
||||
*
|
||||
* Годится для DeepSeek, OpenAI, OpenRouter, Ollama, llama.cpp, LM Studio.
|
||||
* Меняется только AI_BASE_URL и AI_MODEL в .env.
|
||||
*/
|
||||
final class AiClient implements ChatClient
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $extraBody дополнительные поля тела запроса,
|
||||
* если провайдер их требует
|
||||
* @param bool $verifySsl проверять TLS-сертификат (по умолчанию да).
|
||||
* false — только для локальной отладки.
|
||||
* @param string $caInfo путь к своему CA-бандлу (cacert.pem). Пусто —
|
||||
* системные сертификаты PHP/OpenSSL.
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly string $apiKey,
|
||||
private readonly string $model = 'deepseek-chat',
|
||||
private readonly string $baseUrl = 'https://api.deepseek.com',
|
||||
private readonly float $timeout = 30.0,
|
||||
private readonly float $temperature = 0.7,
|
||||
private readonly int $maxTokens = 1000,
|
||||
private readonly array $extraBody = [],
|
||||
private readonly bool $verifySsl = true,
|
||||
private readonly string $caInfo = '',
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Собрать клиент из .env. Все параметры необязательны, кроме ключа
|
||||
* для закрытых провайдеров.
|
||||
*/
|
||||
public static function fromEnv(): self
|
||||
{
|
||||
$extraBody = [];
|
||||
|
||||
// DeepSeek умеет отключать «размышления» — так ответ быстрее и дешевле.
|
||||
if (Env::bool('AI_DISABLE_THINKING', false)) {
|
||||
$extraBody['thinking'] = ['type' => 'disabled'];
|
||||
}
|
||||
|
||||
return new self(
|
||||
apiKey: Env::get('AI_API_KEY', '') ?? '',
|
||||
model: Env::get('AI_MODEL', 'deepseek-chat') ?? 'deepseek-chat',
|
||||
baseUrl: Env::get('AI_BASE_URL', 'https://api.deepseek.com') ?? 'https://api.deepseek.com',
|
||||
timeout: Env::float('AI_TIMEOUT', 30.0),
|
||||
temperature: Env::float('AI_TEMPERATURE', 0.7),
|
||||
maxTokens: Env::int('AI_MAX_TOKENS', 1000),
|
||||
extraBody: $extraBody,
|
||||
verifySsl: Env::bool('AI_VERIFY_SSL', true),
|
||||
caInfo: Env::get('AI_CAINFO', '') ?? '',
|
||||
);
|
||||
}
|
||||
|
||||
public function chat(array $messages, array $tools = []): ChatResult
|
||||
{
|
||||
$body = [
|
||||
'model' => $this->model,
|
||||
'messages' => $messages,
|
||||
'stream' => false,
|
||||
'temperature' => $this->temperature,
|
||||
'max_tokens' => $this->maxTokens,
|
||||
];
|
||||
|
||||
if ($tools !== []) {
|
||||
$body['tools'] = $tools;
|
||||
$body['tool_choice'] = 'auto';
|
||||
}
|
||||
|
||||
$body = array_merge($body, $this->extraBody);
|
||||
|
||||
[$raw, $status, $error] = $this->post($body);
|
||||
|
||||
if ($raw === null) {
|
||||
throw new AiException('Ошибка сети: ' . $error . $this->tlsHint($error));
|
||||
}
|
||||
|
||||
$data = json_decode($raw, true);
|
||||
|
||||
if (!is_array($data)) {
|
||||
throw new AiException(
|
||||
'Модель вернула не-JSON (HTTP ' . $status . '): ' . mb_substr($raw, 0, 300)
|
||||
);
|
||||
}
|
||||
|
||||
if ($status >= 400) {
|
||||
$message = $data['error']['message'] ?? $raw;
|
||||
throw new AiException('HTTP ' . $status . ': ' . mb_substr((string) $message, 0, 300));
|
||||
}
|
||||
|
||||
$message = $data['choices'][0]['message'] ?? null;
|
||||
|
||||
if (!is_array($message)) {
|
||||
throw new AiException('В ответе нет choices[0].message');
|
||||
}
|
||||
|
||||
$text = is_string($message['content'] ?? null) ? $message['content'] : '';
|
||||
|
||||
$assistant = ['role' => 'assistant', 'content' => $text];
|
||||
|
||||
if (isset($message['tool_calls'])) {
|
||||
$assistant['tool_calls'] = $message['tool_calls'];
|
||||
}
|
||||
|
||||
return new ChatResult(
|
||||
text: $text,
|
||||
toolCalls: self::parseToolCalls($message),
|
||||
assistantMessage: $assistant,
|
||||
usage: is_array($data['usage'] ?? null) ? $data['usage'] : [],
|
||||
raw: $data,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Разобрать tool_calls в удобный вид. Аргументы приходят строкой JSON.
|
||||
*
|
||||
* @param array<string, mixed> $message
|
||||
* @return list<array{id: string, name: string, arguments: array<string, mixed>}>
|
||||
*/
|
||||
private static function parseToolCalls(array $message): array
|
||||
{
|
||||
$calls = [];
|
||||
|
||||
foreach ($message['tool_calls'] ?? [] as $call) {
|
||||
if (!is_array($call)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$name = (string) ($call['function']['name'] ?? '');
|
||||
|
||||
if ($name === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$rawArguments = $call['function']['arguments'] ?? '{}';
|
||||
$arguments = is_string($rawArguments)
|
||||
? json_decode($rawArguments, true)
|
||||
: $rawArguments;
|
||||
|
||||
if (!is_array($arguments)) {
|
||||
$arguments = [];
|
||||
}
|
||||
|
||||
$id = (string) ($call['id'] ?? '');
|
||||
|
||||
$calls[] = [
|
||||
'id' => $id !== '' ? $id : 'call_' . bin2hex(random_bytes(6)),
|
||||
'name' => $name,
|
||||
'arguments' => $arguments,
|
||||
];
|
||||
}
|
||||
|
||||
return $calls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Подсказка при типовой ошибке TLS на Windows.
|
||||
*/
|
||||
private function tlsHint(string $error): string
|
||||
{
|
||||
if (!$this->verifySsl) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (!str_contains($error, 'certificate') && !str_contains($error, 'SSL')) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return ' Подсказка: укажите путь к корневым сертификатам в AI_CAINFO '
|
||||
. 'или временно поставьте AI_VERIFY_SSL=false (только локально).';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $body
|
||||
* @return array{0: string|null, 1: int, 2: string|null} тело, HTTP-код, ошибка
|
||||
*/
|
||||
private function post(array $body): array
|
||||
{
|
||||
$url = rtrim($this->baseUrl, '/') . '/chat/completions';
|
||||
|
||||
$headers = [
|
||||
'Content-Type: application/json',
|
||||
'Accept: application/json',
|
||||
'Expect:',
|
||||
];
|
||||
|
||||
if ($this->apiKey !== '') {
|
||||
$headers[] = 'Authorization: Bearer ' . $this->apiKey;
|
||||
}
|
||||
|
||||
$payload = json_encode(
|
||||
$body,
|
||||
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE
|
||||
);
|
||||
|
||||
if ($payload === false) {
|
||||
return [null, 0, 'не удалось сериализовать запрос в JSON'];
|
||||
}
|
||||
|
||||
$ch = curl_init($url);
|
||||
|
||||
if ($ch === false) {
|
||||
return [null, 0, 'не удалось создать cURL-дескриптор'];
|
||||
}
|
||||
|
||||
$options = [
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_POSTFIELDS => $payload,
|
||||
CURLOPT_HTTPHEADER => $headers,
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT_MS => (int) round($this->timeout * 1000),
|
||||
CURLOPT_CONNECTTIMEOUT_MS => 5000,
|
||||
// AI_VERIFY_SSL=false отключает проверку цепочки и имени хоста.
|
||||
CURLOPT_SSL_VERIFYPEER => $this->verifySsl,
|
||||
CURLOPT_SSL_VERIFYHOST => $this->verifySsl ? 2 : 0,
|
||||
CURLOPT_FOLLOWLOCATION => false,
|
||||
];
|
||||
|
||||
// Свой CA-бандл: актуально для Windows, где у PHP нет системных корней.
|
||||
if ($this->caInfo !== '') {
|
||||
$options[CURLOPT_CAINFO] = $this->caInfo;
|
||||
}
|
||||
|
||||
curl_setopt_array($ch, $options);
|
||||
|
||||
$raw = curl_exec($ch);
|
||||
$status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
|
||||
$error = curl_error($ch);
|
||||
curl_close($ch);
|
||||
|
||||
if ($raw === false) {
|
||||
return [null, $status, $error !== '' ? $error : 'неизвестная ошибка cURL'];
|
||||
}
|
||||
|
||||
return [(string) $raw, $status, null];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace AiSdk;
|
||||
|
||||
/**
|
||||
* Любая ошибка обращения к модели: сеть, HTTP 4xx/5xx, неожиданный ответ.
|
||||
*/
|
||||
final class AiException extends \RuntimeException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace AiSdk;
|
||||
|
||||
/**
|
||||
* Минимальный контракт чата. Отдельный интерфейс нужен, чтобы в тестах
|
||||
* подставить фейковую модель и не ходить в сеть.
|
||||
*/
|
||||
interface ChatClient
|
||||
{
|
||||
/**
|
||||
* @param list<array<string, mixed>> $messages история диалога
|
||||
* @param list<array<string, mixed>> $tools определения в формате OpenAI
|
||||
*/
|
||||
public function chat(array $messages, array $tools = []): ChatResult;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace AiSdk;
|
||||
|
||||
/**
|
||||
* Результат одного ответа модели.
|
||||
*
|
||||
* assistantMessage — ровно то, что нужно положить обратно в историю, чтобы
|
||||
* API принял следующие за ним tool-сообщения.
|
||||
*/
|
||||
final class ChatResult
|
||||
{
|
||||
/**
|
||||
* @param list<array{id: string, name: string, arguments: array<string, mixed>}> $toolCalls
|
||||
* @param array<string, mixed> $assistantMessage
|
||||
* @param array<string, int> $usage
|
||||
* @param array<string, mixed> $raw
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly string $text,
|
||||
public readonly array $toolCalls,
|
||||
public readonly array $assistantMessage,
|
||||
public readonly array $usage = [],
|
||||
public readonly array $raw = [],
|
||||
) {
|
||||
}
|
||||
|
||||
public function hasToolCalls(): bool
|
||||
{
|
||||
return $this->toolCalls !== [];
|
||||
}
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace AiSdk;
|
||||
|
||||
/**
|
||||
* Чтение настроек из .env без единой зависимости.
|
||||
*
|
||||
* Формат: KEY=VALUE, пустые строки и # - комментарии, значение можно брать
|
||||
* в кавычки. Уже установленные переменные окружения не перезаписываются.
|
||||
*/
|
||||
final class Env
|
||||
{
|
||||
public static function load(string $file): void
|
||||
{
|
||||
if (!is_file($file)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
||||
|
||||
if ($lines === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($lines as $line) {
|
||||
$line = trim($line);
|
||||
|
||||
if ($line === '' || str_starts_with($line, '#') || !str_contains($line, '=')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
[$key, $value] = explode('=', $line, 2);
|
||||
$key = trim($key);
|
||||
$value = trim($value);
|
||||
|
||||
if (strlen($value) >= 2) {
|
||||
$quote = $value[0];
|
||||
|
||||
if (($quote === '"' || $quote === "'") && str_ends_with($value, $quote)) {
|
||||
$value = substr($value, 1, -1);
|
||||
}
|
||||
}
|
||||
|
||||
if ($key !== '' && getenv($key) === false) {
|
||||
putenv($key . '=' . $value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static function get(string $key, ?string $default = null): ?string
|
||||
{
|
||||
$value = getenv($key);
|
||||
|
||||
return $value === false ? $default : $value;
|
||||
}
|
||||
|
||||
public static function int(string $key, int $default): int
|
||||
{
|
||||
$value = self::get($key);
|
||||
|
||||
return $value === null || $value === '' ? $default : (int) $value;
|
||||
}
|
||||
|
||||
public static function float(string $key, float $default): float
|
||||
{
|
||||
$value = self::get($key);
|
||||
|
||||
return $value === null || $value === '' ? $default : (float) $value;
|
||||
}
|
||||
|
||||
public static function bool(string $key, bool $default): bool
|
||||
{
|
||||
$value = self::get($key);
|
||||
|
||||
if ($value === null || $value === '') {
|
||||
return $default;
|
||||
}
|
||||
|
||||
return in_array(strtolower($value), ['1', 'true', 'yes', 'on'], true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace AiSdk;
|
||||
|
||||
/**
|
||||
* Минимальный HTTP-клиент для инструментов: один GET, таймаут, проверка TLS.
|
||||
*
|
||||
* POST не нужен — для инструментов хватает чтения. Если понадобится,
|
||||
* добавьте рядом метод post() по образцу.
|
||||
*/
|
||||
final class Http
|
||||
{
|
||||
/**
|
||||
* @return array{0: int, 1: string} HTTP-код и тело ответа
|
||||
*/
|
||||
public static function get(string $url, float $timeout = 10.0): array
|
||||
{
|
||||
$ch = curl_init($url);
|
||||
|
||||
if ($ch === false) {
|
||||
throw new AiException('не удалось создать cURL-дескриптор');
|
||||
}
|
||||
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT_MS => (int) round($timeout * 1000),
|
||||
CURLOPT_CONNECTTIMEOUT_MS => 5000,
|
||||
CURLOPT_FOLLOWLOCATION => true,
|
||||
CURLOPT_MAXREDIRS => 3,
|
||||
CURLOPT_SSL_VERIFYPEER => true,
|
||||
CURLOPT_SSL_VERIFYHOST => 2,
|
||||
CURLOPT_USERAGENT => 'ai-sdk/1.0 (+https://example.local)',
|
||||
CURLOPT_HTTPHEADER => ['Accept: application/json'],
|
||||
]);
|
||||
|
||||
$body = curl_exec($ch);
|
||||
$status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
|
||||
$error = curl_error($ch);
|
||||
curl_close($ch);
|
||||
|
||||
if ($body === false) {
|
||||
throw new AiException('HTTP-ошибка: ' . ($error !== '' ? $error : 'неизвестно'));
|
||||
}
|
||||
|
||||
return [$status, (string) $body];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace AiSdk;
|
||||
|
||||
/**
|
||||
* Инструмент, который модель может вызвать.
|
||||
*
|
||||
* Четыре метода: имя, описание, схема аргументов и сама работа.
|
||||
* Ничего больше не требуется — реестр сам отдаст схему модели и вызовет handle().
|
||||
*/
|
||||
interface Tool
|
||||
{
|
||||
/**
|
||||
* Имя латиницей, snake_case. Именно его модель указывает в tool_calls.
|
||||
*/
|
||||
public function name(): string;
|
||||
|
||||
/**
|
||||
* Что делает инструмент и когда его использовать.
|
||||
* Модель читает это описание и решает, звать ли инструмент.
|
||||
*/
|
||||
public function description(): string;
|
||||
|
||||
/**
|
||||
* JSON Schema аргументов в формате OpenAI function calling.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function parameters(): array;
|
||||
|
||||
/**
|
||||
* Выполнить инструмент и вернуть текст для модели.
|
||||
*
|
||||
* Бросать исключения не обязательно: ToolRegistry превратит их в текст
|
||||
* ошибки, и модель сможет исправиться.
|
||||
*
|
||||
* @param array<string, mixed> $args
|
||||
*/
|
||||
public function handle(array $args): string;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace AiSdk;
|
||||
|
||||
/**
|
||||
* Набор инструментов: хранит их, отдаёт схемы модели и вызывает по имени.
|
||||
*/
|
||||
final class ToolRegistry
|
||||
{
|
||||
/** @var array<string, Tool> */
|
||||
private array $tools = [];
|
||||
|
||||
/**
|
||||
* @param int $maxResultChars обрезка результата, чтобы не раздувать контекст
|
||||
*/
|
||||
public function __construct(private readonly int $maxResultChars = 4000)
|
||||
{
|
||||
}
|
||||
|
||||
public function add(Tool ...$tools): self
|
||||
{
|
||||
foreach ($tools as $tool) {
|
||||
$this->tools[$tool->name()] = $tool;
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function has(string $name): bool
|
||||
{
|
||||
return isset($this->tools[$name]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<Tool>
|
||||
*/
|
||||
public function all(): array
|
||||
{
|
||||
return array_values($this->tools);
|
||||
}
|
||||
|
||||
/**
|
||||
* Схемы для поля "tools" запроса к модели.
|
||||
*
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public function definitions(): array
|
||||
{
|
||||
$definitions = [];
|
||||
|
||||
foreach ($this->tools as $tool) {
|
||||
$definitions[] = [
|
||||
'type' => 'function',
|
||||
'function' => [
|
||||
'name' => $tool->name(),
|
||||
'description' => $tool->description(),
|
||||
'parameters' => $tool->parameters(),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
return $definitions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Выполнить инструмент по имени.
|
||||
*
|
||||
* Никогда не бросает исключение: любая проблема становится текстом,
|
||||
* который модель получит как результат вызова и сможет обойти.
|
||||
*
|
||||
* @param array<string, mixed> $arguments
|
||||
*/
|
||||
public function execute(string $name, array $arguments): string
|
||||
{
|
||||
if (!isset($this->tools[$name])) {
|
||||
return 'Ошибка: неизвестный инструмент "' . $name . '".';
|
||||
}
|
||||
|
||||
try {
|
||||
$result = $this->tools[$name]->handle($arguments);
|
||||
} catch (\Throwable $e) {
|
||||
return 'Ошибка инструмента "' . $name . '": ' . $e->getMessage();
|
||||
}
|
||||
|
||||
if (mb_strlen($result) > $this->maxResultChars) {
|
||||
return mb_substr($result, 0, $this->maxResultChars) . '…';
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user