refactor: убрать onAnswer из хуков агента
- onAnswer дублировал возврат Agent::ask() — убран - остались onStep, onToolStart, onToolEnd, shouldStop - пример 14 печатает ответ из возврата ask() - 116 тестов
This commit is contained in:
1 parent
4c25111c0e
commit
204d449519
7 files changed
+15
-27
No files matched your search
@@ -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('вопрос');
|
||||
|
||||
|
||||
|
||||
|
||||
+2
-1
@@ -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 @@
|
||||
|
||||
|
||||
|
||||
|
||||
+1
-1
@@ -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());
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
+1
-3
@@ -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
|
||||
*/
|
||||
}
|
||||
|
||||
|
||||
+2
-9
@@ -8,8 +8,8 @@ namespace AiSdk;
|
||||
* Колбэки хода работы агента.
|
||||
*
|
||||
* Нужны, чтобы интерфейс (CLI, веб, лог) видел, что происходит, в реальном
|
||||
* времени: номер шага, начало и конец инструмента, финальный ответ и запрос
|
||||
* на остановку. Любой колбэк можно не задавать.
|
||||
* времени: номер шага, начало и конец инструмента и запрос на остановку.
|
||||
* Любой колбэк можно не задавать.
|
||||
*
|
||||
* $agent = new Agent(
|
||||
* client: $client,
|
||||
@@ -29,14 +29,12 @@ final class AgentHooks
|
||||
* @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,
|
||||
) {
|
||||
}
|
||||
@@ -62,11 +60,6 @@ final class AgentHooks
|
||||
$this->fire($this->onToolEnd, $step);
|
||||
}
|
||||
|
||||
public function answer(string $text): void
|
||||
{
|
||||
$this->fire($this->onAnswer, $text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Пользователь попросил остановиться. Проверяется между раундами,
|
||||
* чтобы история осталась согласованной.
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user