← Volver al blog

AI Orchestration en Laravel: construyendo un sistema multi-agente con colas, eventos y caché predictiva con Redis

2026-07-26

AI Orchestration en Laravel: construyendo un sistema multi-agente con colas, eventos y caché predictiva con Redis

La orquestación de agentes de IA representa uno de los desafíos arquitectónicos más interesantes en el desarrollo backend moderno. Cuando múltiples agentes especializados deben colaborar para resolver tareas complejas, necesitamos un sistema que gestione dependencias, priorice trabajos críticos y anticipe necesidades de recursos. En este artículo construiremos paso a paso una arquitectura de orquestación multi-agente usando Laravel como núcleo, aprovechando sus capacidades de colas, eventos y Redis para caché predictiva.

Fundamentos de la arquitectura multi-agente

Un sistema multi-agente efectivo requiere cuatro componentes fundamentales: definición clara de responsabilidades por agente, mecanismos de comunicación asíncrona, persistencia de estado con trazabilidad completa, y optimización de recursos mediante predicción de cargas. Laravel proporciona herramientas nativas para cada uno de estos pilares.

Nuestro escenario práctico será una plataforma de análisis de documentos legales donde tres agentes colaboran: un agente extractor identifica cláusulas relevantes, un agente clasificador determina riesgos, y un agente redactor genera resúmenes ejecutivos. La orquestación debe garantizar que el clasificador no ejecute hasta que el extractor complete su trabajo, mientras el redactor puede iniciar parcialmente con resultados intermedios.

Definiendo contratos de agente con tipado estricto

Comenzamos estableciendo interfaces que definan el contrato de cada agente. Esto permite intercambiar implementaciones y facilita el testing unitario.

<?php

namespace App\Contracts;

interface AgentInterface
{
    public function getName(): string;
    
    public function getCapabilities(): array;
    
    public function getPriority(): int;
    
    public function acceptsPayload(array $payload): bool;
    
    public function execute(array $payload, AgentContext $context): AgentResult;
}

class AgentContext
{
    public function __construct(
        public readonly string $orchestrationId,
        public readonly array $completedSteps,
        public readonly array $sharedMemory,
        public readonly ?string $correlationId = null,
    ) {}
}

class AgentResult
{
    public function __construct(
        public readonly bool $success,
        public readonly array $data,
        public readonly array $artifacts = [],
        public readonly ?string $nextRecommendedAgent = null,
        public readonly array $cacheWarmHints = [],
    ) {}
}

La propiedad cacheWarmHints es crucial para nuestro sistema predictivo: cada agente indica qué datos probablemente necesitarán los siguientes agentes, permitiendo precálculo asíncrono.

Implementación de agentes especializados

Veamos la implementación concreta del agente extractor, que utiliza la API de OpenAI con manejo de streaming para documentos grandes.

<?php

namespace App\Agents;

use App\Contracts\{AgentInterface, AgentContext, AgentResult};
use Illuminate\Support\Facades\{Http, Cache, Log};
use OpenAI\Laravel\Facades\OpenAI;

class ContractExtractorAgent implements AgentInterface
{
    public function getName(): string
    {
        return 'contract_extractor';
    }
    
    public function getCapabilities(): array
    {
        return ['clause_extraction', 'entity_recognition', 'obligation_mapping'];
    }
    
    public function getPriority(): int
    {
        return 10;
    }
    
    public function acceptsPayload(array $payload): bool
    {
        return isset($payload['document_type']) 
            && $payload['document_type'] === 'contract'
            && isset($payload['content']);
    }
    
