
Multi Agent Patterns
- 12 installs
- 1 repo stars
- Updated January 27, 2026
- bilalmk/todo_correct
multi-agent-patterns is a Claude Code skill for designing multi-agent architectures using supervisor, swarm, and hierarchical patterns.
About
This skill designs multi-agent architectures that distribute work across multiple model instances, each with its own context window. It covers supervisor/orchestrator, peer-to-peer/swarm, and hierarchical patterns, plus coordination protocols and failure modes. A developer uses it when a single agent's context limits are exceeded or a task decomposes into parallel subtasks. It stresses that sub-agents exist to isolate context, and it documents the token cost of doing so.
- Details three architectures: supervisor/orchestrator, peer-to-peer/swarm, and hierarchical
- Documents token economics: multi-agent systems run ~15x baseline tokens
- Explains the telephone-game failure and a forward_message fix
Multi Agent Patterns by the numbers
- 12 all-time installs (skills.sh)
- Ranked #11,618 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Jul 28, 2026 (Skillselion catalog sync)
multi-agent-patterns capabilities & compatibility
- Capabilities
- orchestration
- Use cases
- orchestration
- Runs
- Runs locally
- Pricing
- Free
What multi-agent-patterns says it does
Design multi-agent architectures for complex tasks.
sub-agents exist primarily to isolate context, not to anthropomorphize role division
The supervisor pattern places a central agent in control, delegating to specialists and synthesizing results.
npx skills add https://github.com/bilalmk/todo_correct --skill multi-agent-patternsAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 12 |
|---|---|
| repo stars | ★ 1 |
| Last updated | January 27, 2026 |
| Repository | bilalmk/todo_correct ↗ |
What it does
Design a multi-agent architecture to isolate context and parallelize subtasks when a single agent hits its limits.
Who is it for?
Splitting a complex task across specialized agents with isolated context.
When should I use this skill?
Single-agent context limits are exceeded or a task decomposes naturally into parallel subtasks.
What you get
Delivers a multi-agent architecture that isolates context and parallelizes subtasks.
By the numbers
- Describes 3 architectural patterns
- Multi-agent systems run ~15x baseline tokens
- Token usage explains 80% of performance variance
Files
Multi-Agent Architecture Patterns
Multi-agent architectures distribute work across multiple language model instances, each with its own context window. When designed well, this distribution enables capabilities beyond single-agent limits. When designed poorly, it introduces coordination overhead that negates benefits. The critical insight is that sub-agents exist primarily to isolate context, not to anthropomorphize role division.
When to Activate
Activate this skill when:
- Single-agent context limits constrain task complexity
- Tasks decompose naturally into parallel subtasks
- Different subtasks require different tool sets or system prompts
- Building systems that must handle multiple domains simultaneously
- Scaling agent capabilities beyond single-context limits
- Designing production agent systems with multiple specialized components
Core Concepts
Multi-agent systems address single-agent context limitations through distribution. Three dominant patterns exist: supervisor/orchestrator for centralized control, peer-to-peer/swarm for flexible handoffs, and hierarchical for layered abstraction. The critical design principle is context isolation—sub-agents exist primarily to partition context rather than to simulate organizational roles.
Effective multi-agent systems require explicit coordination protocols, consensus mechanisms that avoid sycophancy, and careful attention to failure modes including bottlenecks, divergence, and error propagation.
Detailed Topics
Why Multi-Agent Architectures
The Context Bottleneck Single agents face inherent ceilings in reasoning capability, context management, and tool coordination. As tasks grow more complex, context windows fill with accumulated history, retrieved documents, and tool outputs. Performance degrades according to predictable patterns: the lost-in-middle effect, attention scarcity, and context poisoning.
Multi-agent architectures address these limitations by partitioning work across multiple context windows. Each agent operates in a clean context focused on its subtask. Results aggregate at a coordination layer without any single context bearing the full burden.
The Token Economics Reality Multi-agent systems consume significantly more tokens than single-agent approaches. Production data shows:
| Architecture | Token Multiplier | Use Case |
|---|---|---|
| Single agent chat | 1× baseline | Simple queries |
| Single agent with tools | ~4× baseline | Tool-using tasks |
| Multi-agent system | ~15× baseline | Complex research/coordination |
Research on the BrowseComp evaluation found that three factors explain 95% of performance variance: token usage (80% of variance), number of tool calls, and model choice. This validates the multi-agent approach of distributing work across agents with separate context windows to add capacity for parallel reasoning.
Critically, upgrading to better models often provides larger performance gains than doubling token budgets. Claude Sonnet 4.5 showed larger gains than doubling tokens on earlier Sonnet versions. GPT-5.2's thinking mode similarly outperforms raw token increases. This suggests model selection and multi-agent architecture are complementary strategies.
The Parallelization Argument Many tasks contain parallelizable subtasks that a single agent must execute sequentially. A research task might require searching multiple independent sources, analyzing different documents, or comparing competing approaches. A single agent processes these sequentially, accumulating context with each step.
Multi-agent architectures assign each subtask to a dedicated agent with a fresh context. All agents work simultaneously, then return results to a coordinator. The total real-world time approaches the duration of the longest subtask rather than the sum of all subtasks.
The Specialization Argument Different tasks benefit from different agent configurations: different system prompts, different tool sets, different context structures. A general-purpose agent must carry all possible configurations in context. Specialized agents carry only what they need.
Multi-agent architectures enable specialization without combinatorial explosion. The coordinator routes to specialized agents; each agent operates with lean context optimized for its domain.
Architectural Patterns
Pattern 1: Supervisor/Orchestrator The supervisor pattern places a central agent in control, delegating to specialists and synthesizing results. The supervisor maintains global state and trajectory, decomposes user objectives into subtasks, and routes to appropriate workers.
User Query -> Supervisor -> [Specialist, Specialist, Specialist] -> Aggregation -> Final OutputWhen to use: Complex tasks with clear decomposition, tasks requiring coordination across domains, tasks where human oversight is important.
Advantages: Strict control over workflow, easier to implement human-in-the-loop interventions, ensures adherence to predefined plans.
Disadvantages: Supervisor context becomes bottleneck, supervisor failures cascade to all workers, "telephone game" problem where supervisors paraphrase sub-agent responses incorrectly.
The Telephone Game Problem and Solution LangGraph benchmarks found supervisor architectures initially performed 50% worse than optimized versions due to the "telephone game" problem where supervisors paraphrase sub-agent responses incorrectly, losing fidelity.
The fix: implement a forward_message tool allowing sub-agents to pass responses directly to users:
def forward_message(message: str, to_user: bool = True):
"""
Forward sub-agent response directly to user without supervisor synthesis.
Use when:
- Sub-agent response is final and complete
- Supervisor synthesis would lose important details
- Response format must be preserved exactly
"""
if to_user:
return {"type": "direct_response", "content": message}
return {"type": "supervisor_input", "content": message}With this pattern, swarm architectures slightly outperform supervisors because sub-agents respond directly to users, eliminating translation errors.
Implementation note: Implement direct pass-through mechanisms allowing sub-agents to pass responses directly to users rather than through supervisor synthesis when appropriate.
Pattern 2: Peer-to-Peer/Swarm The peer-to-peer pattern removes central control, allowing agents to communicate directly based on predefined protocols. Any agent can transfer control to any other through explicit handoff mechanisms.
def transfer_to_agent_b():
return agent_b # Handoff via function return
agent_a = Agent(
name="Agent A",
functions=[transfer_to_agent_b]
)When to use: Tasks requiring flexible exploration, tasks where rigid planning is counterproductive, tasks with emergent requirements that defy upfront decomposition.
Advantages: No single point of failure, scales effectively for breadth-first exploration, enables emergent problem-solving behaviors.
Disadvantages: Coordination complexity increases with agent count, risk of divergence without central state keeper, requires robust convergence constraints.
Implementation note: Define explicit handoff protocols with state passing. Ensure agents can communicate their context needs to receiving agents.
Pattern 3: Hierarchical Hierarchical structures organize agents into layers of abstraction: strategic, planning, and execution layers. Strategy layer agents define goals and constraints; planning layer agents break goals into actionable plans; execution layer agents perform atomic tasks.
Strategy Layer (Goal Definition) -> Planning Layer (Task Decomposition) -> Execution Layer (Atomic Tasks)When to use: Large-scale projects with clear hierarchical structure, enterprise workflows with management layers, tasks requiring both high-level planning and detailed execution.
Advantages: Mirrors organizational structures, clear separation of concerns, enables different context structures at different levels.
Disadvantages: Coordination overhead between layers, potential for misalignment between strategy and execution, complex error propagation.
Context Isolation as Design Principle
The primary purpose of multi-agent architectures is context isolation. Each sub-agent operates in a clean context window focused on its subtask without carrying accumulated context from other subtasks.
Isolation Mechanisms Full context delegation: For complex tasks where the sub-agent needs complete understanding, the planner shares its entire context. The sub-agent has its own tools and instructions but receives full context for its decisions.
Instruction passing: For simple, well-defined subtasks, the planner creates instructions via function call. The sub-agent receives only the instructions needed for its specific task.
File system memory: For complex tasks requiring shared state, agents read and write to persistent storage. The file system serves as the coordination mechanism, avoiding context bloat from shared state passing.
Isolation Trade-offs Full context delegation provides maximum capability but defeats the purpose of sub-agents. Instruction passing maintains isolation but limits sub-agent flexibility. File system memory enables shared state without context passing but introduces latency and consistency challenges.
The right choice depends on task complexity, coordination needs, and acceptable latency.
Consensus and Coordination
The Voting Problem Simple majority voting treats hallucinations from weak models as equal to reasoning from strong models. Without intervention, multi-agent discussions devolve into consensus on false premises due to inherent bias toward agreement.
Weighted Voting Weight agent votes by confidence or expertise. Agents with higher confidence or domain expertise carry more weight in final decisions.
Debate Protocols Debate protocols require agents to critique each other's outputs over multiple rounds. Adversarial critique often yields higher accuracy on complex reasoning than collaborative consensus.
Trigger-Based Intervention Monitor multi-agent interactions for specific behavioral markers. Stall triggers activate when discussions make no progress. Sycophancy triggers detect when agents mimic each other's answers without unique reasoning.
Framework Considerations
Different frameworks implement these patterns with different philosophies. LangGraph uses graph-based state machines with explicit nodes and edges. AutoGen uses conversational/event-driven patterns with GroupChat. CrewAI uses role-based process flows with hierarchical crew structures.
Practical Guidance
Failure Modes and Mitigations
Failure: Supervisor Bottleneck The supervisor accumulates context from all workers, becoming susceptible to saturation and degradation.
Mitigation: Implement output schema constraints so workers return only distilled summaries. Use checkpointing to persist supervisor state without carrying full history.
Failure: Coordination Overhead Agent communication consumes tokens and introduces latency. Complex coordination can negate parallelization benefits.
Mitigation: Minimize communication through clear handoff protocols. Batch results where possible. Use asynchronous communication patterns.
Failure: Divergence Agents pursuing different goals without central coordination can drift from intended objectives.
Mitigation: Define clear objective boundaries for each agent. Implement convergence checks that verify progress toward shared goals. Use time-to-live limits on agent execution.
Failure: Error Propagation Errors in one agent's output propagate to downstream agents that consume that output.
Mitigation: Validate agent outputs before passing to consumers. Implement retry logic with circuit breakers. Use idempotent operations where possible.
Examples
Example 1: Research Team Architecture
Supervisor
├── Researcher (web search, document retrieval)
├── Analyzer (data analysis, statistics)
├── Fact-checker (verification, validation)
└── Writer (report generation, formatting)Example 2: Handoff Protocol
def handle_customer_request(request):
if request.type == "billing":
return transfer_to(billing_agent)
elif request.type == "technical":
return transfer_to(technical_agent)
elif request.type == "sales":
return transfer_to(sales_agent)
else:
return handle_general(request)Guidelines
1. Design for context isolation as the primary benefit of multi-agent systems 2. Choose architecture pattern based on coordination needs, not organizational metaphor 3. Implement explicit handoff protocols with state passing 4. Use weighted voting or debate protocols for consensus 5. Monitor for supervisor bottlenecks and implement checkpointing 6. Validate outputs before passing between agents 7. Set time-to-live limits to prevent infinite loops 8. Test failure scenarios explicitly
Integration
This skill builds on context-fundamentals and context-degradation. It connects to:
- memory-systems - Shared state management across agents
- tool-design - Tool specialization per agent
- context-optimization - Context partitioning strategies
References
Internal reference:
- Frameworks Reference - Detailed framework implementation patterns
Related skills in this collection:
- context-fundamentals - Context basics
- memory-systems - Cross-agent memory
- context-optimization - Partitioning strategies
External resources:
- LangGraph Documentation - Multi-agent patterns and state management
- AutoGen Framework - GroupChat and conversational patterns
- CrewAI Documentation - Hierarchical agent processes
- Research on Multi-Agent Coordination - Survey of multi-agent systems
---
Skill Metadata
Created: 2025-12-20 Last Updated: 2025-12-20 Author: Agent Skills for Context Engineering Contributors Version: 1.0.0
Multi-Agent Patterns: Technical Reference
This document provides implementation details for multi-agent architectures across different frameworks.
Supervisor Pattern
LangGraph Supervisor Implementation
Implement a supervisor that routes to worker nodes:
from typing import TypedDict, Union
from langgraph.graph import StateGraph, END
class AgentState(TypedDict):
task: str
current_agent: str
task_output: dict
messages: list
def supervisor_node(state: AgentState) -> AgentState:
"""
Supervisor decides which worker to invoke next.
Returns routing decision and updates state.
"""
task = state["task"]
messages = state.get("messages", [])
# Determine next agent based on task and history
if "research" in task.lower():
next_agent = "researcher"
elif "write" in task.lower() or "create" in task.lower():
next_agent = "writer"
elif "review" in task.lower() or "analyze" in task.lower():
next_agent = "reviewer"
else:
next_agent = "coordinator"
return {
"task": task,
"current_agent": next_agent,
"task_output": {},
"messages": messages + [{"supervisor": f"Routing to {next_agent}"}]
}
def researcher_node(state: AgentState) -> AgentState:
"""Research worker that gathers information."""
# Perform research task
output = perform_research(state["task"])
return {
"task": state["task"],
"current_agent": "researcher",
"task_output": output,
"messages": state["messages"] + [{"researcher": "Research complete"}]
}
def writer_node(state: AgentState) -> AgentState:
"""Writer worker that creates content based on research."""
output = create_content(state["task"], state["task_output"])
return {
"task": state["task"],
"current_agent": "writer",
"task_output": output,
"messages": state["messages"] + [{"writer": "Content created"}]
}
def build_supervisor_graph():
"""Build the supervisor workflow graph."""
workflow = StateGraph(AgentState)
# Add nodes
workflow.add_node("supervisor", supervisor_node)
workflow.add_node("researcher", researcher_node)
workflow.add_node("writer", writer_node)
# Add edges
workflow.add_edge("supervisor", "researcher")
workflow.add_edge("researcher", "supervisor")
workflow.add_edge("supervisor", "writer")
workflow.add_edge("writer", "supervisor")
# Set entry point
workflow.set_entry_point("supervisor")
return workflow.compile()AutoGen Supervisor
Implement supervisor using GroupChat pattern:
from autogen import AssistantAgent, UserProxyAgent, GroupChat
# Define specialized agents
researcher = AssistantAgent(
name="researcher",
system_message="""You are a research specialist.
Your goal is to gather accurate, comprehensive information
on topics assigned by the supervisor. Always cite sources
and note confidence levels.""",
llm_config=llm_config
)
writer = AssistantAgent(
name="writer",
system_message="""You are a content creation specialist.
Your goal is to create well-structured content based on
research provided by the supervisor. Follow style guidelines
and ensure factual accuracy.""",
llm_config=llm_config
)
# Define supervisor
supervisor = AssistantAgent(
name="supervisor",
system_message="""You are the project supervisor.
Your goal is to coordinate researchers and writers to
complete tasks efficiently.
Process:
1. Break down the task into research and writing phases
2. Route to appropriate specialists
3. Synthesize results into final output
4. Ensure quality before completing""",
llm_config=llm_config
)
# Configure group chat
group_chat = GroupChat(
agents=[supervisor, researcher, writer],
messages=[],
max_round=20
)
manager = GroupChatManager(
groupchat=group_chat,
llm_config=llm_config
)Swarm Pattern Implementation
LangGraph Swarms
Implement peer-to-peer handoffs:
def create_agent(name, system_prompt, tools):
"""Create an agent node for the swarm."""
def agent_node(state):
# Process current state with agent
response = invoke_agent(name, system_prompt, state["input"], tools)
# Check for handoff
if "handoff" in response:
return {"next_agent": response["handoff"], "output": response["output"]}
else:
return {"next_agent": END, "output": response["output"]}
return agent_node
def build_swarm():
"""Build a peer-to-peer agent swarm."""
workflow = StateGraph(State)
# Create agents
triage = create_agent("triage", TRIAGE_PROMPT, [search, read])
research = create_agent("research", RESEARCH_PROMPT, [search, browse, read])
analysis = create_agent("analysis", ANALYSIS_PROMPT, [calculate, compare])
writing = create_agent("writing", WRITING_PROMPT, [write, edit])
# Add to graph
workflow.add_node("triage", triage)
workflow.add_node("research", research)
workflow.add_node("analysis", analysis)
workflow.add_node("writing", writing)
# Define handoff edges
workflow.add_edge("triage", "research")
workflow.add_edge("triage", "analysis")
workflow.add_edge("research", "writing")
workflow.add_edge("analysis", "writing")
workflow.set_entry_point("triage")
return workflow.compile()Hierarchical Pattern Implementation
CrewAI-Style Hierarchy
class ManagerAgent:
def __init__(self, name, system_prompt, llm):
self.name = name
self.system_prompt = system_prompt
self.llm = llm
self.workers = []
def add_worker(self, worker):
"""Add a worker agent to the team."""
self.workers.append(worker)
def delegate(self, task):
"""
Analyze task and delegate to appropriate worker.
Returns work assignment and expected output format.
"""
# Analyze task requirements
requirements = analyze_task_requirements(task)
# Select best worker
best_worker = select_worker(self.workers, requirements)
# Create assignment
assignment = {
"worker": best_worker.name,
"task": task,
"context": self.get_relevant_context(task),
"output_format": requirements.output_format,
"deadline": requirements.deadline
}
return assignment
def review_output(self, worker_output, requirements):
"""
Review worker output against requirements.
Returns approval or revision request.
"""
quality_score = assess_quality(worker_output, requirements)
if quality_score >= requirements.threshold:
return {"status": "approved", "output": worker_output}
else:
return {
"status": "revision_requested",
"feedback": generate_feedback(worker_output, requirements),
"revise_worker": requirements.revise_worker
}Context Isolation Patterns
Full Context Delegation
def delegate_with_full_context(planner_state, subagent):
"""
Pass entire planner context to subagent.
Use for complex tasks requiring complete understanding.
"""
return {
"context": planner_state,
"subagent": subagent,
"isolation_mode": "full"
}Instruction Passing
def delegate_with_instructions(task_spec, subagent):
"""
Pass only instructions to subagent.
Use for simple, well-defined subtasks.
"""
return {
"instructions": {
"objective": task_spec.objective,
"constraints": task_spec.constraints,
"inputs": task_spec.inputs,
"outputs": task_spec.output_schema
},
"subagent": subagent,
"isolation_mode": "minimal"
}File System Coordination
class FileSystemCoordination:
def __init__(self, workspace_path):
self.workspace = workspace_path
def write_shared_state(self, key, value):
"""Write state accessible to all agents."""
path = f"{self.workspace}/{key}.json"
with open(path, 'w') as f:
json.dump(value, f)
return path
def read_shared_state(self, key):
"""Read state written by any agent."""
path = f"{self.workspace}/{key}.json"
with open(path, 'r') as f:
return json.load(f)
def acquire_lock(self, resource, agent_id):
"""Prevent concurrent access to shared resources."""
lock_path = f"{self.workspace}/locks/{resource}.lock"
if os.path.exists(lock_path):
return False
with open(lock_path, 'w') as f:
f.write(agent_id)
return TrueConsensus Mechanisms
Weighted Voting
def weighted_consensus(agent_outputs, weights):
"""
Calculate weighted consensus from agent outputs.
Weight = verbalized_confidence * domain_expertise
"""
weighted_sum = sum(
output.vote * weights[output.agent_id]
for output in agent_outputs
)
total_weight = sum(weights[output.agent_id] for output in agent_outputs)
return weighted_sum / total_weightDebate Protocol
class DebateProtocol:
def __init__(self, agents, max_rounds=5):
self.agents = agents
self.max_rounds = max_rounds
self.history = []
def run_debate(self, topic):
"""Execute structured debate on topic."""
# Initial statements
statements = {agent.name: agent.initial_statement(topic)
for agent in self.agents}
for round_num in range(self.max_rounds):
# Generate critiques
critiques = {}
for agent in self.agents:
critiques[agent.name] = agent.critique(
topic,
statements,
exclude=[agent.name]
)
# Update statements with critique integration
for agent in self.agents:
statements[agent.name] = agent.integrate_critique(
statements[agent.name],
critiques
)
# Check for convergence
if self.check_convergence(statements):
break
# Final evaluation
return self.evaluate_final(statements)Failure Recovery
Circuit Breaker
class AgentCircuitBreaker:
def __init__(self, failure_threshold=3, timeout_seconds=60):
self.failure_count = {}
self.failure_threshold = failure_threshold
self.timeout_seconds = timeout_seconds
def call(self, agent, task):
"""Execute agent task with circuit breaker protection."""
if self.is_open(agent.name):
raise CircuitBreakerOpen(f"Agent {agent.name} temporarily unavailable")
try:
result = agent.execute(task)
self.record_success(agent.name)
return result
except Exception as e:
self.record_failure(agent.name)
if self.failure_count[agent.name] >= self.failure_threshold:
self.open_circuit(agent.name)
raiseCheckpoint and Resume
class CheckpointManager:
def __init__(self, checkpoint_dir):
self.checkpoint_dir = checkpoint_dir
os.makedirs(checkpoint_dir, exist_ok=True)
def save_checkpoint(self, workflow_id, step, state):
"""Save workflow state for potential resume."""
checkpoint = {
"workflow_id": workflow_id,
"step": step,
"state": state,
"timestamp": time.time()
}
path = f"{self.checkpoint_dir}/{workflow_id}.json"
with open(path, 'w') as f:
json.dump(checkpoint, f)
def load_checkpoint(self, workflow_id):
"""Load last saved checkpoint for workflow."""
path = f"{self.checkpoint_dir}/{workflow_id}.json"
with open(path, 'r') as f:
return json.load(f)"""
Multi-Agent Coordination
This module provides utilities for implementing multi-agent coordination patterns.
"""
from typing import Dict, List, Any, Optional
from dataclasses import dataclass, field
from enum import Enum
import time
import uuid
class MessageType(Enum):
REQUEST = "request"
RESPONSE = "response"
HANDOVER = "handover"
FEEDBACK = "feedback"
ALERT = "alert"
@dataclass
class AgentMessage:
"""Message exchanged between agents."""
sender: str
receiver: str
message_type: MessageType
content: Dict[str, Any]
timestamp: float = field(default_factory=time.time)
message_id: str = field(default_factory=lambda: str(uuid.uuid4()))
requires_response: bool = False
priority: int = 0 # 0 = normal, higher = more urgent
class AgentCommunication:
"""Communication channel for multi-agent systems."""
def __init__(self):
self.inbox: Dict[str, List[AgentMessage]] = {}
self.outbox: List[AgentMessage] = []
self.message_history: List[AgentMessage] = []
def send(self, message: AgentMessage):
"""Send a message to an agent."""
if message.receiver not in self.inbox:
self.inbox[message.receiver] = []
self.inbox[message.receiver].append(message)
self.outbox.append(message)
self.message_history.append(message)
def receive(self, agent_id: str) -> List[AgentMessage]:
"""Receive all messages for an agent."""
messages = self.inbox.get(agent_id, [])
self.inbox[agent_id] = [] # Clear inbox after receiving
return messages
def broadcast(self, sender: str, message_type: MessageType,
content: Dict[str, Any], receivers: List[str]):
"""Broadcast message to multiple agents."""
for receiver in receivers:
self.send(AgentMessage(
sender=sender,
receiver=receiver,
message_type=message_type,
content=content
))
# Supervisor Pattern Implementation
class SupervisorAgent:
"""
Central supervisor agent that coordinates worker agents.
"""
def __init__(self, name: str, communication: AgentCommunication):
self.name = name
self.communication = communication
self.workers: Dict[str, Dict] = {}
self.task_queue: List[Dict] = []
self.completed_tasks: List[Dict] = []
self.current_state: Dict = {}
def register_worker(self, worker_id: str, capabilities: List[str]):
"""Register a worker agent with the supervisor."""
self.workers[worker_id] = {
"capabilities": capabilities,
"status": "available",
"current_task": None,
"metrics": {"tasks_completed": 0, "avg_response_time": 0}
}
def decompose_task(self, task: Dict) -> List[Dict]:
"""
Decompose a task into subtasks.
In production, this would use task analysis and planning.
"""
subtasks = []
# Simple decomposition based on task type
task_type = task.get("type", "general")
if task_type == "research":
subtasks = [
{"type": "search", "description": "Gather information"},
{"type": "analyze", "description": "Analyze findings"},
{"type": "synthesize", "description": "Synthesize results"}
]
elif task_type == "create":
subtasks = [
{"type": "plan", "description": "Create plan"},
{"type": "draft", "description": "Draft content"},
{"type": "review", "description": "Review and refine"}
]
else:
subtasks = [
{"type": "execute", "description": task.get("description", "Execute task")}
]
# Add parent task info
for subtask in subtasks:
subtask["parent_task"] = task.get("id")
subtask["priority"] = task.get("priority", 0)
return subtasks
def assign_task(self, subtask: Dict, worker_id: str):
"""Assign a subtask to a worker agent."""
if worker_id not in self.workers:
raise ValueError(f"Unknown worker: {worker_id}")
self.workers[worker_id]["status"] = "busy"
self.workers[worker_id]["current_task"] = subtask["id"]
self.send(AgentMessage(
sender=self.name,
receiver=worker_id,
message_type=MessageType.REQUEST,
content={
"action": "execute_task",
"task": subtask
},
requires_response=True,
priority=subtask.get("priority", 0)
))
def select_worker(self, subtask: Dict) -> str:
"""Select the best worker for a subtask."""
required_capability = subtask.get("type", "general")
# Find available workers with required capability
candidates = [
wid for wid, info in self.workers.items()
if info["status"] == "available"
and required_capability in info["capabilities"]
]
if not candidates:
# Fall back to any available worker
candidates = [
wid for wid, info in self.workers.items()
if info["status"] == "available"
]
if not candidates:
raise ValueError("No available workers")
# Select based on metrics (fewest tasks completed = most available)
return min(candidates, key=lambda w: self.workers[w]["metrics"]["tasks_completed"])
def aggregate_results(self, subtask_results: List[Dict]) -> Dict:
"""Aggregate results from subtasks."""
aggregated = {
"results": subtask_results,
"summary": "",
"quality_score": 0.0
}
# Generate summary from results
summaries = [r.get("summary", "") for r in subtask_results if r.get("success")]
aggregated["summary"] = " | ".join(summaries)
# Calculate quality score
successful = sum(1 for r in subtask_results if r.get("success", False))
aggregated["quality_score"] = successful / len(subtask_results) if subtask_results else 0
return aggregated
def run_workflow(self, task: Dict) -> Dict:
"""Execute a complete workflow with supervision."""
# Decompose task
subtasks = self.decompose_task(task)
# Assign subtasks
results = []
for subtask in subtasks:
worker = self.select_worker(subtask)
self.assign_task(subtask, worker)
# Wait for result
messages = self.receive(self.name)
for msg in messages:
if msg.message_type == MessageType.RESPONSE:
results.append(msg.content)
# Aggregate results
final_result = self.aggregate_results(results)
return {
"task": task,
"subtask_results": results,
"final_result": final_result,
"success": final_result["quality_score"] >= 0.8
}
def send(self, message: AgentMessage):
"""Send message through communication channel."""
self.communication.send(message)
# Handoff Protocol
class HandoffProtocol:
"""
Protocol for agent-to-agent handoffs.
"""
def __init__(self, communication: AgentCommunication):
self.communication = communication
def create_handoff(self, from_agent: str, to_agent: str,
context: Dict, reason: str) -> AgentMessage:
"""Create a handoff message."""
return AgentMessage(
sender=from_agent,
receiver=to_agent,
message_type=MessageType.HANDOVER,
content={
"handoff_reason": reason,
"transferred_context": context,
"handoff_timestamp": time.time()
},
priority=1
)
def accept_handoff(self, agent_id: str) -> Optional[AgentMessage]:
"""Accept pending handoff for an agent."""
messages = self.communication.receive(agent_id)
for msg in messages:
if msg.message_type == MessageType.HANDOVER:
return msg
return None
def transfer_with_state(self, from_agent: str, to_agent: str,
state: Dict, task: Dict) -> bool:
"""
Transfer task state from one agent to another.
Returns success status.
"""
handoff = self.create_handoff(
from_agent=from_agent,
to_agent=to_agent,
context={
"task_state": state,
"task_details": task,
"progress": state.get("progress", 0)
},
reason="task_transfer"
)
self.communication.send(handoff)
# Wait for acknowledgment
time.sleep(0.1) # In production, use async with timeout
ack = self.communication.receive(from_agent)
return any(
m.message_type == MessageType.RESPONSE and
m.content.get("status") == "handoff_received"
for m in ack
)
# Consensus Mechanism
class ConsensusManager:
"""
Manager for multi-agent consensus building.
"""
def __init__(self):
self.votes: Dict[str, List[Dict]] = {}
self.debates: Dict[str, List[Dict]] = {}
def initiate_vote(self, topic_id: str, agents: List[str],
options: List[str]):
"""Initiate a voting round on a topic."""
self.votes[topic_id] = []
# Request votes from agents
for agent in agents:
vote_request = {
"agent": agent,
"topic": topic_id,
"options": options,
"status": "pending"
}
self.votes[topic_id].append(vote_request)
def submit_vote(self, topic_id: str, agent_id: str,
selection: str, confidence: float):
"""Submit a vote for a topic."""
if topic_id not in self.votes:
raise ValueError(f"Unknown topic: {topic_id}")
vote_record = {
"agent": agent_id,
"selection": selection,
"confidence": confidence,
"timestamp": time.time()
}
for vote in self.votes[topic_id]:
if vote["agent"] == agent_id:
vote["status"] = "cast"
vote["selection"] = selection
vote["confidence"] = confidence
break
def calculate_weighted_consensus(self, topic_id: str) -> Dict:
"""
votes.
Weight = confidence * expertise_factor
Calculate weighted consensus from """
if topic_id not in self.votes:
raise ValueError(f"Unknown topic: {topic_id}")
votes = [v for v in self.votes[topic_id] if v.get("status") == "cast"]
if not votes:
return {"status": "no_votes", "result": None}
# Group by selection
selections: Dict[str, List[Dict]] = {}
for vote in votes:
selection = vote["selection"]
if selection not in selections:
selections[selection] = []
selections[selection].append(vote)
# Calculate weighted score for each selection
results = {}
for selection, selection_votes in selections.items():
weighted_sum = sum(v["confidence"] for v in selection_votes)
avg_confidence = weighted_sum / len(selection_votes) if selection_votes else 0
results[selection] = {
"weighted_score": weighted_sum,
"avg_confidence": avg_confidence,
"vote_count": len(selection_votes)
}
# Select winner
winner = max(results.keys(), key=lambda s: results[s]["weighted_score"])
return {
"status": "complete",
"result": winner,
"details": results,
"consensus_strength": results[winner]["weighted_score"] / len(votes) if votes else 0
}
# Failure Handling
class AgentFailureHandler:
"""
Handler for agent failures in multi-agent systems.
"""
def __init__(self, communication: AgentCommunication,
max_retries: int = 3):
self.communication = communication
self.max_retries = max_retries
self.failure_counts: Dict[str, int] = {}
self.circuit_breakers: Dict[str, float] = {} # agent -> unlock time
def handle_failure(self, agent_id: str, task_id: str,
error: str) -> Dict:
"""
Handle a failure from an agent.
Returns action to take.
"""
# Increment failure count
self.failure_counts[agent_id] = self.failure_counts.get(agent_id, 0) + 1
# Check if circuit breaker should activate
if self.failure_counts[agent_id] >= self.max_retries:
self._activate_circuit_breaker(agent_id)
return {
"action": "reroute",
"reason": "circuit_breaker_activated",
"alternative": self._find_alternative_agent(agent_id)
}
return {
"action": "retry",
"reason": error,
"retry_count": self.failure_counts[agent_id],
"delay": min(2 ** self.failure_counts[agent_id], 60) # Exponential backoff
}
def _activate_circuit_breaker(self, agent_id: str):
"""Temporarily disable an agent."""
self.circuit_breakers[agent_id] = time.time() + 60 # 1 minute cooldown
def _find_alternative_agent(self, failed_agent: str) -> str:
"""Find an alternative agent to handle the task."""
# In production, this would check agent capabilities and availability
return "default_backup_agent"
def is_available(self, agent_id: str) -> bool:
"""Check if an agent is available (circuit breaker not active)."""
if agent_id in self.circuit_breakers:
if time.time() < self.circuit_breakers[agent_id]:
return False
# Reset after cooldown
del self.circuit_breakers[agent_id]
self.failure_counts[agent_id] = 0
return True
def record_success(self, agent_id: str):
"""Record a successful task completion."""
self.failure_counts[agent_id] = 0
#!/usr/bin/env python3
"""Verify skill structure and content."""
import sys
from pathlib import Path
def main():
skill_dir = Path(__file__).parent.parent
skill_md = skill_dir / "SKILL.md"
if not skill_md.exists():
print("✗ SKILL.md not found")
sys.exit(1)
content = skill_md.read_text()
# Check frontmatter
if not content.startswith("---"):
print("✗ Missing YAML frontmatter")
sys.exit(1)
# Check required sections
required = ["When to Activate", "Core Concepts", "Guidelines"]
missing = [s for s in required if s not in content]
if missing:
print(f"✗ Missing sections: {', '.join(missing)}")
sys.exit(1)
print(f"✓ {skill_dir.name} skill validated")
sys.exit(0)
if __name__ == "__main__":
main()