Sistemas Multi-Agente

Construya aplicaciones sofisticadas componiendo agentes especializados en equipos.

Visión General de la Jerarquía de Agentes

Rendering architecture…

Lo que Construirá

En esta guía, creará un Sistema de Atención al Cliente donde un coordinator enruta las consultas a specialists:

                        ┌─────────────────────┐
       User Query       │                     │
      ────────────────▶ │    COORDINATOR      │
                        │  "Route to expert"  │
                        └──────────┬──────────┘
                                   │
                   ┌───────────────┴───────────────┐
                   │                               │
                   ▼                               ▼
        ┌──────────────────┐            ┌──────────────────┐
        │  BILLING AGENT   │            │  SUPPORT AGENT   │
        │                  │            │                  │
        │  💰 Payments     │            │  🔧 Tech Issues  │
        │  📄 Invoices     │            │  🐛 Bug Reports  │
        │  💳 Subscriptions│            │  ❓ How-To       │
        └──────────────────┘            └──────────────────┘

Conceptos Clave:

  • Coordinator - Recibe todas las solicitudes, decide quién las maneja
  • Specialists - Agentes enfocados que sobresalen en dominios específicos
  • Transfer - Traspaso sin interrupciones del coordinator al specialist

Inicio Rápido

1. Cree Su Proyecto

cargo new multi_agent_demo
cd multi_agent_demo

Agregue dependencias a Cargo.toml:

[dependencies]
adk-rust = "2.0.0"
tokio = { version = "1", features = ["full"] }
dotenvy = "0.15"

Cree .env con su clave API:

echo 'GOOGLE_API_KEY=your-api-key' > .env

2. Ejemplo de Atención al Cliente

Aquí tiene un ejemplo completo y funcional:

use adk_rust::prelude::*;
use adk_rust::Launcher;
use std::sync::Arc;

#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    dotenvy::dotenv().ok();
    let api_key = std::env::var("GOOGLE_API_KEY")?;
    let model = Arc::new(GeminiModel::new(&api_key, "gemini-2.5-flash")?);

    // Specialist: Billing Agent
    let billing_agent = LlmAgentBuilder::new("billing_agent")
        .description("Handles billing questions: payments, invoices, subscriptions, refunds")
        .instruction("You are a billing specialist. Help customers with:\n\
                     - Invoice questions and payment history\n\
                     - Subscription plans and upgrades\n\
                     - Refund requests\n\
                     - Payment method updates\n\
                     Be professional and provide clear information about billing matters.")
        .model(model.clone())
        .build()?;

    // Specialist: Technical Support Agent
    let support_agent = LlmAgentBuilder::new("support_agent")
        .description("Handles technical support: bugs, errors, troubleshooting, how-to questions")
        .instruction("You are a technical support specialist. Help customers with:\n\
                     - Troubleshooting errors and bugs\n\
                     - How-to questions about using the product\n\
                     - Configuration and setup issues\n\
                     - Performance problems\n\
                     Be patient and provide step-by-step guidance.")
        .model(model.clone())
        .build()?;

    // Coordinator: Routes to appropriate specialist
    let coordinator = LlmAgentBuilder::new("coordinator")
        .description("Main customer service coordinator")
        .instruction("You are a customer service coordinator. Analyze each customer request:\n\n\
                     - For BILLING questions (payments, invoices, subscriptions, refunds):\n\
                       Transfer to billing_agent\n\n\
                     - For TECHNICAL questions (errors, bugs, how-to, troubleshooting):\n\
                       Transfer to support_agent\n\n\
                     - For GENERAL greetings or unclear requests:\n\
                       Respond yourself and ask clarifying questions\n\n\
                     When transferring, briefly acknowledge the customer and explain the handoff.")
        .model(model.clone())
        .sub_agent(Arc::new(billing_agent))
        .sub_agent(Arc::new(support_agent))
        .build()?;

    println!("🏢 Customer Service Center");
    println!("   Coordinator → Billing Agent | Support Agent");
    println!();

    Launcher::new(Arc::new(coordinator)).run().await?;
    Ok(())
}