    public function execute(array $payload, AgentContext $context): AgentResult
    {
        $cacheKey = "extraction:{$context->orchestrationId}";
        
        $extracted = Cache::remember(
            $cacheKey,
            now()->addHours(2),
            function () use ($payload, $context) {
                $response = OpenAI::chat()->create([
                    'model' => 'gpt-4',
                    'messages' => [
                        [
                            'role' => 'system',
                            'content' => $this->getExtractionPrompt()
                        ],
                        [
                            'role' => 'user', 
                            'content' => $this->truncateContent($payload['content'])
                        ]
                    ],
                    'response_format' => ['type' => 'json_object'],
                    'temperature' => 0.1,
                ]);
                
                return json_decode($response->choices[0]->message->content, true);
            }
        );
        
        return new AgentResult(
            success: true,
            data: [
                'clauses' => $extracted['clauses'] ?? [],
                'parties' => $extracted['parties'] ?? [],
                'obligations' => $extracted['obligations'] ?? [],
                'extracted_at' => now()->toIso8601String(),
            ],
            artifacts: [
                'raw_extraction' => $extracted,
                'token_usage' => $response->usage->totalTokens ?? null,
            ],
            nextRecommendedAgent: 'risk_classifier',
            cacheWarmHints: [
                'risk_classifier' => [
                    'clauses' => $extracted['clauses'] ?? [],
                    'obligations' => $extracted['obligations'] ?? [],
                ],
                'executive_summarizer' => [
                    'parties' => $extracted['parties'] ?? [],
                    'key_clauses_count' => count($extracted['clauses'] ?? []),
                ],
            ]
        );
    }
}

Orquestador con máquina de estados y Redis Streams

El orquestador central utiliza Redis Streams para persistencia de eventos, implementando un patrón de event sourcing ligero. Esto garantiza trazabilidad completa y permite reconstruir el estado de cualquier orquestación.

<?php

namespace App\Services;

use Illuminate\Support\Facades\{Redis, Bus, Log};
use App\Events\{AgentCompleted, OrchestrationFailed, CacheWarmingRequested};
use App\Jobs\{ExecuteAgentJob, WarmPredictiveCacheJob};

class AgentOrchestrator
{
    private const STREAM_KEY = 'orchestration:events';
    private const CONSUMER_GROUP = 'orchestrator-workers';
    
    public function __construct(
        private AgentRegistry $registry,
        private PredictiveCacheManager $cacheManager,
    ) {}
    
    public function initiate(array $workflow, array $initialPayload, string $correlationId): string
    {
        $orchestrationId = uniqid('orch_', true);
        
        $this->appendEvent($orchestrationId, 'orchestration.started', [
            'workflow' => $workflow,
            'correlation_id' => $correlationId,
            'started_at' => now()->toIso8601String(),
        ]);
        
        $firstAgent = $workflow['steps'][0]['agent'] ?? null;
        
        if (!$firstAgent) {
            throw new \InvalidArgumentException('Workflow sin pasos definidos');
        }
        
        $this->dispatchAgentJob(
            agentName: $firstAgent,
            payload: $initialPayload,
            orchestrationId: $orchestrationId,
            stepIndex: 0,
        );
        
        return $orchestrationId;
    }
    
    public function handleAgentCompletion(string $orchestrationId, AgentResult $result, int $completedStepIndex): void
    {
        $this->appendEvent($orchestrationId, 'agent.completed', [
            'step_index' => $completedStepIndex,
            'agent' => $result->data['_agent_name'] ?? 'unknown',
            'next_recommended' => $result->nextRecommendedAgent,
            'duration_ms' => $result->data['_duration_ms'] ?? null,
        ]);
        
        event(new AgentCompleted($orchestrationId, $result));
        
        if (!empty($result->cacheWarmHints)) {
            $this->triggerPredictiveWarming($orchestrationId, $result->cacheWarmHints);
        }
        
        $workflow = $this->reconstructWorkflowState($orchestrationId);
        $nextStep = $this->determineNextStep($workflow, $completedStepIndex, $result);
        
        if ($nextStep === null) {
            $this->finalizeOrchestration($orchestrationId, 'completed');
            return;
        }
        
        $mergedPayload = $this->mergeStepPayloads($orchestrationId, $nextStep['input_mapping'] ?? []);
        
        $this->dispatchAgentJob(
            agentName: $nextStep['agent'],
            payload: $mergedPayload,
            orchestrationId: $orchestrationId,
            stepIndex: $nextStep['index'],
            priority: $nextStep['priority'] ?? 'default',
        );
    }
    
    private function appendEvent(string $orchestrationId, string $type, array $data): void
    {
        Redis::xAdd(self::STREAM_KEY, '*', [
            'orch_id' => $orchestrationId,
            'type' => $type,
            'data' => json_encode($data),
            'timestamp' => now()->getTimestampMs(),
        ]);
    }
    
