From 4c25111c0e18cdef7a7b43bfcb9b1daca5d8f595 Mon Sep 17 00:00:00 2001 From: rsgrinko Date: Fri, 13 Nov 2026 00:25:45 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20=D1=85=D1=83=D0=BA=D0=B8=20=D0=B0=D0=B3?= =?UTF-8?q?=D0=B5=D0=BD=D1=82=D0=B0=20=E2=80=94=20=D1=88=D0=B0=D0=B3=D0=B8?= =?UTF-8?q?,=20=D0=B8=D0=BD=D1=81=D1=82=D1=80=D1=83=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D1=82=D1=8B,=20=D0=BE=D1=82=D0=B2=D0=B5=D1=82,=20=D0=BE=D1=81?= =?UTF-8?q?=D1=82=D0=B0=D0=BD=D0=BE=D0=B2=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - AgentHooks: onStep, onToolStart, onToolEnd, onAnswer, shouldStop - Agent принимает hooks (и в fromEnv); исключение в колбэке не ломает ответ - остановка проверяется между раундами, история остаётся валидной - пример 14: прогресс в консоли и остановка после первого раунда - 116 тестов --- README.md | 3 ++ docs/examples.md | 2 + docs/reference.md | 14 +++++ examples/14-hooks.php | 68 ++++++++++++++++++++++++ src/Agent.php | 27 ++++++++++ src/AgentHooks.php | 99 +++++++++++++++++++++++++++++++++++ tests/cases/hooks.php | 119 ++++++++++++++++++++++++++++++++++++++++++ 7 files changed, 332 insertions(+) create mode 100644 examples/14-hooks.php create mode 100644 src/AgentHooks.php create mode 100644 tests/cases/hooks.php diff --git a/README.md b/README.md index c6ee331..45b5e07 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,7 @@ src/ ChatClient.php интерфейс (для тестов) ChatResult.php ответ модели: текст, tool_calls, usage Agent.php цикл: вопрос → инструменты → ответ + AgentHooks.php колбэки хода: шаг, инструмент, ответ, остановка LoggingClient.php декоратор: логи запросов и ответов Cost.php оценка стоимости по токенам и тарифу Tool.php интерфейс инструмента @@ -86,6 +87,7 @@ examples/ 11-json.php инструменты без модели 12-logging.php логирование запросов к модели 13-code-task.php задача «с нуля»: код, тест, правка + 14-hooks.php прогресс в консоли и остановка через хуки tests/run.php раннер тестов tests/support.php помощники, заглушки, FakeClient tests/cases/ тесты по темам (agent, files, http, shell, ...) @@ -263,3 +265,4 @@ $agent->ask('вопрос'); + diff --git a/docs/examples.md b/docs/examples.md index 756bb45..1652efc 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -18,9 +18,11 @@ | `11-json.php` | инструменты без модели | `json_query`, `convert_units`, `date_calc`, `uuid`, `hash_text` | — | | `12-logging.php` | логи запросов | `get_time`, `calculator` | `verbose`, `sink` | | `13-code-task.php` | агент пишет код и проверяет тестом | `read_file`, `write_file`, `replace_in_file`, `list_dir`, `run_command` | `workdir`, `allow`, `maxRounds` | +| `14-hooks.php` | прогресс и остановка | `get_time`, `calculator` | `hooks`: onStep, onToolStart, onToolEnd, onAnswer, shouldStop | `10-http.php` и `11-json.php` работают без модели и без сети — их можно запускать где угодно. Остальные обращаются к модели из `.env`. + diff --git a/docs/reference.md b/docs/reference.md index 85e88d9..84625c6 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -82,6 +82,19 @@ $agent->setSystemPrompt('новый промпт'); // на ходу, истор $agent->systemPrompt(); // текущий промпт $agent->reset(); +// Хуки хода +$agent = new Agent( + client: $client, + tools: $tools, + hooks: new AgentHooks( + onStep: fn (int $step, int $max) => print("шаг {$step}/{$max}\n"), + onToolStart: fn (string $name, array $args) => print("→ {$name}\n"), + onToolEnd: fn (array $s) => print(' ' . mb_substr($s['output'], 0, 60) . "\n"), + onAnswer: fn (string $text) => print("ответ: {$text}\n"), + shouldStop: fn (): bool => false, + ), +); + // Агент целиком из .env $agent = Agent::fromEnv($tools, 'Отвечай кратко.'); @@ -104,3 +117,4 @@ $tools->add(new FinishTool()); + diff --git a/examples/14-hooks.php b/examples/14-hooks.php new file mode 100644 index 0000000..8e38407 --- /dev/null +++ b/examples/14-hooks.php @@ -0,0 +1,68 @@ +add(new TimeTool(), new CalculatorTool()); + +// 1. Полный набор хуков: как это выглядит в консоли. +$hooks = new AgentHooks( + onStep: static fn (int $step, int $max) => print("шаг {$step}/{$max}" . PHP_EOL), + onToolStart: static fn (string $name, array $args) => print( + ' → ' . $name . ' ' . json_encode($args, JSON_UNESCAPED_UNICODE) . PHP_EOL + ), + onToolEnd: static fn (array $step) => print( + ' ← ' . mb_substr(str_replace("\n", ' ', $step['output']), 0, 70) . PHP_EOL + ), + onAnswer: static fn (string $text) => print('ответ: ' . $text . PHP_EOL), +); + +$agent = new Agent( + client: AiClient::fromEnv(timeout: 120.0), + tools: $tools, + systemPrompt: 'Отвечай кратко, одной строкой.', + maxRounds: 4, + hooks: $hooks, +); + +echo '1) обычный ход' . PHP_EOL; +$agent->ask('Который час в Москве и сколько будет 2+2?'); + +// 2. Остановка: shouldStop проверяется между раундами, поэтому история +// остаётся целой, а модель больше не вызывается. +echo PHP_EOL . '2) shouldStop: остановка после первого раунда' . PHP_EOL; + +$stopped = new Agent( + client: AiClient::fromEnv(timeout: 120.0), + tools: $tools, + systemPrompt: 'Отвечай кратко.', + maxRounds: 4, + hooks: new AgentHooks( + onStep: static fn (int $step, int $max) => print("шаг {$step}/{$max}" . PHP_EOL), + shouldStop: static fn (): bool => true, + ), +); + +echo 'ответ: ' . $stopped->ask('Который час в Москве?') . PHP_EOL; diff --git a/src/Agent.php b/src/Agent.php index d9b00a0..91aaf72 100644 --- a/src/Agent.php +++ b/src/Agent.php @@ -69,6 +69,7 @@ final class Agent private readonly int $historyLimit = 40, private readonly ?\Closure $toolApproval = null, private readonly string $finishTool = 'finish', + private readonly ?AgentHooks $hooks = null, ) { $this->systemPrompt = $systemPrompt; } @@ -79,6 +80,7 @@ final class Agent public static function fromEnv( ToolRegistry $tools = new ToolRegistry(), string $systemPrompt = self::DEFAULT_SYSTEM_PROMPT, + ?AgentHooks $hooks = null, ): self { return new self( client: AiClient::fromEnv(), @@ -89,6 +91,7 @@ final class Agent parallelToolCalls: Env::bool('AI_PARALLEL_TOOL_CALLS', true), historyLimit: Env::int('AI_HISTORY_LIMIT', 40), finishTool: Env::get('AI_FINISH_TOOL', 'finish') ?? 'finish', + hooks: $hooks, ); } @@ -128,6 +131,8 @@ final class Agent // tool_choice применяется только к первому запросу хода: иначе // 'required' заставит модель звать инструменты в каждом раунде и она // никогда не сможет дать ответ. + $request = 1; + $this->fireStep($request); $result = $this->chat(true); $round = 0; @@ -144,6 +149,13 @@ final class Agent return $this->finish($finished); } + // Остановку проверяем между раундами: недоделанных вызовов нет, + // история остаётся валидной. + if ($this->hooks?->stopRequested() === true) { + return $this->finish('Остановлено пользователем.'); + } + + $this->fireStep(++$request); $result = $this->chat(false); } @@ -155,11 +167,13 @@ final class Agent ]; // Без инструментов и без tool_choice: иначе API может отвергнуть запрос. + $this->fireStep(++$request); $result = $this->send($this->messages, []); } $text = $result->text !== '' ? $result->text : '(модель вернула пустой ответ)'; $this->messages[] = ['role' => 'assistant', 'content' => $text]; + $this->hooks?->answer($text); return $text; } @@ -216,6 +230,8 @@ final class Agent $started = microtime(true); $blocked = false; + $this->hooks?->toolStart($call['name'], $call['arguments']); + if ($this->toolApproval !== null && !$this->approve($call['name'], $call['arguments'])) { $blocked = true; $output = 'Вызов инструмента "' . $call['name'] . '" отклонён оператором.'; @@ -231,6 +247,8 @@ final class Agent 'blocked' => $blocked, ]; + $this->hooks?->toolEnd($this->trace[count($this->trace) - 1]); + return [ 'role' => 'tool', 'tool_call_id' => $call['id'], @@ -262,6 +280,7 @@ final class Agent } if ($this->isFinishCall($call)) { + $this->hooks?->toolStart($call['name'], $call['arguments']); $finished = $this->finishResult($call); $this->trace[] = [ @@ -272,6 +291,8 @@ final class Agent 'blocked' => false, ]; + $this->hooks?->toolEnd($this->trace[count($this->trace) - 1]); + $this->messages[] = [ 'role' => 'tool', 'tool_call_id' => $call['id'], @@ -320,10 +341,16 @@ final class Agent { $text = $result !== '' ? $result : '(модель завершила работу без результата)'; $this->messages[] = ['role' => 'assistant', 'content' => $text]; + $this->hooks?->answer($text); return $text; } + private function fireStep(int $step): void + { + $this->hooks?->step($step, $this->maxRounds); + } + /** * @param array $arguments */ diff --git a/src/AgentHooks.php b/src/AgentHooks.php new file mode 100644 index 0000000..8dc014e --- /dev/null +++ b/src/AgentHooks.php @@ -0,0 +1,99 @@ + print("→ {$name}\n"), + * onToolEnd: fn (array $step) => print(' ' . mb_substr($step['output'], 0, 60) . "\n"), + * ), + * ); + * + * Исключение внутри колбэка не ломает агента: оно проглатывается. + */ +final class AgentHooks +{ + /** + * @param (\Closure(int, int): void)|null $onStep номер запроса к модели и предел раундов + * @param (\Closure(string, array): void)|null $onToolStart имя инструмента и аргументы + * @param (\Closure(array{name: string, arguments: array, output: string, ms: int, blocked: bool}): void)|null $onToolEnd + * запись трассировки после выполнения инструмента + * @param (\Closure(string): void)|null $onAnswer финальный текст ответа + * @param (\Closure(): bool)|null $shouldStop возвращает true — остановиться между раундами + */ + public function __construct( + public readonly ?\Closure $onStep = null, + public readonly ?\Closure $onToolStart = null, + public readonly ?\Closure $onToolEnd = null, + public readonly ?\Closure $onAnswer = null, + public readonly ?\Closure $shouldStop = null, + ) { + } + + public function step(int $step, int $max): void + { + $this->fire($this->onStep, $step, $max); + } + + /** + * @param array $arguments + */ + public function toolStart(string $name, array $arguments): void + { + $this->fire($this->onToolStart, $name, $arguments); + } + + /** + * @param array{name: string, arguments: array, output: string, ms: int, blocked: bool} $step + */ + public function toolEnd(array $step): void + { + $this->fire($this->onToolEnd, $step); + } + + public function answer(string $text): void + { + $this->fire($this->onAnswer, $text); + } + + /** + * Пользователь попросил остановиться. Проверяется между раундами, + * чтобы история осталась согласованной. + */ + public function stopRequested(): bool + { + if ($this->shouldStop === null) { + return false; + } + + try { + return ($this->shouldStop)() === true; + } catch (\Throwable) { + return false; + } + } + + private function fire(?\Closure $hook, mixed ...$arguments): void + { + if ($hook === null) { + return; + } + + try { + $hook(...$arguments); + } catch (\Throwable) { + // Колбэк логгера не должен ломать ответ агента. + } + } +} diff --git a/tests/cases/hooks.php b/tests/cases/hooks.php new file mode 100644 index 0000000..d82aa31 --- /dev/null +++ b/tests/cases/hooks.php @@ -0,0 +1,119 @@ + ' . $step['output']; + }, + onAnswer: static function (string $text) use (&$events): void { + $events[] = 'answer ' . $text; + }, + ); + + $client = new FakeClient([ + toolCall('calculator', ['expression' => '2+2'], 'c1'), + textResult('4'), + ]); + + $agent = new Agent( + client: $client, + tools: (new ToolRegistry())->add(new CalculatorTool()), + systemPrompt: 'тест', + maxRounds: 3, + hooks: $hooks, + ); + + assertSame('4', $agent->ask('посчитай')); + + assertSame([ + 'step 1/3', + 'start calculator', + 'end calculator -> 2+2 = 4', + 'step 2/3', + 'answer 4', + ], $events); +}); + +test('hooks: shouldStop останавливает между раундами', function (): void { + $client = new FakeClient([ + toolCall('calculator', ['expression' => '2+2'], 'c1'), + ]); + + $agent = new Agent( + client: $client, + tools: (new ToolRegistry())->add(new CalculatorTool()), + systemPrompt: 'тест', + maxRounds: 3, + hooks: new AgentHooks(shouldStop: static fn (): bool => true), + ); + + assertSame('Остановлено пользователем.', $agent->ask('посчитай')); + assertSame(1, count($client->requests), 'после остановки модель не вызывается'); + + $messages = $agent->messages(); + assertSame('assistant', $messages[count($messages) - 1]['role']); +}); + +test('hooks: исключение в колбэке не ломает ответ', function (): void { + $client = new FakeClient([textResult('ок')]); + + $agent = new Agent( + client: $client, + tools: new ToolRegistry(), + systemPrompt: 'тест', + maxRounds: 2, + hooks: new AgentHooks( + onStep: static function (): void { + throw new RuntimeException('лог упал'); + }, + ), + ); + + assertSame('ок', $agent->ask('вопрос')); +}); + +test('hooks: finish виден как инструмент и как ответ', function (): void { + $events = []; + + $hooks = new AgentHooks( + onToolStart: static function (string $name) use (&$events): void { + $events[] = 'start ' . $name; + }, + onAnswer: static function (string $text) use (&$events): void { + $events[] = 'answer ' . $text; + }, + ); + + $client = new FakeClient([ + toolCalls([['name' => 'finish', 'arguments' => ['result' => 'готово'], 'id' => 'f1']]), + ]); + + $agent = new Agent( + client: $client, + tools: (new ToolRegistry())->add(new FinishTool()), + systemPrompt: 'тест', + maxRounds: 2, + hooks: $hooks, + ); + + assertSame('готово', $agent->ask('сделай')); + assertSame(['start finish', 'answer готово'], $events); +});