Interacción de Ejemplo:

You: I have a question about my last invoice

[Agent: coordinator]
Assistant: I'll connect you with our billing specialist to help with your invoice question.

[Agent: billing_agent]
Assistant: Hello! I can help you with your invoice. What specific question do you have about your last invoice?

You: Why was I charged twice?

[Agent: billing_agent]
Assistant: I understand your concern about the duplicate charge. Let me help you investigate this...

Cómo Funciona la Transferencia Multi-Agente

El Panorama General

Cuando añades sub-agentes a un agente padre, el LLM obtiene la capacidad de delegar tareas:

                    ┌─────────────────────┐
    User Message    │                     │
   ─────────────────▶    COORDINATOR      │
                    │                     │
                    └──────────┬──────────┘
                               │
           "This is a billing question..."
                               │
              ┌────────────────┴────────────────┐
              │                                 │
              ▼                                 ▼
   ┌──────────────────┐              ┌──────────────────┐
   │  billing_agent   │              │  support_agent   │
   │  💰 Payments     │              │  🔧 Tech Issues  │
   │  📄 Invoices     │              │  🐛 Bug Reports  │
   └──────────────────┘              └──────────────────┘

Flujo de Transferencia Paso a Paso

Esto es exactamente lo que sucede cuando un usuario hace una pregunta de facturación:

┌──────────────────────────────────────────────────────────────────────┐
│ STEP 1: User sends message                                           │
├──────────────────────────────────────────────────────────────────────┤
│                                                                      │
│   User: "Why was I charged twice on my invoice?"                     │
│                                                                      │
│                              ↓                                       │
│                                                                      │
│   ┌──────────────────────────────────────┐                          │
│   │         COORDINATOR AGENT            │                          │
│   │  Receives message first              │                          │
│   └──────────────────────────────────────┘                          │
│                                                                      │
└──────────────────────────────────────────────────────────────────────┘
                              ↓
┌──────────────────────────────────────────────────────────────────────┐
│ STEP 2: LLM analyzes and decides to transfer                         │
├──────────────────────────────────────────────────────────────────────┤
│                                                                      │
│   🧠 LLM thinks: "This is about an invoice charge..."                │
│                  "Invoice = billing topic..."                        │
│                  "I should transfer to billing_agent"                │
│                                                                      │
│   📞 LLM calls: transfer_to_agent(agent_name="billing_agent")        │
│                                                                      │
└──────────────────────────────────────────────────────────────────────┘
                              ↓
┌──────────────────────────────────────────────────────────────────────┐
│ STEP 3: Runner detects transfer and invokes target                   │
├──────────────────────────────────────────────────────────────────────┤
│                                                                      │
│   ┌─────────┐     transfer event      ┌─────────────────┐           │
│   │ Runner  │ ─────────────────────▶  │  billing_agent  │           │
│   └─────────┘   (same user message)   └─────────────────┘           │
│                                                                      │
│   • Runner finds "billing_agent" in agent tree                       │
│   • Creates new context with SAME user message                       │
│   • Invokes billing_agent immediately                                │
│                                                                      │
└──────────────────────────────────────────────────────────────────────┘
                              ↓
┌──────────────────────────────────────────────────────────────────────┐
│ STEP 4: Target agent responds                                        │
├──────────────────────────────────────────────────────────────────────┤
│                                                                      │
│   ┌─────────────────────────────────────────┐                       │
│   │           billing_agent responds        │                       │
│   │                                         │                       │
│   │  "I can help with your duplicate        │                       │
│   │   charge. Let me investigate..."        │                       │
│   └─────────────────────────────────────────┘                       │
│                                                                      │
│   ✅ User sees seamless response - no interruption!                  │
│                                                                      │
└──────────────────────────────────────────────────────────────────────┘

¿Qué lo Hace Funcionar?

