Middleware и события
Middleware в AI SDK позволяют вклиниться в обработку промпта.
Создание
namespace App\Ai\Middleware;
use Closure;
use Laravel\Ai\Responses\AgentResponse;
use Laravel\Ai\Values\AgentPrompt;
class LogPrompt
{
public function handle(AgentPrompt $prompt, Closure $next)
{
Log::info('AI prompt', ['text' => $prompt->text]);
return $next($prompt)->then(function (AgentResponse $response) {
Log::info('AI response', ['text' => $response->text]);
});
}
}
Подключение
use Laravel\Ai\Attributes\WithMiddleware;
#[WithMiddleware(LogPrompt::class)]
class SupportAgent implements Agent
then() в ответе
$response = (new SupportAgent)->prompt('Привет');
$response->then(function (AgentResponse $response) {
// после завершения
});
События
SDK отправляет события Laravel. Можно слушать:
Event::listen(AgentResponded::class, function ($event) {
Log::info('Agent responded', ['text' => $event->response->text]);
});
Middleware для шагов
Middleware выполняется на каждом шаге агента (при вызове tools). Можно:
- Менять модель
- Убирать tools
- Суммировать историю
- Возвращать кеш
public function handle(AgentPrompt $prompt, Closure $next)
{
// модификация перед шагом
$response = $next($prompt);
// после шага
return $response;
}
Итоги
- Middleware для логирования, модификации
handle(AgentPrompt, Closure)then()в ответе- События Laravel
- Middleware на каждом шаге