    private function dispatchAgentJob(
        string $agentName,
        array $payload,
        string $orchestrationId,
        int $stepIndex,
        string $priority = 'default',
    ): void {
        $job = new ExecuteAgentJob($agentName, $payload, $orchestrationId, $stepIndex);
        
        $queueMapping = [
            'critical' => 'agents-critical',
            'high' => 'agents-high',
            'default' => 'agents-default',
            'background' => 'agents-background',
        ];
        
        $queue = $queueMapping[$priority] ?? 'agents-default';
        
        Bus::dispatchToQueue($job, $queue);
    }
    
    private function triggerPredictiveWarming(string $orchestrationId, array $hints): void
    {
        foreach ($hints as $targetAgent => $predictedInput) {
            $cacheKey = $this->cacheManager->generateWarmKey($orchestrationId, $targetAgent);
            
            if (Redis::setnx($cacheKey . ':warming', now()->addMinutes(5)->getTimestamp())) {
                WarmPredictiveCacheJob::dispatch(
                    $orchestrationId,
                    $targetAgent,
                    $predictedInput
                )->onQueue('cache-warming');
            }
        }
    }
}

Jobs con manejo de prioridad y backoff exponencial

Los jobs de ejecución de agentes implementan patrones de resiliencia y métricas para optimización continua.

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\{Redis, Log};
use App\Services\{AgentOrchestrator, AgentRegistry};
use App\Contracts\AgentContext;

class ExecuteAgentJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    
    public $tries = 3;
    public $backoff = [10, 30, 120];
    public $timeout = 300;
    public $failOnTimeout = true;
    
    public function __construct(
        public readonly string $agentName,
        public readonly array $payload,
        public readonly string $orchestrationId,
        public readonly int $stepIndex,
    ) {}
    
    public function handle(AgentOrchestrator $orchestrator, AgentRegistry $registry): void
    {
        $startTime = hrtime(true);
        
        Redis::funnel("orch:{$this->orchestrationId}")
            ->limit(1)
            ->then(function () use ($orchestrator, $registry, $startTime) {
                $agent = $registry->resolve($this->agentName);
                
                $context = $this->buildContext($this->orchestrationId);
                
                $result = $agent->execute($this->payload, $context);
                
                $durationMs = (hrtime(true) - $startTime) / 1e6;
                $result->data['_duration_ms'] = $durationMs;
                $result->data['_agent_name'] = $this->agentName;
                
                $this->recordExecutionMetrics($this->agentName, $durationMs, $result->success);
                
                if (!$result->success) {
                    throw new \RuntimeException("Agente {$this->agentName} falló: " . json_encode($result->data));
                }
                
                $orchestrator->handleAgentCompletion(
                    $this->orchestrationId,
                    $result,
                    $this->stepIndex
                );
            }, function () {
                return $this->release(5);
            });
    }
    
    private function buildContext(string $orchestrationId): AgentContext
    {
        $completedSteps = Redis::hGetAll("orch:{$orchestrationId}:steps");
        $sharedMemory = Redis::hGetAll("orch:{$orchestrationId}:memory");
        
        return new AgentContext(
            orchestrationId: $orchestrationId,
            completedSteps: array_map('json_decode', $completedSteps),
            sharedMemory: array_map('json_decode', $sharedMemory),
            correlationId: Redis::hGet("orch:{$orchestrationId}:meta", 'correlation_id'),
        );
    }
    
    private function recordExecutionMetrics(string $agent, float $durationMs, bool $success): void
    {
        $key = "metrics:agent:{$agent}:" . now()->format('YmdH');
        
        Redis::pipeline(function ($pipe) use ($key, $durationMs, $success) {
            $pipe->hIncrBy($key, 'executions', 1);
            $pipe->hIncrBy($key, $success ? 'successes' : 'failures', 1);
            $pipe->zAdd("{$key}:durations", $durationMs, microtime(true));
            $pipe->expire($key, 86400 * 7);
        });
    }
}

Caché predictiva con invalidación inteligente

El componente de caché predictiva analiza patrones de acceso históricos para precalcular resultados probables antes de que sean solicitados explícitamente.

