CommunityProgramación y desarrollogithub.com

SKY-lv/skylv-multi-agent-orchestrator

Diseña y gestiona sistemas multi-agente con soporte para descomposición de tareas, ejecución en paralelo y comunicación entre agentes.

¿Qué es skylv-multi-agent-orchestrator?

Esta habilidad proporciona un orquestador completo para gestionar sistemas de múltiples agentes inteligentes. Permite diseñar y ejecutar flujos de trabajo colaborativos donde varios agentes especializados trabajan juntos para resolver tareas complejas. Incluye un planificador de tareas que descompone objetivos grandes en subtareas manejables, un gestor de ejecución que maneja dependencias y paralelismo, un bus de mensajes para la comunicación entre agentes, y un gestor de estados que controla las transiciones entre estados como 'idle', 'thinking' o 'error'. Soporta patrones comunes como role-play (asignación de roles como planificador, ejecutor y crítico) y debate (argumentación estructurada entre agentes a favor y en contra). También incluye un sistema de memoria semántica para mantener contexto entre interacciones. Está diseñado para ser utilizado con OpenClaw y es ideal para aplicaciones que requieren coordinación entre múltiples agentes de IA, como sistemas de razonamiento complejo, generación de contenido o simulación de equipos de trabajo.

Compatible con~Claude Code✓Codex CLI~Cursor
npx skills add SKY-lv/skylv-multi-agent-orchestrator

Installed? Explore more Programación y desarrollo skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

Multi-Agent Orchestrator

Descripción

Diseñar y gestionar sistemas de colaboración multi-agente.

Arquitectura

┌─────────────┐
│ Orchestrator │ ← Descomposición de tareas, coordinación
└──────┬──────┘
       │
   ┌───┼───┐
   ▼   ▼   ▼
 ┌───┐┌───┐┌───┐
 │ A ││ B ││ C │ ← Agentes especializados
 └───┘└───┘└───┘

Implementación principal

1. Clase base de Agente

interface AgentConfig {
  name: string;
  role: string;
  capabilities: string[];
  llm: LLMConfig;
  tools: Tool[];
  instructions: string;
}

class BaseAgent {
  protected config: AgentConfig;
  protected memory: AgentMemory;
  
  constructor(config: AgentConfig) {
    this.config = config;
    this.memory = new AgentMemory(config.name);
  }
  
  async think(task: Task): Promise<Response> {
    const context = await this.memory.buildContext(task.description);
    const prompt = this.buildPrompt(task, context);
    const response = await this.callLLM(prompt);
    await this.memory.add({ type: 'semantic', content: task.description + ' -> ' + response.content, importance: 8 });
    return response;
  }
  
  protected buildPrompt(task: Task, context: string): Message[] {
    return [
      { role: 'system', content: this.config.instructions },
      { role: 'system', content: context },
      { role: 'user', content: task.description }
    ];
  }
  
  protected async callLLM(messages: Message[]): Promise<Response> {
    const res = await fetch('https://api.openai.com/v1/chat/completions', {
      method: 'POST',
      headers: { 'Authorization': `Bearer ${process.env.OPENAI_API_KEY}` },
      body: JSON.stringify({ model: this.config.llm.model, messages, tools: this.config.tools.map(t => t.definition) })
    });
    return res.json();
  }
}

2. Orquestador

interface TaskResult {
  agentId: string;
  status: 'pending' | 'running' | 'done' | 'failed';
  output?: string;
  dependencies: string[];
  startTime?: number;
  endTime?: number;
}

class Orchestrator {
  private agents: Map<string, BaseAgent> = new Map();
  private taskGraph: DAG<Task>;
  
  constructor(private llmRouter: LLMRouter) {}
  
  registerAgent(agent: BaseAgent) {
    this.agents.set(agent.config.name, agent);
  }
  
  async execute(goal: string): Promise<string> {
    // 1. Descomposición de tareas
    const plan = await this.decompose(goal);
    
    // 2. Construcción del DAG
    this.taskGraph = this.buildDAG(plan);
    
    // 3. Ejecución y planificación
    const results = await this.schedule();
    
    // 4. Resumen de resultados
    return this.summarize(goal, results);
  }
  
  private async decompose(goal: string): Promise<Task[]> {
    const response = await this.llmRouter.route({
      prompt: `Descompón la siguiente tarea en subtareas ejecutables, devuelve un array JSON:
      
Objetivo: ${goal}

Requisitos:
- Cada subtarea debe ser responsabilidad de un solo agente
- Define las dependencias entre tareas de forma explícita
- Formato de retorno: [{"id":"t1","description":"...","agent":"investigador","depends":[]},...]`,
      system: 'Eres un experto en descomposición de tareas.'
    });
    
    return JSON.parse(response.content);
  }
  
  private async schedule(): Promise<Map<string, TaskResult>> {
    const results = new Map<string, TaskResult>();
    const pending = new Set(this.taskGraph.nodes);
    const running: Promise<void>[] = [];
    const maxConcurrent = 3;
    
    while (pending.size > 0 || running.length > 0) {
      // Inicar tareas paralelizables
      while (running.length < maxConcurrent) {
        const next = this.findNextRunnable(pending, results);
        if (!next) break;
        
        pending.delete(next.id);
        const p = this.runTask(next, results).catch(console.error);
        running.push(p);
      }
      
      // Esperar a que una termine
      await Promise.race(running);
      running.splice(running.findIndex(p => false), 1);
    }
    
    return results;
  }
  