ComponenteRol
.sub_agent()Registra especialistas bajo el padre
transfer_to_agent toolAuto-inyectado cuando existen sub-agentes
Descripciones de AgentAyuda LLM a decidir qué agent maneja qué
RunnerDetecta eventos de transferencia e invoca al agente objetivo
Sesión compartidaEstado e historial preservados entre transferencias

Antes vs Después de Añadir Sub-Agentes

Sin sub-agentes - Un agente lo hace todo:

User ──▶ coordinator ──▶ Response (handles billing AND support)

Con sub-agentes - Los especialistas manejan su dominio:

User ──▶ coordinator ──▶ billing_agent ──▶ Response (billing expert)
                    ──▶ support_agent ──▶ Response (tech expert)

Sistemas Multi-Agente Jerárquicos

Para escenarios complejos, puedes crear jerarquías multinivel. Cada agente puede tener sus propios sub-agentes, formando un árbol:

Visual: Equipo de Contenido de 3 Niveles

                    ┌─────────────────────┐
                    │  PROJECT MANAGER    │  ← Level 1: Top-level coordinator
                    │  "Manage projects"  │
                    └──────────┬──────────┘
                               │
                               ▼
                    ┌─────────────────────┐
                    │  CONTENT CREATOR    │  ← Level 2: Mid-level coordinator  
                    │  "Coordinate R&W"   │
                    └──────────┬──────────┘
                               │
              ┌────────────────┴────────────────┐
              │                                 │
              ▼                                 ▼
   ┌──────────────────┐              ┌──────────────────┐
   │   RESEARCHER     │              │     WRITER       │  ← Level 3: Specialists
   │                  │              │                  │
   │  📚 Gather facts │              │  ✍️ Write content │
   │  🔍 Analyze data │              │  📝 Polish text  │
   │  📊 Find sources │              │  🎨 Style & tone │
   └──────────────────┘              └──────────────────┘

Cómo Fluyen las Solicitudes

User: "Create a blog post about electric vehicles"
                        │
                        ▼
┌─────────────────────────────────────────────────────────────┐
│  PROJECT MANAGER: "This is a content task"                  │
│  → transfers to content_creator                             │
└─────────────────────────────────────────────────────────────┘
                        │
                        ▼
┌─────────────────────────────────────────────────────────────┐
│  CONTENT CREATOR: "Need research first, then writing"       │
│  → transfers to researcher                                  │
└─────────────────────────────────────────────────────────────┘
                        │
                        ▼
┌─────────────────────────────────────────────────────────────┐
│  RESEARCHER: "Here's what I found about EVs..."             │
│  → provides research summary                                │
└─────────────────────────────────────────────────────────────┘

Código de Ejemplo Completo

use adk_rust::prelude::*;
use adk_rust::Launcher;
use std::sync::Arc;

