Agent-to-Agent Communication
Multi-agent collaboration
Build sophisticated multi-agent systems where agents can communicate, delegate tasks, and collaborate on complex workflows. The A2A protocol enables agents to work together like a team, with each agent specializing in different capabilities. Perfect for complex tasks that require multiple skills like research + writing, analysis + visualization, or planning + execution.
Installation
Install the A2A package to enable multi-agent collaboration in your OrkaJS applications.
# ─────────────────────────────────────────────────────────────────────────────# Install @orka-js/a2a for multi-agent collaboration# ───────────────────────────────────────────────────────────────────────────── npm install @orka-js/a2a # Or with pnpmpnpm add @orka-js/a2a # The package works with any OrkaJS agent type:# - StreamingToolAgent# - ReActAgent# - PlanAndExecuteAgent# - OpenAIFunctionsAgentCommunication Patterns
Agents send messages to each other directly, like a conversation
One agent delegates subtasks to specialized agents
A coordinator agent manages the workflow between agents
Multiple agents vote or agree on decisions
Basic Network Setup
Create a network of agents that can collaborate on tasks. Each agent has its own goal and tools.
// ─────────────────────────────────────────────────────────────────────────────// Basic Agent Network//// Create a network of specialized agents that collaborate on tasks.// In this example:// - Researcher: Finds information using web search// - Writer: Creates content based on research// - Editor: Reviews and improves the content// ───────────────────────────────────────────────────────────────────────────── import { AgentNetwork } from '@orka-js/a2a';import { StreamingToolAgent } from '@orka-js/agent';import { OpenAIAdapter } from '@orka-js/openai'; const llm = new OpenAIAdapter({ apiKey: process.env.OPENAI_API_KEY! }); // ─── Define Specialized Agents ─────────────────────────────────────────────── // Research Agent: Expert at finding informationconst researcher = new StreamingToolAgent({ goal: 'Research topics thoroughly and provide accurate information', systemPrompt: `You are a research specialist. Your job is to:1. Search for relevant information on the given topic2. Verify facts from multiple sources3. Summarize findings clearly for other team membersAlways cite your sources.`, tools: [webSearch, academicSearch],}, llm); // Writer Agent: Expert at creating contentconst writer = new StreamingToolAgent({ goal: 'Write engaging, well-structured content based on research', systemPrompt: `You are a professional writer. Your job is to:1. Take research provided by the research team2. Create engaging, well-structured content3. Ensure the content is accurate and easy to understandWrite in a clear, professional tone.`, tools: [], // Writer doesn't need tools, just uses the LLM}, llm); // Editor Agent: Expert at reviewing and improving contentconst editor = new StreamingToolAgent({ goal: 'Review content for quality, accuracy, and clarity', systemPrompt: `You are an expert editor. Your job is to:1. Review content for grammar, style, and clarity2. Fact-check against the original research3. Suggest improvements and polish the final outputBe thorough but constructive.`, tools: [grammarCheck, factCheck],}, llm); // ─── Create the Agent Network ──────────────────────────────────────────────── const network = new AgentNetwork({ // Register all agents with their names // These names are used for routing and delegation agents: { researcher, writer, editor, }, // Communication protocol: // - 'message-passing': Agents send messages to each other // - 'delegation': Coordinator delegates to specialists // - 'orchestration': Defined workflow between agents protocol: 'message-passing', // Optional: Define which agent starts the workflow entryPoint: 'researcher', // Optional: Maximum rounds of communication (prevents infinite loops) maxRounds: 10,}); // ─── Run a Task Through the Network ────────────────────────────────────────── const result = await network.run( // The task to accomplish 'Write a comprehensive article about the future of AI in healthcare', // Options { // Which agent coordinates the task coordinator: 'researcher', // Optional: Provide context for all agents context: { targetAudience: 'Healthcare professionals', wordCount: 1500, tone: 'professional', }, }); // Result contains the final output and execution traceconsole.log('Final Article:', result.output);console.log('Agents involved:', result.trace.agents);console.log('Total rounds:', result.trace.rounds);Task Delegation
Set up a coordinator agent that can delegate subtasks to specialized agents.
// ─────────────────────────────────────────────────────────────────────────────// Task Delegation Pattern//// A coordinator agent receives tasks and delegates subtasks to specialists.// This is useful when you have a complex task that requires multiple skills.// ───────────────────────────────────────────────────────────────────────────── import { AgentNetwork, DelegationProtocol } from '@orka-js/a2a'; // ─── Create Specialist Agents ──────────────────────────────────────────────── const dataAnalyst = new StreamingToolAgent({ goal: 'Analyze data and extract insights', tools: [queryDatabase, runStatistics, createChart],}, llm); const reportWriter = new StreamingToolAgent({ goal: 'Write clear, professional reports', tools: [formatDocument, addVisuals],}, llm); const factChecker = new StreamingToolAgent({ goal: 'Verify facts and data accuracy', tools: [searchSources, compareData],}, llm); // ─── Create Coordinator Agent ──────────────────────────────────────────────── // The coordinator has a special tool: delegateTask// This tool allows it to send subtasks to other agentsconst coordinator = new StreamingToolAgent({ goal: 'Coordinate complex tasks by delegating to specialists', systemPrompt: `You are a project coordinator. Your job is to:1. Break down complex tasks into subtasks2. Delegate subtasks to the right specialist3. Combine results into a final deliverable Available specialists:- dataAnalyst: For data analysis and visualization- reportWriter: For writing reports and documentation- factChecker: For verifying accuracy Use the delegateTask tool to assign work to specialists.`, // The delegateTask tool is automatically added by the network tools: [],}, llm); // ─── Create Network with Delegation Protocol ───────────────────────────────── const network = new AgentNetwork({ agents: { coordinator, dataAnalyst, reportWriter, factChecker, }, // Use delegation protocol protocol: new DelegationProtocol({ // The coordinator agent coordinator: 'coordinator', // Specialists that can receive delegated tasks specialists: ['dataAnalyst', 'reportWriter', 'factChecker'], // How specialists report back reportingMode: 'immediate', // or 'batch' for collecting all results // Allow specialists to delegate to each other allowSubDelegation: false, }),}); // ─── Run a Complex Task ────────────────────────────────────────────────────── const result = await network.run( 'Create a quarterly sales report with analysis and recommendations', { // Provide data context context: { quarter: 'Q4 2024', dataSource: 'sales_database', }, }); // The coordinator will:// 1. Ask dataAnalyst to analyze sales data// 2. Ask factChecker to verify the numbers// 3. Ask reportWriter to create the final report// 4. Combine everything into the final deliverable console.log('Report:', result.output);console.log('Delegation trace:', result.trace.delegations);// [// { from: 'coordinator', to: 'dataAnalyst', task: 'Analyze Q4 sales...' },// { from: 'coordinator', to: 'factChecker', task: 'Verify these numbers...' },// { from: 'coordinator', to: 'reportWriter', task: 'Write report with...' },// ]Workflow Orchestration
Create complex workflows where agents work in sequence or parallel.
// ─────────────────────────────────────────────────────────────────────────────// Workflow Orchestration Pattern//// Define a structured workflow where agents work in sequence or parallel.// This gives you precise control over the execution order.// ───────────────────────────────────────────────────────────────────────────── import { AgentNetwork, WorkflowOrchestrator } from '@orka-js/a2a'; // ─── Define the Workflow ───────────────────────────────────────────────────── const workflow = new WorkflowOrchestrator({ // Define workflow steps steps: [ // Step 1: Research (runs first) { name: 'research', agent: 'researcher', description: 'Gather information on the topic', // Input comes from the initial task input: (task) => task.query, }, // Step 2: Analysis (runs after research) { name: 'analysis', agent: 'analyst', description: 'Analyze the research findings', // Input comes from previous step's output input: (task, results) => ({ research: results.research.output, focus: task.analysisFocus, }), // Only run if research was successful condition: (results) => results.research.success, }, // Step 3: Writing and Review (run in parallel) { name: 'parallel-review', parallel: [ { name: 'draft', agent: 'writer', description: 'Write the first draft', input: (task, results) => ({ research: results.research.output, analysis: results.analysis.output, }), }, { name: 'outline', agent: 'editor', description: 'Create content outline', input: (task, results) => results.analysis.output, }, ], }, // Step 4: Final editing (runs after parallel steps complete) { name: 'final-edit', agent: 'editor', description: 'Polish the final content', input: (task, results) => ({ draft: results.draft.output, outline: results.outline.output, }), }, ], // Error handling onStepError: async (step, error, results) => { console.error(`Step ${step.name} failed:`, error); // Return fallback or rethrow return { fallback: true, message: 'Step failed, using fallback' }; }, // Progress tracking onStepComplete: async (step, result) => { console.log(`✓ Step ${step.name} completed`); },}); // ─── Create Network with Workflow ──────────────────────────────────────────── const network = new AgentNetwork({ agents: { researcher, analyst, writer, editor }, protocol: workflow,}); // ─── Execute the Workflow ──────────────────────────────────────────────────── const result = await network.run({ query: 'Impact of remote work on productivity', analysisFocus: 'statistical trends',}); // Access results from each stepconsole.log('Research:', result.steps.research.output);console.log('Analysis:', result.steps.analysis.output);console.log('Draft:', result.steps.draft.output);console.log('Final:', result.steps['final-edit'].output); // Workflow execution timelineconsole.log('Timeline:', result.timeline);// [// { step: 'research', duration: 5200, status: 'success' },// { step: 'analysis', duration: 3100, status: 'success' },// { step: 'draft', duration: 4500, status: 'success' }, // parallel// { step: 'outline', duration: 2800, status: 'success' }, // parallel// { step: 'final-edit', duration: 3200, status: 'success' },// ]Network Events
Monitor agent communication and task progress with event listeners.
// ─────────────────────────────────────────────────────────────────────────────// Network Events & Monitoring//// Listen to events to monitor agent communication, track progress,// and debug multi-agent workflows.// ───────────────────────────────────────────────────────────────────────────── import { AgentNetwork } from '@orka-js/a2a'; const network = new AgentNetwork({ agents: { researcher, writer, editor }, protocol: 'message-passing',}); // ─── Message Events ────────────────────────────────────────────────────────── // When an agent sends a message to another agentnetwork.on('message', (event) => { console.log(`[${event.from}] → [${event.to}]: ${event.content.substring(0, 100)}...`); // event structure: // { // from: 'researcher', // to: 'writer', // content: 'Here is the research on AI in healthcare...', // timestamp: Date, // round: 1, // }}); // ─── Agent Activity Events ─────────────────────────────────────────────────── // When an agent starts processingnetwork.on('agentStart', (event) => { console.log(`🚀 Agent ${event.agent} started working on: ${event.task}`);}); // When an agent finishes processingnetwork.on('agentComplete', (event) => { console.log(`✅ Agent ${event.agent} completed in ${event.duration}ms`);}); // When an agent uses a toolnetwork.on('toolCall', (event) => { console.log(`🔧 Agent ${event.agent} called tool: ${event.tool}(${JSON.stringify(event.args)})`);}); // ─── Delegation Events ─────────────────────────────────────────────────────── // When a task is delegatednetwork.on('delegation', (event) => { console.log(`📋 ${event.from} delegated to ${event.to}: ${event.task}`);}); // When a delegated task is completednetwork.on('delegationComplete', (event) => { console.log(`📬 ${event.to} returned result to ${event.from}`);}); // ─── Workflow Events ───────────────────────────────────────────────────────── // When a workflow step startsnetwork.on('stepStart', (event) => { console.log(`📍 Step ${event.step} started`);}); // When a workflow step completesnetwork.on('stepComplete', (event) => { console.log(`✓ Step ${event.step} completed in ${event.duration}ms`);}); // ─── Error Events ──────────────────────────────────────────────────────────── // When an error occursnetwork.on('error', (event) => { console.error(`❌ Error in agent ${event.agent}:`, event.error); // You can implement retry logic here if (event.retryable) { console.log('Retrying...'); }}); // ─── Network-Level Events ──────────────────────────────────────────────────── // When the network starts processing a tasknetwork.on('start', (event) => { console.log(`🌐 Network started processing: ${event.task}`);}); // When the network completes a tasknetwork.on('complete', (event) => { console.log(`🎉 Network completed in ${event.totalDuration}ms`); console.log(` Rounds: ${event.rounds}`); console.log(` Agents used: ${event.agentsUsed.join(', ')}`);}); // ─── Run with Events ───────────────────────────────────────────────────────── const result = await network.run('Write an article about AI'); // Output will show all events as they happen:// 🌐 Network started processing: Write an article about AI// 🚀 Agent researcher started working on: Write an article about AI// 🔧 Agent researcher called tool: webSearch({"query":"AI trends 2024"})// ✅ Agent researcher completed in 3200ms// [researcher] → [writer]: Here is the research on AI...// 🚀 Agent writer started working on: Write based on research// ✅ Agent writer completed in 4100ms// [writer] → [editor]: Here is the draft article...// 🚀 Agent editor started working on: Review and polish// ✅ Agent editor completed in 2800ms// 🎉 Network completed in 10100ms// Rounds: 3// Agents used: researcher, writer, editorBest Practices
- Give each agent a clear, specific goal to avoid confusion
- Use maxRounds to prevent infinite loops in message-passing
- Monitor events during development to understand agent behavior
- Start with simple workflows and add complexity gradually
- Use different LLMs for different agents based on their needs