<?php

namespace App\Services;

use Illuminate\Support\Facades\{Redis, Cache, Log};
use App\Jobs\WarmPredictiveCacheJob;

class PredictiveCacheManager
{
    private const PREDICTION_WINDOW_SECONDS = 300;
    
    public function generateWarmKey(string $orchestrationId, string $agentName): string
    {
        return "predict:{$orchestrationId}:{$agentName}";
    }
    
    public function predictAndWarm(string $agentName, array $currentContext): void
    {
        $pattern = $this->findSimilarPattern($agentName, $currentContext);
        
        if (!$pattern) {
            return;
        }
        
        $predictedNextAgents = $this->getFrequentTransitions($agentName, $pattern);
        
        foreach ($predictedNextAgents as $prediction) {
            $confidence = $prediction['confidence'];
            
            if ($confidence < 0.6) {
                continue;
            }
            
            $predictedInput = $this->projectInput($currentContext, $prediction['target_agent']);
            
            $potentialKey = $this->generateWarmKey(
                $currentContext['orchestration_id'],
                $prediction['target_agent']
            );
            
            if (Redis::exists($potentialKey)) {
                continue;
            }
            
            WarmPredictiveCacheJob::dispatch(
                $currentContext['orchestration_id'],
                $prediction['target_agent'],
                $predictedInput
            )->delay(now()->addSeconds($prediction['typical_delay_ms'] / 1000));
        }
    }
    
    private function findSimilarPattern(string $agentName, array $context): ?array
    {
        $patternKey = "patterns:{$agentName}:" . $this->contextSignature($context);
        
        return Redis::get($patternKey) ? json_decode(Redis::get($patternKey), true) : null;
    }
    
    private function getFrequentTransitions(string $fromAgent, array $pattern): array
    {
        $transitionsKey = "transitions:{$fromAgent}";
        
        $raw = Redis::zRevRangeByScore(
            $transitionsKey,
            '+inf',
            0,
            ['withscores' => true, 'limit' => [0, 5]]
        );
        
        $total = array_sum($raw) ?: 1;
        $result = [];
        
        foreach ($raw as $targetAgent => $count) {
            $result[] = [
                'target_agent' => $targetAgent,
                'confidence' => $count / $total,
                'typical_delay_ms' => $this->getTypicalDelay($fromAgent, $targetAgent),
            ];
        }
        
        return $result;
    }
    
    public function storeIfPredicted(string $orchestrationId, string $agentName, mixed $result): bool
    {
        $warmKey = $this->generateWarmKey($orchestrationId, $agentName);
        
        if (!Redis::exists("{$warmKey}:warming")) {
            return false;
        }
        
        Redis::setex(
            $warmKey,
            self::PREDICTION_WINDOW_SECONDS,
            serialize($result)
        );
        
        Redis::del("{$warmKey}:warming");
        
        return true;
    }
    
    public function retrievePredicted(string $orchestrationId, string $agentName): ?AgentResult
    {
        $warmKey = $this->generateWarmKey($orchestrationId, $agentName);
        $cached = Redis::get($warmKey);
        
        if (!$cached) {
            return null;
        }
        
        Redis::hIncrBy('metrics:predictive_cache', 'hits', 1);
        
        return unserialize($cached);
    }
    
    private function contextSignature(array $context): string
    {
        $relevant = array_intersect_key($context, array_flip(['document_type', 'complexity_score', 'industry']));
        return md5(json_encode($relevant));
    }
}

Workers especializados y monitoreo

La ejecución productiva requiere workers dedicados por prioridad, con monitoreo de latencia y throughput. Configuramos supervisord con múltiples grupos de procesos.

[program:laravel-agents-critical]
command=php /var/www/artisan queue:work redis --queue=agents-critical --sleep=0 --timeout=300 --tries=3 --max-jobs=1000
numprocs=4
autostart=true
autorestart=true
user=www-data
priority=10

[program:laravel-agents-high]
command=php /var/www/artisan queue:work redis --queue=agents-high --sleep=1 --timeout=300 --tries=3
numprocs=6
autostart=true
autorestart=true
user=www-data
priority=20