#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    dotenvy::dotenv().ok();
    let api_key = std::env::var("GOOGLE_API_KEY")?;
    let model = Arc::new(GeminiModel::new(&api_key, "gemini-2.5-flash")?);

    // Level 3: Leaf specialists
    let researcher = LlmAgentBuilder::new("researcher")
        .description("Researches topics and gathers comprehensive information")
        .instruction("You are a research specialist. When asked to research a topic:\n\
                     - Gather key facts and data\n\
                     - Identify main themes and subtopics\n\
                     - Note important sources or references\n\
                     Provide thorough, well-organized research summaries.")
        .model(model.clone())
        .build()?;

    let writer = LlmAgentBuilder::new("writer")
        .description("Writes polished content based on research")
        .instruction("You are a content writer. When asked to write:\n\
                     - Create engaging, clear content\n\
                     - Use appropriate tone for the audience\n\
                     - Structure content logically\n\
                     - Polish for grammar and style\n\
                     Produce professional, publication-ready content.")
        .model(model.clone())
        .build()?;

    // Level 2: Content coordinator
    let content_creator = LlmAgentBuilder::new("content_creator")
        .description("Coordinates content creation by delegating research and writing")
        .instruction("You are a content creation lead. For content requests:\n\n\
                     - If RESEARCH is needed: Transfer to researcher\n\
                     - If WRITING is needed: Transfer to writer\n\
                     - For PLANNING or overview: Handle yourself\n\n\
                     Coordinate between research and writing phases.")
        .model(model.clone())
        .sub_agent(Arc::new(researcher))
        .sub_agent(Arc::new(writer))
        .build()?;

    // Level 1: Top-level manager
    let project_manager = LlmAgentBuilder::new("project_manager")
        .description("Manages projects and coordinates with content team")
        .instruction("You are a project manager. For incoming requests:\n\n\
                     - For CONTENT creation tasks: Transfer to content_creator\n\
                     - For PROJECT STATUS or general questions: Handle yourself\n\n\
                     Keep track of overall project goals and deadlines.")
        .model(model.clone())
        .sub_agent(Arc::new(content_creator))
        .build()?;

    println!("📊 Hierarchical Multi-Agent System");
    println!();
    println!("   project_manager");
    println!("       └── content_creator");
    println!("               ├── researcher");
    println!("               └── writer");
    println!();

    Launcher::new(Arc::new(project_manager)).run().await?;
    Ok(())
}

Jerarquía de Agentes:

project_manager
└── content_creator
    ├── researcher
    └── writer

Ejemplos de prompts:

  • "Crear una publicación de blog sobre IA en la atención médica" → Gerente de Proyecto → Creador de Contenido → Escritor
  • "Investigar vehículos eléctricos" → Gerente de Proyecto → Creador de Contenido → Investigador

Configuración de Sub-Agentes

Añade sub-agentes a cualquier LlmAgent usando el método constructor sub_agent():

let parent = LlmAgentBuilder::new("parent")
    .description("Coordinates specialized tasks")
    .instruction("Route requests to appropriate specialists.")
    .model(model.clone())
    .sub_agent(Arc::new(specialist_a))
    .sub_agent(Arc::new(specialist_b))
    .build()?;

Puntos Clave:

  • Cada Agent puede tener múltiples sub-agents
  • Los sub-agents pueden tener sus propios sub-agents (jerarquías multinivel)
  • Los nombres de los Agent deben ser únicos dentro de la jerarquía
  • Las descripciones ayudan al LLM a decidir a qué Agent transferir

Cómo Escribir Instrucciones de Transferencia Efectivas

Para transferencias de Agent exitosas, proporcione instrucciones y descripciones claras:

Instrucciones del Agent Padre

let coordinator = LlmAgentBuilder::new("coordinator")
    .description("Main customer service coordinator")
    .instruction("You are a customer service coordinator. Analyze each request:\n\n\
                 - For BILLING questions (payments, invoices, subscriptions):\n\
                   Transfer to billing_agent\n\n\
                 - For TECHNICAL questions (errors, bugs, troubleshooting):\n\
                   Transfer to support_agent\n\n\
                 - For GENERAL greetings or unclear requests:\n\
                   Respond yourself and ask clarifying questions")
    .model(model.clone())
    .sub_agent(Arc::new(billing_agent))
    .sub_agent(Arc::new(support_agent))
    .build()?;

Descripciones de Sub-Agent

let billing_agent = LlmAgentBuilder::new("billing_agent")
    .description("Handles billing questions: payments, invoices, subscriptions, refunds")
    .instruction("You are a billing specialist. Help with payment and subscription issues.")
    .model(model.clone())
    .build()?;

let support_agent = LlmAgentBuilder::new("support_agent")
    .description("Handles technical support: bugs, errors, troubleshooting, how-to questions")
    .instruction("You are a technical support specialist. Provide step-by-step guidance.")
    .model(model.clone())
    .build()?;

