feat: хуки агента — шаги, инструменты, ответ, остановка

- AgentHooks: onStep, onToolStart, onToolEnd, onAnswer, shouldStop
- Agent принимает hooks (и в fromEnv); исключение в колбэке не ломает ответ
- остановка проверяется между раундами, история остаётся валидной
- пример 14: прогресс в консоли и остановка после первого раунда
- 116 тестов
This commit is contained in:
rsgrinko committed 2026-11-13 00:25:45 +03:00
1 parent ab081a4dcd
commit 4c25111c0e
7 files changed
+332

No files matched your search

+3
View File
@@ -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('вопрос');
+2
View File
@@ -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`.
+14
View File
@@ -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());
+68
View File
@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
/**
* Пример 14. Хуки агента: прогресс, инструменты, остановка.
*
* Инструменты: get_time, calculator.
* Флаги: hooks (AgentHooks с onStep, onToolStart, onToolEnd, onAnswer,
* shouldStop).
*
* Хуки — это колбэки без логики: агент вызывает их в ходе работы, а вы решаете,
* что делать — печатать прогресс, писать лог, показать кнопку «стоп».
*
* Запуск:
* php examples/14-hooks.php
*/
require dirname(__DIR__) . '/bootstrap.php';
use AiSdk\Agent;
use AiSdk\AgentHooks;
use AiSdk\AiClient;
use AiSdk\ToolRegistry;
use AiSdk\Tools\CalculatorTool;
use AiSdk\Tools\TimeTool;
$tools = (new ToolRegistry())->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;
+27
View File
@@ -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<string, mixed> $arguments
*/
+99
View File
@@ -0,0 +1,99 @@
<?php
declare(strict_types=1);
namespace AiSdk;
/**
* Колбэки хода работы агента.
*
* Нужны, чтобы интерфейс (CLI, веб, лог) видел, что происходит, в реальном
* времени: номер шага, начало и конец инструмента, финальный ответ и запрос
* на остановку. Любой колбэк можно не задавать.
*
* $agent = new Agent(
* client: $client,
* tools: $tools,
* hooks: new AgentHooks(
* onToolStart: fn (string $name, array $args) => 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<string, mixed>): void)|null $onToolStart имя инструмента и аргументы
* @param (\Closure(array{name: string, arguments: array<string, mixed>, 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<string, mixed> $arguments
*/
public function toolStart(string $name, array $arguments): void
{
$this->fire($this->onToolStart, $name, $arguments);
}
/**
* @param array{name: string, arguments: array<string, mixed>, 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) {
// Колбэк логгера не должен ломать ответ агента.
}
}
}
+119
View File
@@ -0,0 +1,119 @@
<?php
declare(strict_types=1);
// Тесты: хуки агента — шаги, инструменты, ответ, остановка.
use AiSdk\Agent;
use AiSdk\AgentHooks;
use AiSdk\ToolRegistry;
use AiSdk\Tools\CalculatorTool;
use AiSdk\Tools\FinishTool;
test('hooks: шаги, инструменты и ответ идут по порядку', function (): void {
$events = [];
$hooks = new AgentHooks(
onStep: static function (int $step, int $max) use (&$events): void {
$events[] = "step {$step}/{$max}";
},
onToolStart: static function (string $name, array $args) use (&$events): void {
$events[] = 'start ' . $name;
},
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([
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);
});