[program:laravel-agents-default]
command=php /var/www/artisan queue:work redis --queue=agents-default --sleep=3 --timeout=300 --tries=3
numprocs=8
autostart=true
autorestart=true
user=www-data
priority=30

[program:laravel-cache-warming]
command=php /var/www/artisan queue:work redis --queue=cache-warming --sleep=5 --timeout=60 --tries=1
numprocs=4
autostart=true
autorestart=true
user=www-data
priority=40

Eventos para desacoplamiento y observabilidad

Los eventos de Laravel conectan el orquestador con sistemas externos de monitoreo y notificación.

<?php

namespace App\Listeners;

use App\Events\{AgentCompleted, OrchestrationFailed, CacheWarmingRequested};
use Illuminate\Support\Facades\{Http, Log, Redis};
use App\Services\PredictiveCacheManager;

class OrchestrationMetricsCollector
{
    public function handleAgentCompleted(AgentCompleted $event): void
    {
        $latency = $event->result->data['_duration_ms'] ?? 0;
        
        Redis::tsAdd('ts:agent:latency', time(), $latency);
        
        if ($latency > 10000) {
            Http::post(config('services.pagerduty.webhook'), [
                'routing_key' => config('services.pagerduty.key'),
                'event_action' => 'trigger',
                'payload' => [
                    'summary' => "Latencia de agente elevada: {$event->result->data['_agent_name']}",
                    'severity' => $latency > 30000 ? 'critical' : 'warning',
                    'custom_details' => [
                        'orchestration_id' => $event->orchestrationId,
                        'latency_ms' => $latency,
                    ],
                ],
            ]);
        }
    }
    
    public function handleCacheWarmingRequested(CacheWarmingRequested $event): void
    {
        $cacheManager = app(PredictiveCacheManager::class);
        $cacheManager->predictAndWarm($event->currentAgent, $event->contextSnapshot);
    }
}

Patrones avanzados: circuit breaker y degradación graceful

Para operación en producción, implementamos circuit breaker por proveedor de IA, permitiendo failover entre múltiples servicios.

<?php

namespace App\Services;

use Illuminate\Support\Facades\{Redis, Http};
use App\Exceptions\CircuitOpenException;

class ResilientAIProvider
{
    private const FAILURE_THRESHOLD = 5;
    private const RECOVERY_TIMEOUT = 60;
    
    public function __construct(
        private string $provider,
        private array $fallbackProviders,
    ) {}
    
    public function executeWithResilience(callable $operation)
    {
        $breakerKey = "circuit:{$this->provider}";
        $state = Redis::get($breakerKey);
        
        if ($state === 'open') {
            if ($this->shouldAttemptReset($breakerKey)) {
                Redis::setex($breakerKey, self::RECOVERY_TIMEOUT, 'half-open');
            } else {
                return $this->tryFallback($operation);
            }
        }
        
        try {
            $result = $operation();
            
            if ($state === 'half-open') {
                Redis::del("{$breakerKey}:failures");
                Redis::del($breakerKey);
            }
            
            return $result;
            
        } catch (\Exception $e) {
            $this->recordFailure($breakerKey);
            throw $e;
        }
    }
    
    private function recordFailure(string $breakerKey): void
    {
        $failures = Redis::incr("{$breakerKey}:failures");
        
        if ($failures >= self::FAILURE_THRESHOLD) {
            Redis::setex($breakerKey, self::RECOVERY_TIMEOUT, 'open');
        }
    }
}

Conclusiones y recomendaciones

La orquestación de agentes de IA en Laravel demanda considerar la arquitectura como un sistema distribuido desde el diseño inicial. Los puntos críticos para producción incluyen: monitoreo exhaustivo de latencia por paso de workflow, límites estrictos de tiempo de ejecución con rollback definido, aislamiento de fallos entre agentes mediante colas separadas, y aprendizaje continuo de patrones de ejecución para optimizar la caché predictiva.

La combinación de Redis Streams para event sourcing, colas con prioridad para scheduling, y caché predictiva para reducción de latencia proporciona una base sólida que escala horizontalmente. La clave está en comenzar con telemetría completa: sin medición precisa de tiempos por agente y transiciones, cualquier optimización será especulativa.