Mejores Prácticas:

  • Utilice nombres de Agent descriptivos que indiquen claramente su propósito
  • Escriba descripciones detalladas: el LLM las utiliza para decidir las transferencias
  • Incluya palabras clave específicas en las descripciones que coincidan con las solicitudes probables del usuario
  • Proporcione reglas de delegación claras en las instrucciones del Agent padre
  • Utilice terminología consistente en todas las descripciones de los Agent

Probando su Sistema Multi-Agent

Ejecutando Ejemplos

cargo run --manifest-path examples/tier_examples/enterprise/Cargo.toml --bin 14-enterprise-multi-agent

Ejemplos de Prompts de Prueba

Servicio al Cliente:

  • "Tengo una pregunta sobre mi última factura" → Debería dirigirse a billing_agent
  • "La aplicación sigue fallando" → Debería dirigirse a support_agent
  • "¿Cómo actualizo mi plan?" → Debería dirigirse a billing_agent
  • "Hola, necesito ayuda" → Debería quedarse con coordinator para aclaración

Jerárquico:

  • "Crear una entrada de blog sobre IA en la atención médica" → PM → Content Creator → Writer
  • "Investigar la historia de los vehículos eléctricos" → PM → Content Creator → Researcher
  • "¿Cuál es el estado de nuestros proyectos actuales?" → Debería quedarse con project_manager

Depuración de Problemas de Transferencia

Si las transferencias no funcionan como se esperaba:

  1. Verificar nombres de agent - Deben coincidir exactamente en las llamadas de transferencia
  2. Revisar descripciones - Hacerlas más específicas y ricas en palabras clave
  3. Aclarar instrucciones - Ser explícito sobre cuándo transferir
  4. Probar casos límite - Intentar solicitudes ambiguas para ver el comportamiento de enrutamiento
  5. Buscar indicadores de transferencia - [Agent: name] muestra qué agent está respondiendo

Instrucción Global

Uso Básico

let agent = LlmAgentBuilder::new("assistant")
    .description("A helpful assistant")
    .global_instruction(
        "You are a professional assistant for Acme Corp. \
         Always maintain a friendly but professional tone. \
         Our company values are: customer-first, innovation, and integrity."
    )
    .instruction("Help users with their questions and tasks.")
    .model(model.clone())
    .build()?;

Instrucción Global vs. Instrucción de Agent

  • Instrucción Global: Aplicada a todos los agents en la jerarquía, establece la personalidad/contexto general
  • Instrucción de Agent: Específica para cada agent, define su rol y comportamiento particular

Ambas instrucciones se incluyen en el historial de conversación, apareciendo primero la instrucción global.

Instrucciones Globales Dinámicas

Para escenarios más avanzados, puedes usar un proveedor de instrucción global que calcule la instrucción dinámicamente:

use adk_core::GlobalInstructionProvider;

let provider: GlobalInstructionProvider = Arc::new(|ctx| {
    Box::pin(async move {
        // Access context information
        let user_id = ctx.user_id();
        
        // Compute dynamic instruction
        let instruction = format!(
            "You are assisting user {}. Tailor your responses to their preferences.",
            user_id
        );
        
        Ok(instruction)
    })
});

let agent = LlmAgentBuilder::new("assistant")
    .description("A personalized assistant")
    .global_instruction_provider(provider)
    .model(model.clone())
    .build()?;

Inyección de Variables de Estado

Tanto las instrucciones globales como las de los agentes soportan la inyección de variables de estado usando la sintaxis {variable}:

// Set state in a previous agent or tool
// state["company_name"] = "Acme Corp"
// state["user_role"] = "manager"

let agent = LlmAgentBuilder::new("assistant")
    .global_instruction(
        "You are an assistant for {company_name}. \
         The user is a {user_role}."
    )
    .instruction("Help with {user_role}-level tasks.")
    .model(model.clone())
    .build()?;

El framework inyecta automáticamente valores del estado de la sesión en las plantillas de instrucciones.

Patrones Comunes de Multi-Agente

Patrón Coordinador/Despachador

