diff --git a/.env.example b/.env.example index 44609f4..56c2cb3 100644 --- a/.env.example +++ b/.env.example @@ -30,3 +30,20 @@ AI_VERIFY_SSL=true # Свой CA-бандл (cacert.pem). Пусто — системные сертификаты PHP/OpenSSL. # Актуально для Windows: скачайте https://curl.se/ca/cacert.pem и укажите путь. AI_CAINFO= + +# === Агент === + +# Сколько раундов «модель → инструменты» разрешено до принудительного ответа. +AI_MAX_ROUNDS=5 + +# Разрешить модели возвращать несколько tool_calls в одном ответе. +# false — вызовы пойдут по одному (полезно для слабых моделей и опасных инструментов). +AI_PARALLEL_TOOL_CALLS=true + +# Сколько сообщений истории держать перед вопросом (0 — без лимита). +# Старые ходы обрезаются целиком, system и текущий вопрос сохраняются. +AI_HISTORY_LIMIT=40 + +# auto — решает модель | none — не вызывать инструменты | +# required — обязать вызвать хоть что-то | имя_инструмента — заставить конкретный. +AI_TOOL_CHOICE=auto diff --git a/README.md b/README.md index 47f60e4..155fe8e 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,7 @@ examples/ 02-tools.php агент с тремя инструментами 03-custom-tool.php свой инструмент с нуля 04-cli.php интерактивный чат в терминале + 05-settings.php tool_choice, подтверждение вызовов, история tests/run.php тесты без сети ``` @@ -98,6 +99,45 @@ messages += {role: tool, tool_call_id, content} Ошибки инструментов не ломают диалог: `ToolRegistry` превращает исключение в текст, модель видит `Ошибка инструмента "x": ...` и может исправиться. +## Настройки агента + +Все параметры — именованными аргументами конструктора, defaults безопасные: + +```php +$agent = new Agent( + client: AiClient::fromEnv(), + tools: $tools, + systemPrompt: 'Отвечай кратко.', + maxRounds: 5, // предохранитель от зацикливания + toolChoice: 'auto', // auto | none | required | имя инструмента + parallelToolCalls: true, // разрешить модели батчить вызовы + historyLimit: 40, // сообщений истории (0 — без лимита) + toolApproval: fn (string $name, array $args): bool => $name !== 'get_time', +); +``` + +| Параметр | `.env` | Что делает | +|---|---|---| +| `maxRounds` | `AI_MAX_ROUNDS` | сколько раундов «инструменты → модель» до принудительного ответа | +| `toolChoice` | `AI_TOOL_CHOICE` | `required` заставит вызвать инструмент, `none` запретит, имя — конкретный | +| `parallelToolCalls` | `AI_PARALLEL_TOOL_CALLS` | `false` — вызовы пойдут по одному | +| `historyLimit` | `AI_HISTORY_LIMIT` | обрезка старых ходов; `system` и текущий вопрос остаются | +| `toolApproval` | — | колбэк-подтверждение: `false` запрещает вызов, модель получает отказ | + +Два нюанса, которые важно знать: + +- **`toolChoice` действует только на первый запрос хода.** Иначе `required` + заставит модель звать инструменты в каждом раунде, и она никогда не ответит. + Дальше всегда `auto`. +- **`toolApproval` — не песочница.** Это удобный хук для «спросить человека» и + для логов. Настоящая защита — не давать инструменту опасных прав вообще. + +Агент целиком из `.env`: + +```php +$agent = Agent::fromEnv($tools, 'Отвечай кратко.'); +``` + ## Свой инструмент Четыре метода. Всё. @@ -192,7 +232,8 @@ curl http://10.10.10.77:8080/v1/models php tests/run.php ``` -18 проверок: калькулятор, время, реестр, обрезка результатов, весь цикл агента +26 проверок: калькулятор, время, реестр, обрезка результатов, весь цикл агента, +настройки (tool_choice, подтверждение вызовов, история) (успех, ошибка инструмента, лимит раундов, история). Сеть не нужна — модель подменяется `FakeClient` из `tests/run.php`. @@ -217,10 +258,10 @@ final class LoggingClient implements ChatClient { public function __construct(private ChatClient $inner) {} - public function chat(array $messages, array $tools = []): ChatResult + public function chat(array $messages, array $tools = [], array $options = []): ChatResult { $started = microtime(true); - $result = $this->inner->chat($messages, $tools); + $result = $this->inner->chat($messages, $tools, $options); error_log(sprintf('LLM: %d мс, токенов %d', (microtime(true) - $started) * 1000, $result->usage['total_tokens'] ?? 0)); return $result; @@ -246,18 +287,31 @@ $agent = new Agent(new LoggingClient(AiClient::fromEnv()), $tools); ```php // Клиент $client = AiClient::fromEnv(); -$result = $client->chat($messages, $tools = []); +$result = $client->chat($messages, $tools = [], $options = []); +// options: tool_choice, parallel_tool_calls, temperature, max_tokens $result->text; $result->toolCalls; $result->usage; // Агент -$agent = new Agent($client, $tools, $systemPrompt = '...', $maxRounds = 5); +$agent = new Agent( + client: $client, + tools: $tools, + systemPrompt: '...', + maxRounds: 5, + toolChoice: 'auto', // auto | none | required | имя + parallelToolCalls: true, + historyLimit: 40, // 0 — без обрезки + toolApproval: fn ($name, $args): bool => true, +); $agent->ask('вопрос'); // string -$agent->trace(); // [{name, arguments, output, ms}] +$agent->trace(); // [{name, arguments, output, ms, blocked}] $agent->messages(); // вся история $agent->setSystemPrompt('новый промпт'); // на ходу, история сохраняется $agent->systemPrompt(); // текущий промпт $agent->reset(); +// Агент целиком из .env +$agent = Agent::fromEnv($tools, 'Отвечай кратко.'); + // Реестр $registry = (new ToolRegistry($maxResultChars = 4000))->add($tool1, $tool2); $registry->definitions(); // схемы для модели diff --git a/examples/05-settings.php b/examples/05-settings.php new file mode 100644 index 0000000..3839686 --- /dev/null +++ b/examples/05-settings.php @@ -0,0 +1,69 @@ +add(new TimeTool(), new CalculatorTool()); +$client = AiClient::fromEnv(); + +// --- 1. tool_choice: 'required' — модель обязана вызвать хоть что-то -------- +// Вопрос не требует инструментов, но настройка заставляет модель действовать. + +$forced = new Agent($client, $tools, 'Отвечай одной строкой.', 3, 'required'); + +echo "1) tool_choice=required\n"; +echo ' ответ: ' . $forced->ask('Поздоровайся со мной.') . PHP_EOL; +echo ' вызовов: ' . count($forced->trace()) . PHP_EOL . PHP_EOL; + +// --- 2. toolApproval: запрет вызова ---------------------------------------- +// Колбэк получает имя и аргументы. false — инструмент не выполняется, +// модель получает текст отказа и пытается ответить иначе. + +$blocked = new Agent( + client: $client, + tools: $tools, + systemPrompt: 'Отвечай одной строкой.', + maxRounds: 3, + toolApproval: static function (string $name, array $arguments): bool { + echo ' запрос: ' . $name . ' ' . json_encode($arguments, JSON_UNESCAPED_UNICODE) . PHP_EOL; + + // Разрешаем только калькулятор, «время» считаем запрещённым. + return $name === 'calculator'; + }, +); + +echo "2) toolApproval: get_time запрещён\n"; +echo ' ответ: ' . $blocked->ask('Который час в Москве?') . PHP_EOL; + +foreach ($blocked->trace() as $step) { + echo ' ' . $step['name'] . ' → ' . ($step['blocked'] ? 'ЗАПРЕЩЁН' : $step['output']) . PHP_EOL; +} + +// --- 3. historyLimit ------------------------------------------------------- +// В .env это AI_HISTORY_LIMIT. Обрезает старые ходы, system и текущий +// вопрос остаются. Ноль — не обрезать. + +echo PHP_EOL . "3) размер истории после двух вопросов\n"; +$memory = new Agent($client, $tools, 'Отвечай одним словом.', 3, 'auto', true, 40); +$memory->ask('Меня зовут Роман.'); +$memory->ask('Как меня зовут?'); +echo ' сообщений в истории: ' . count($memory->messages()) . ' (лимит 40)' . PHP_EOL; diff --git a/src/Agent.php b/src/Agent.php index 8fb5cd5..1bfb9b4 100644 --- a/src/Agent.php +++ b/src/Agent.php @@ -15,6 +15,19 @@ use AiSdk\Tools\TimeTool; * * Внутри: отправили вопрос -> модель попросила инструменты -> выполнили -> * отправили результаты -> получили ответ. И так до maxRounds. + * + * Настройки — именованными аргументами конструктора: + * + * new Agent( + * client: $client, + * tools: $tools, + * systemPrompt: '...', + * maxRounds: 5, // предохранитель от зацикливания + * toolChoice: 'auto', // auto | none | required | имя инструмента + * parallelToolCalls: true, // разрешить модели батчить вызовы + * historyLimit: 40, // сколько сообщений держать (0 — без лимита) + * toolApproval: fn ($name, $args) => $name !== 'drop_database', + * ); */ final class Agent { @@ -27,20 +40,54 @@ final class Agent /** @var list> */ private array $messages = []; - /** @var list, output: string, ms: int}> */ + /** @var list, output: string, ms: int, blocked: bool}> */ private array $trace = []; private string $systemPrompt; + /** + * @param string $toolChoice 'auto' — решает модель, 'none' — запретить вызов, + * 'required' — обязать вызвать хоть что-то, + * иначе считается именем конкретного инструмента. + * @param bool $parallelToolCalls если false, отправляется + * parallel_tool_calls=false и модель не батчит вызовы. + * @param int $historyLimit максимум сообщений в истории перед вопросом + * (0 — не обрезать). System и текущий вопрос сохраняются. + * @param (\Closure(string, array): bool)|null $toolApproval + * хук перед выполнением инструмента. Вернул false — вызов запрещён, + * модель получит текст отказа. Удобно для подтверждения опасных действий. + */ public function __construct( private readonly ChatClient $client, private readonly ToolRegistry $tools = new ToolRegistry(), string $systemPrompt = self::DEFAULT_SYSTEM_PROMPT, private readonly int $maxRounds = 5, + private readonly string $toolChoice = 'auto', + private readonly bool $parallelToolCalls = true, + private readonly int $historyLimit = 40, + private readonly ?\Closure $toolApproval = null, ) { $this->systemPrompt = $systemPrompt; } + /** + * Агент из настроек .env (AI_*), с переданными инструментами. + */ + public static function fromEnv( + ToolRegistry $tools = new ToolRegistry(), + string $systemPrompt = self::DEFAULT_SYSTEM_PROMPT, + ): self { + return new self( + client: AiClient::fromEnv(), + tools: $tools, + systemPrompt: $systemPrompt, + maxRounds: Env::int('AI_MAX_ROUNDS', 5), + toolChoice: Env::get('AI_TOOL_CHOICE', 'auto') ?? 'auto', + parallelToolCalls: Env::bool('AI_PARALLEL_TOOL_CALLS', true), + historyLimit: Env::int('AI_HISTORY_LIMIT', 40), + ); + } + /** * Сменить системный промпт на ходу. * @@ -72,8 +119,12 @@ final class Agent } $this->messages[] = ['role' => 'user', 'content' => $question]; + $this->trimHistory(); - $result = $this->chat(); + // tool_choice применяется только к первому запросу хода: иначе + // 'required' заставит модель звать инструменты в каждом раунде и она + // никогда не сможет дать ответ. + $result = $this->chat(true); $round = 0; while ($result->hasToolCalls() && $round < $this->maxRounds) { @@ -84,24 +135,10 @@ final class Agent $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, - ]; + $this->messages[] = $this->runTool($call); } - $result = $this->chat(); + $result = $this->chat(false); } // Модель зациклилась на инструментах — просим ответить без них. @@ -111,6 +148,7 @@ final class Agent 'content' => 'Лимит вызовов инструментов исчерпан. Ответь на вопрос без инструментов.', ]; + // Без инструментов и без tool_choice: иначе API может отвергнуть запрос. $result = $this->client->chat($this->messages, []); } @@ -131,9 +169,9 @@ final class Agent } /** - * Что реально вызывалось: имя, аргументы, результат, время. + * Что реально вызывалось: имя, аргументы, результат, время, был ли отказ. * - * @return list, output: string, ms: int}> + * @return list, output: string, ms: int, blocked: bool}> */ public function trace(): array { @@ -149,9 +187,133 @@ final class Agent $this->trace = []; } - private function chat(): ChatResult + /** + * Выполнить один вызов инструмента (с учётом хука подтверждения) + * и вернуть tool-сообщение для истории. + * + * @param array{id: string, name: string, arguments: array} $call + * @return array + */ + private function runTool(array $call): array { - return $this->client->chat($this->messages, $this->tools->definitions()); + $started = microtime(true); + $blocked = false; + + if ($this->toolApproval !== null && !$this->approve($call['name'], $call['arguments'])) { + $blocked = true; + $output = 'Вызов инструмента "' . $call['name'] . '" отклонён оператором.'; + } else { + $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), + 'blocked' => $blocked, + ]; + + return [ + 'role' => 'tool', + 'tool_call_id' => $call['id'], + 'content' => $output, + ]; + } + + /** + * @param array $arguments + */ + private function approve(string $name, array $arguments): bool + { + try { + return $this->toolApproval === null + || ($this->toolApproval)($name, $arguments) === true; + } catch (\Throwable) { + // Упавший хук считаем запретом: безопаснее не выполнять действие. + return false; + } + } + + /** + * Обрезать историю до historyLimit сообщений. + * + * Режем целыми ходами: system и текущий вопрос остаются, а «осиротевшие» + * tool-сообщения в начале недопустимы — API отвергнет такой запрос. + */ + private function trimHistory(): void + { + if ($this->historyLimit <= 0) { + return; + } + + $count = count($this->messages); + + if ($count <= $this->historyLimit) { + return; + } + + $keepFrom = $count - $this->historyLimit; + + // Нельзя начинать с role:tool — у результата не будет своего вызова. + while ($keepFrom < $count && ($this->messages[$keepFrom]['role'] ?? '') === 'tool') { + $keepFrom++; + } + + // Текущий вопрос (последний user) трогать нельзя. + $lastUser = 0; + + foreach ($this->messages as $index => $message) { + if (($message['role'] ?? '') === 'user') { + $lastUser = $index; + } + } + + if ($keepFrom > $lastUser) { + $keepFrom = $lastUser; + } + + if ($keepFrom <= 0) { + return; + } + + $head = []; + + if (($this->messages[0]['role'] ?? '') === 'system') { + $head[] = $this->messages[0]; + } + + $this->messages = array_merge($head, array_slice($this->messages, $keepFrom)); + } + + /** + * @param bool $withToolChoice применять ли tool_choice (только первый + * запрос хода, дальше — auto) + * @return array + */ + private function chatOptions(bool $withToolChoice): array + { + $options = []; + + if ($withToolChoice && $this->toolChoice !== '' && $this->toolChoice !== 'auto') { + $options['tool_choice'] = $this->toolChoice; + } + + // Значение по умолчанию у провайдеров и так true — шлём только false. + if (!$this->parallelToolCalls) { + $options['parallel_tool_calls'] = false; + } + + return $options; + } + + private function chat(bool $withToolChoice = false): ChatResult + { + return $this->client->chat( + $this->messages, + $this->tools->definitions(), + $this->chatOptions($withToolChoice), + ); } /** diff --git a/src/AiClient.php b/src/AiClient.php index 6faa0d5..2a33bda 100644 --- a/src/AiClient.php +++ b/src/AiClient.php @@ -59,19 +59,23 @@ final class AiClient implements ChatClient ); } - public function chat(array $messages, array $tools = []): ChatResult + public function chat(array $messages, array $tools = [], array $options = []): ChatResult { $body = [ 'model' => $this->model, 'messages' => $messages, 'stream' => false, - 'temperature' => $this->temperature, - 'max_tokens' => $this->maxTokens, + 'temperature' => isset($options['temperature']) ? (float) $options['temperature'] : $this->temperature, + 'max_tokens' => isset($options['max_tokens']) ? (int) $options['max_tokens'] : $this->maxTokens, ]; if ($tools !== []) { $body['tools'] = $tools; - $body['tool_choice'] = 'auto'; + $body['tool_choice'] = self::normalizeToolChoice($options['tool_choice'] ?? 'auto'); + + if (array_key_exists('parallel_tool_calls', $options)) { + $body['parallel_tool_calls'] = (bool) $options['parallel_tool_calls']; + } } $body = array_merge($body, $this->extraBody); @@ -160,6 +164,26 @@ final class AiClient implements ChatClient return $calls; } + /** + * Привести tool_choice к формату OpenAI. + * + * @param string|array $choice + * @return string|array + */ + private static function normalizeToolChoice(string|array $choice): string|array + { + if (is_array($choice)) { + return $choice; + } + + if (in_array($choice, ['auto', 'none', 'required'], true)) { + return $choice; + } + + // Имя конкретного инструмента -> объект. + return ['type' => 'function', 'function' => ['name' => $choice]]; + } + /** * Подсказка при типовой ошибке TLS на Windows. */ diff --git a/src/ChatClient.php b/src/ChatClient.php index e15ea54..e3d293f 100644 --- a/src/ChatClient.php +++ b/src/ChatClient.php @@ -13,6 +13,10 @@ interface ChatClient /** * @param list> $messages история диалога * @param list> $tools определения в формате OpenAI + * @param array $options + * tool_choice — 'auto' | 'none' | 'required' | имя функции + * parallel_tool_calls — разрешить модели батчить вызовы + * temperature, max_tokens — переопределить настройки клиента */ - public function chat(array $messages, array $tools = []): ChatResult; + public function chat(array $messages, array $tools = [], array $options = []): ChatResult; } diff --git a/tests/run.php b/tests/run.php index cd6f548..42e233a 100644 --- a/tests/run.php +++ b/tests/run.php @@ -74,7 +74,7 @@ function assertContains(string $needle, string $haystack, string $message = ''): */ final class FakeClient implements ChatClient { - /** @var list, tools: array}> */ + /** @var list, tools: array, options: array}> */ public array $requests = []; /** @@ -84,9 +84,9 @@ final class FakeClient implements ChatClient { } - public function chat(array $messages, array $tools = []): ChatResult + public function chat(array $messages, array $tools = [], array $options = []): ChatResult { - $this->requests[] = ['messages' => $messages, 'tools' => $tools]; + $this->requests[] = ['messages' => $messages, 'tools' => $tools, 'options' => $options]; $result = array_shift($this->results); @@ -351,6 +351,161 @@ test('агент: без явного промпта берётся встрое assertTrue($agent->systemPrompt() !== '', 'промпт по умолчанию пустой'); }); +test('агент: tool_choice не навязывается на повторных раундах', function (): void { + $client = new FakeClient([ + toolCall('calculator', ['expression' => '2+2'], 'c1'), + textResult('4'), + ]); + + $agent = new Agent( + $client, + (new ToolRegistry())->add(new CalculatorTool()), + 'тест', + 3, + 'required', + ); + + $agent->ask('посчитай'); + + assertSame('required', $client->requests[0]['options']['tool_choice'] ?? null); + assertTrue( + !isset($client->requests[1]['options']['tool_choice']), + 'во втором раунде tool_choice должен вернуться к auto, иначе модель зациклится' + ); +}); + +// --------------------------------------------------------------------------- +// Настройки агента +// --------------------------------------------------------------------------- + +test('настройки: tool_choice уходит в клиент', function (): void { + $client = new FakeClient([textResult('ок')]); + $agent = new Agent($client, new ToolRegistry(), 'тест', 3, 'required'); + + $agent->ask('вопрос'); + + assertSame('required', $client->requests[0]['options']['tool_choice'] ?? null); +}); + +test('настройки: tool_choice по умолчанию не навязывается', function (): void { + $client = new FakeClient([textResult('ок')]); + $agent = new Agent($client, new ToolRegistry(), 'тест', 3); + + $agent->ask('вопрос'); + + assertTrue(!isset($client->requests[0]['options']['tool_choice']), 'auto не должен уходить явно'); +}); + +test('настройки: parallel_tool_calls=false отправляется только когда выключено', function (): void { + $off = new FakeClient([textResult('ок')]); + (new Agent($off, new ToolRegistry(), 'тест', 3, 'auto', false))->ask('вопрос'); + + assertSame(false, $off->requests[0]['options']['parallel_tool_calls']); + + $on = new FakeClient([textResult('ок')]); + (new Agent($on, new ToolRegistry(), 'тест', 3, 'auto', true))->ask('вопрос'); + + assertTrue(!isset($on->requests[0]['options']['parallel_tool_calls']), 'true — это значение по умолчанию'); +}); + +test('настройки: хук может запретить вызов инструмента', function (): void { + $client = new FakeClient([ + toolCall('calculator', ['expression' => '2+2'], 'c1'), + textResult('Не смог: действие запрещено.'), + ]); + + $agent = new Agent( + $client, + (new ToolRegistry())->add(new CalculatorTool()), + 'тест', + 3, + 'auto', + true, + 40, + static fn (string $name, array $args): bool => false, + ); + + $agent->ask('посчитай'); + + assertTrue($agent->trace()[0]['blocked'], 'вызов должен быть помечен как отклонённый'); + assertContains('отклонён оператором', $agent->trace()[0]['output']); + + $messages = $client->requests[1]['messages']; + $last = $messages[count($messages) - 1]; + assertContains('отклонён оператором', $last['content']); +}); + +test('настройки: хук пропускает разрешённый вызов', function (): void { + $client = new FakeClient([ + toolCall('calculator', ['expression' => '2+2'], 'c1'), + textResult('4'), + ]); + + $seen = null; + $agent = new Agent( + $client, + (new ToolRegistry())->add(new CalculatorTool()), + 'тест', + 3, + 'auto', + true, + 40, + static function (string $name, array $args) use (&$seen): bool { + $seen = [$name, $args]; + + return true; + }, + ); + + $agent->ask('посчитай'); + + assertSame('calculator', $seen[0]); + assertSame('2+2', $seen[1]['expression']); + assertSame(false, $agent->trace()[0]['blocked']); + assertSame('2+2 = 4', $agent->trace()[0]['output']); +}); + +test('настройки: historyLimit обрезает историю целыми ходами', function (): void { + $client = new FakeClient([ + textResult('a1'), + textResult('a2'), + textResult('a3'), + textResult('a4'), + ]); + + $agent = new Agent($client, new ToolRegistry(), 'тест', 3, 'auto', true, 4); + + $agent->ask('вопрос 1'); + $agent->ask('вопрос 2'); + $agent->ask('вопрос 3'); + $agent->ask('вопрос 4'); + + $messages = $agent->messages(); + + assertSame('system', $messages[0]['role'], 'system должен оставаться первым'); + assertTrue(($messages[1]['role'] ?? '') !== 'tool', 'история не должна начинаться с tool'); + + // Обрезка идёт Перед запросом: лимит 4 + system + финальный ответ. + assertSame(6, count($messages), 'без лимита было бы 9'); + + $last = $messages[count($messages) - 1]; + $question = $messages[count($messages) - 2]; + + assertSame('user', $question['role']); + assertSame('вопрос 4', $question['content'], 'текущий вопрос должен сохраниться'); + assertSame('assistant', $last['role']); +}); + +test('настройки: historyLimit=0 отключает обрезку', function (): void { + $client = new FakeClient([textResult('a'), textResult('b')]); + $agent = new Agent($client, new ToolRegistry(), 'тест', 3, 'auto', true, 0); + + $agent->ask('раз'); + $agent->ask('два'); + + assertSame(5, count($agent->messages()), 'system + 2 вопроса + 2 ответа'); +}); + test('агент: reset очищает историю и трассировку', function (): void { $client = new FakeClient([textResult('ответ')]); $agent = new Agent($client, new ToolRegistry(), 'ты тестовый', 3);