feat: хуки агента — шаги, инструменты, ответ, остановка
- AgentHooks: onStep, onToolStart, onToolEnd, onAnswer, shouldStop - Agent принимает hooks (и в fromEnv); исключение в колбэке не ломает ответ - остановка проверяется между раундами, история остаётся валидной - пример 14: прогресс в консоли и остановка после первого раунда - 116 тестов
This commit is contained in:
1 parent
ab081a4dcd
commit
4c25111c0e
7 files changed
+332
No files matched your search
@@ -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
|
||||
*/
|
||||
|
||||
@@ -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) {
|
||||
// Колбэк логгера не должен ломать ответ агента.
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user