Un agente central enruta las solicitudes a sub-agentes especializados:

let billing = LlmAgentBuilder::new("billing")
    .description("Handles billing and payment questions")
    .model(model.clone())
    .build()?;

let support = LlmAgentBuilder::new("support")
    .description("Provides technical support")
    .model(model.clone())
    .build()?;

let coordinator = LlmAgentBuilder::new("coordinator")
    .instruction("Route requests to billing or support agents as appropriate.")
    .sub_agent(Arc::new(billing))
    .sub_agent(Arc::new(support))
    .model(model.clone())
    .build()?;

Ejemplo de Conversación:

User: I have a question about my last invoice

[Agent: coordinator]
Assistant: I'll connect you with our billing specialist.
🔄 [Transfer requested to: billing]

[Agent: billing]
Assistant: Hello! I can help you with your invoice. 
What specific question do you have?

User: Why was I charged twice?

[Agent: billing]
Assistant: Let me investigate that duplicate charge for you...

Puntos Clave:

  • El coordinador analiza la solicitud y transfiere al agente de facturación
  • El agente de facturación responde inmediatamente en el mismo turno
  • Los mensajes subsiguientes continúan con el agente de facturación
  • Los indicadores de transferencia (🔄) muestran cuándo ocurren los traspasos

Descomposición Jerárquica de Tareas

Jerarquías de múltiples niveles para desglosar tareas complejas:

// Low-level specialists
let researcher = LlmAgentBuilder::new("researcher")
    .description("Researches topics and gathers information")
    .model(model.clone())
    .build()?;

let writer = LlmAgentBuilder::new("writer")
    .description("Writes content based on research")
    .model(model.clone())
    .build()?;

// Mid-level coordinator
let content_creator = LlmAgentBuilder::new("content_creator")
    .description("Creates content by coordinating research and writing")
    .sub_agent(Arc::new(researcher))
    .sub_agent(Arc::new(writer))
    .model(model.clone())
    .build()?;

// Top-level manager
let project_manager = LlmAgentBuilder::new("project_manager")
    .description("Manages content creation projects")
    .sub_agent(Arc::new(content_creator))
    .model(model.clone())
    .build()?;

Combinando con Agentes de Flujo de Trabajo

Los sistemas multi-agente funcionan bien con agentes de flujo de trabajo (Sequential, Parallel, Loop):

use adk_agent::workflow::{SequentialAgent, ParallelAgent};

// Create specialized agents
let validator = LlmAgentBuilder::new("validator")
    .instruction("Validate the input data.")
    .output_key("validation_result")
    .model(model.clone())
    .build()?;

let processor = LlmAgentBuilder::new("processor")
    .instruction("Process data if {validation_result} is valid.")
    .output_key("processed_data")
    .model(model.clone())
    .build()?;

// Combine in a sequential workflow
let pipeline = SequentialAgent::new(
    "validation_pipeline",
    vec![Arc::new(validator), Arc::new(processor)]
);

// Use the pipeline as a sub-agent
let coordinator = LlmAgentBuilder::new("coordinator")
    .description("Coordinates data processing")
    .sub_agent(Arc::new(pipeline))
    .model(model.clone())
    .build()?;

Comunicación entre Agentes

Los Agents en una jerarquía se comunican a través del estado de sesión compartido:

// Agent A saves data to state
let agent_a = LlmAgentBuilder::new("agent_a")
    .instruction("Analyze the topic and save key points.")
    .output_key("key_points")  // Automatically saves output to state
    .model(model.clone())
    .build()?;

// Agent B reads data from state
let agent_b = LlmAgentBuilder::new("agent_b")
    .instruction("Expand on the key points: {key_points}")
    .model(model.clone())
    .build()?;

La configuración output_key guarda automáticamente la respuesta final de un Agent en el estado de sesión, haciéndola disponible para los Agents subsiguientes.

AgentTool Reenvío de State y Artifact