  private async runTask(task: Task, results: Map<string, TaskResult>) {
    results.set(task.id, { agentId: task.agent, status: 'running', dependencies: task.depends || [], startTime: Date.now() });
    
    try {
      // Esperar a que las dependencias terminen
      for (const depId of task.depends || []) {
        const dep = results.get(depId);
        if (dep?.status !== 'done') {
          await this.waitFor(depId, results);
        }
      }
      
      const agent = this.agents.get(task.agent);
      const context = this.buildContext(task, results);
      const response = await agent.think({ id: task.id, description: task.description, context });
      
      results.set(task.id, { ...results.get(task.id)!, status: 'done', output: response.content, endTime: Date.now() });
    } catch (error) {
      results.set(task.id, { ...results.get(task.id)!, status: 'failed', output: String(error), endTime: Date.now() });
    }
  }
  
  private buildContext(task: Task, results: Map<string, TaskResult>): string {
    return (task.depends || []).map(depId => {
      const dep = results.get(depId);
      return dep?.output || '';
    }).join('\n\n');
  }
}

3. Bus de mensajes

class MessageBus {
  private subscriptions = new Map<string, Subscriber[]>();
  
  publish(channel: string, message: Message) {
    const subs = this.subscriptions.get(channel) || [];
    for (const sub of subs) {
      sub.handler(message);
    }
  }
  
  subscribe(channel: string, handler: (msg: Message) => void): () => void {
    if (!this.subscriptions.has(channel)) {
      this.subscriptions.set(channel, []);
    }
    const sub = { id: crypto.randomUUID(), handler };
    this.subscriptions.get(channel)!.push(sub);
    return () => this.unsubscribe(channel, sub.id);
  }
  
  unsubscribe(channel: string, subId: string) {
    const subs = this.subscriptions.get(channel) || [];
    const idx = subs.findIndex(s => s.id === subId);
    if (idx >= 0) subs.splice(idx, 1);
  }
}

// Tipos de mensaje
interface Message {
  id: string;
  type: 'request' | 'response' | 'broadcast' | 'event';
  from: string;
  to?: string;
  content: any;
  timestamp: number;
}

4. Máquina de estados

type AgentState = 'idle' | 'thinking' | 'waiting' | 'acting' | 'error';

interface AgentSession {
  id: string;
  agentId: string;
  state: AgentState;
  currentTask?: string;
  history: Turn[];
  sharedContext: Record<string, any>;
}

class StateManager {
  private sessions = new Map<string, AgentSession>();
  
  transition(sessionId: string, newState: AgentState) {
    const session = this.sessions.get(sessionId);
    if (!session) return;
    
    const oldState = session.state;
    session.state = newState;
    
    // Hook de transición de estado
    this.onTransition(sessionId, oldState, newState);
  }
  
  // Reglas de transición de estado
  private canTransition(from: AgentState, to: AgentState): boolean {
    const rules: Record<AgentState, AgentState[]> = {
      idle: ['thinking'],
      thinking: ['waiting', 'acting', 'error', 'idle'],
      waiting: ['thinking', 'error', 'idle'],
      acting: ['thinking', 'error', 'idle'],
      error: ['idle', 'thinking']
    };
    return rules[from]?.includes(to) || false;
  }
}

Patrones de comunicación

PatrónDescripciónCasos de uso
BroadcastTodos los agentes recibenNotificaciones globales
Punto a puntoAgente específico recibeAsignación de tareas
Publicar/SuscribirDistribución por temaOrientado a eventos
PizarraEspacio de conocimiento compartidoRazonamiento colaborativo

Patrones comunes

Juego de roles (Role Play)

class RolePlayOrchestrator extends Orchestrator {
  async execute(goal: string) {
    // Asignar roles
    const planner = this.getAgent('planner');
    const executor = this.getAgent('executor');
    const critic = this.getAgent('critic');
    
    const plan = await planner.think({ description: goal });
    const result = await executor.think({ description: plan.output, context: '' });
    const review = await critic.think({ description: result.output, context: '' });
    
    return review.output;
  }
}

Debate

async debate(topic: string, rounds = 3) {
  const pro = this.getAgent('pro');
  const con = this.getAgent('con');
  const judge = this.getAgent('judge');
  
  let context = '';
  for (let i = 0; i < rounds; i++) {
    const proArg = await pro.think({ description: `Argumento a favor (ronda ${i+1}): ${topic}`, context });
    context += `\nA favor: ${proArg.output}`;
    
    const conArg = await con.think({ description: `Argumento en contra (ronda ${i+1}): ${topic}`, context });
    context += `\nEn contra: ${conArg.output}`;
  }
  
  return judge.think({ description: `Fallar: ${topic}`, context });
}

Buenas prácticas

  1. Responsabilidad única: Cada agente debe tener un dominio de especialización claro
  2. Acoplamiento débil: Comunicación a través del bus de mensajes, evitando dependencias directas
  3. Control de tiempo de espera: Evitar que un agente se quede bloqueado
  4. Mecanismo de cortocircuito: Degradación automática tras demasiados fallos
  5. Observabilidad: Registro completo y trazabilidad

Uso

  1. Instalar la habilidad
  2. Configurar según sea necesario
  3. Ejecutar con OpenClaw

Skills relacionados