diff --git a/README.md b/README.md index 45b5e07..d2b6ca7 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ src/ ChatClient.php интерфейс (для тестов) ChatResult.php ответ модели: текст, tool_calls, usage Agent.php цикл: вопрос → инструменты → ответ - AgentHooks.php колбэки хода: шаг, инструмент, ответ, остановка + AgentHooks.php колбэки хода: шаг, инструмент, остановка LoggingClient.php декоратор: логи запросов и ответов Cost.php оценка стоимости по токенам и тарифу Tool.php интерфейс инструмента @@ -266,3 +266,4 @@ $agent->ask('вопрос'); + diff --git a/docs/examples.md b/docs/examples.md index 1652efc..da9d15f 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -18,7 +18,7 @@ | `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 | +| `14-hooks.php` | прогресс и остановка | `get_time`, `calculator` | `hooks`: onStep, onToolStart, onToolEnd, shouldStop | `10-http.php` и `11-json.php` работают без модели и без сети — их можно запускать где угодно. Остальные обращаются к модели из `.env`. @@ -26,3 +26,4 @@ + diff --git a/docs/reference.md b/docs/reference.md index 84625c6..9cfa1af 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -90,7 +90,6 @@ $agent = new Agent( 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, ), ); @@ -118,3 +117,4 @@ $tools->add(new FinishTool()); + diff --git a/examples/14-hooks.php b/examples/14-hooks.php index 8e38407..3d871ef 100644 --- a/examples/14-hooks.php +++ b/examples/14-hooks.php @@ -6,8 +6,8 @@ declare(strict_types=1); * Пример 14. Хуки агента: прогресс, инструменты, остановка. * * Инструменты: get_time, calculator. - * Флаги: hooks (AgentHooks с onStep, onToolStart, onToolEnd, onAnswer, - * shouldStop). + * Флаги: hooks (AgentHooks с onStep, onToolStart, onToolEnd, shouldStop). + * shouldStop проверяется между раундами. * * Хуки — это колбэки без логики: агент вызывает их в ходе работы, а вы решаете, * что делать — печатать прогресс, писать лог, показать кнопку «стоп». @@ -36,7 +36,6 @@ $hooks = new AgentHooks( 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( @@ -48,7 +47,7 @@ $agent = new Agent( ); echo '1) обычный ход' . PHP_EOL; -$agent->ask('Который час в Москве и сколько будет 2+2?'); +echo 'ответ: ' . $agent->ask('Который час в Москве и сколько будет 2+2?') . PHP_EOL; // 2. Остановка: shouldStop проверяется между раундами, поэтому история // остаётся целой, а модель больше не вызывается. @@ -66,3 +65,5 @@ $stopped = new Agent( ); echo 'ответ: ' . $stopped->ask('Который час в Москве?') . PHP_EOL; + + diff --git a/src/Agent.php b/src/Agent.php index 91aaf72..deb2bb6 100644 --- a/src/Agent.php +++ b/src/Agent.php @@ -4,7 +4,6 @@ declare(strict_types=1); namespace AiSdk; - /** * Диалог с моделью и цикл вызова инструментов. * @@ -173,7 +172,6 @@ final class Agent $text = $result->text !== '' ? $result->text : '(модель вернула пустой ответ)'; $this->messages[] = ['role' => 'assistant', 'content' => $text]; - $this->hooks?->answer($text); return $text; } @@ -341,7 +339,6 @@ final class Agent { $text = $result !== '' ? $result : '(модель завершила работу без результата)'; $this->messages[] = ['role' => 'assistant', 'content' => $text]; - $this->hooks?->answer($text); return $text; } @@ -468,3 +465,4 @@ final class Agent */ } + diff --git a/src/AgentHooks.php b/src/AgentHooks.php index 8dc014e..0180108 100644 --- a/src/AgentHooks.php +++ b/src/AgentHooks.php @@ -8,8 +8,8 @@ namespace AiSdk; * Колбэки хода работы агента. * * Нужны, чтобы интерфейс (CLI, веб, лог) видел, что происходит, в реальном - * времени: номер шага, начало и конец инструмента, финальный ответ и запрос - * на остановку. Любой колбэк можно не задавать. + * времени: номер шага, начало и конец инструмента и запрос на остановку. + * Любой колбэк можно не задавать. * * $agent = new Agent( * client: $client, @@ -29,14 +29,12 @@ final class AgentHooks * @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, ) { } @@ -62,11 +60,6 @@ final class AgentHooks $this->fire($this->onToolEnd, $step); } - public function answer(string $text): void - { - $this->fire($this->onAnswer, $text); - } - /** * Пользователь попросил остановиться. Проверяется между раундами, * чтобы история осталась согласованной. diff --git a/tests/cases/hooks.php b/tests/cases/hooks.php index d82aa31..9584649 100644 --- a/tests/cases/hooks.php +++ b/tests/cases/hooks.php @@ -23,9 +23,6 @@ test('hooks: шаги, инструменты и ответ идут по пор onToolEnd: static function (array $step) use (&$events): void { $events[] = 'end ' . $step['name'] . ' -> ' . $step['output']; }, - onAnswer: static function (string $text) use (&$events): void { - $events[] = 'answer ' . $text; - }, ); $client = new FakeClient([ @@ -48,7 +45,6 @@ test('hooks: шаги, инструменты и ответ идут по пор 'start calculator', 'end calculator -> 2+2 = 4', 'step 2/3', - 'answer 4', ], $events); }); @@ -97,9 +93,6 @@ test('hooks: finish виден как инструмент и как ответ' 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([ @@ -115,5 +108,6 @@ test('hooks: finish виден как инструмент и как ответ' ); assertSame('готово', $agent->ask('сделай')); - assertSame(['start finish', 'answer готово'], $events); + assertSame(['start finish'], $events); }); +