Al usar AgentTool para envolver Agents como Tools, los cambios de estado y los Artifacts de los sub-Agents se reenvían automáticamente al contexto padre:

use adk_tool::AgentTool;

// Create a sub-agent that modifies state
let data_processor = LlmAgentBuilder::new("data_processor")
    .instruction("Process the data and save results.")
    .output_key("processed_data")
    .model(model.clone())
    .build()?;

// Wrap as a tool - state_delta and artifact_delta are forwarded
let processor_tool = AgentTool::new(Arc::new(data_processor));

// Parent agent can use the tool and see state changes
let coordinator = LlmAgentBuilder::new("coordinator")
    .instruction("Use the data_processor tool, then access {processed_data}.")
    .model(model.clone())
    .tool(Arc::new(processor_tool))
    .build()?;

AgentTool ejecuta los sub-Agents en modo no-streaming (StreamingMode::None) internamente, por lo que el sub-Agent acumula su respuesta completa antes de devolverla al padre. Esto evita problemas donde los fragmentos de streaming parciales podrían producir resultados vacíos.

Esto permite un flujo de datos sin interrupciones entre los Agents padre e hijo al usar el patrón AgentTool.

Ejecutando Sistemas Multi-Agente

Usando el Lanzador

El Launcher proporciona una forma sencilla de ejecutar y probar sistemas multi-agente:

use adk_rust::Launcher;

let coordinator = /* your multi-agent setup */;

Launcher::new(Arc::new(coordinator))
    .run()
    .await?;

Modos de Ejecución:

# Interactive console mode
cargo run --manifest-path examples/tier_examples/enterprise/Cargo.toml --bin 14-enterprise-multi-agent

# Use a generated API project when you need HTTP serving
cargo adk new multi_agent_api --template api

Características:

  • Indicadores de agente: Muestra qué agente está respondiendo [Agent: coordinator]
  • Visualización de transferencias: Muestra los eventos de transferencia 🔄 [Transfer requested to: billing_agent]
  • Traspasos sin interrupciones: El agente objetivo responde inmediatamente después de la transferencia
  • Historial de conversación: Mantiene el contexto a través de las transferencias de agente

Probando Transferencias

Para verificar que su sistema multi-agente funciona correctamente:

  1. Verifique que los nombres de los agentes aparezcan entre corchetes cuando respondan
  2. Busque indicadores de transferencia (🔄) cuando los agentes traspasen
  3. Verifique las respuestas inmediatas de los agentes objetivo sin volver a solicitar
  4. Pruebe diferentes tipos de solicitudes para asegurar un enrutamiento adecuado
  5. Verifique casos límite como la transferencia a agentes inexistentes

Depuración de Problemas de Transferencia

Si las transferencias no funcionan:

  • Verifique que los subagentes estén añadidos vía .sub_agent()
  • Revise las descripciones de los Agent — el LLM las usa para decidir las transferencias
  • Revise las instrucciones — el padre debería mencionar cuándo transferir
  • Verifique los nombres de los Agent — deben coincidir exactamente en las llamadas de transferencia
  • Habilite el registro para ver las acciones de transferencia en el flujo de eventos

Mejores Prácticas

  1. Descripciones Claras: Escriba nombres y descripciones de Agent descriptivos para ayudar al LLM a tomar buenas decisiones de transferencia
  2. Instrucciones Específicas: Dé a cada Agent instrucciones claras y enfocadas para su rol
  3. Usar Instrucción Global: Establezca una personalidad y un contexto consistentes en todos los Agents
  4. Gestión de Estado: Use output_key y variables de estado para la comunicación de Agent
  5. Limitar la Profundidad de la Jerarquía: Mantenga las jerarquías poco profundas (2-3 niveles) para una mejor mantenibilidad
  6. Probar la Lógica de Transferencia: Verifique que los Agents transfieran a los sub-Agents correctos para diferentes solicitudes

Anterior: ← Workflow Agents | Siguiente: Graph Agents →