Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
A comprehensive collection of Agent Skills for context engineering, multi-agent architectures, and production agent systems.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
skills/multi-agent-patterns/references/frameworks.md
1# Multi-Agent Patterns: Technical Reference23This document provides implementation details for multi-agent architectures across different frameworks.45## Supervisor Pattern67### LangGraph Supervisor Implementation89Implement a supervisor that routes to worker nodes:1011```python12from typing import TypedDict, Union13from langgraph.graph import StateGraph, END1415class AgentState(TypedDict):16task: str17current_agent: str18task_output: dict19messages: list2021def supervisor_node(state: AgentState) -> AgentState:22"""23Supervisor decides which worker to invoke next.2425Returns routing decision and updates state.26"""27task = state["task"]28messages = state.get("messages", [])2930# Determine next agent based on task and history31if "research" in task.lower():32next_agent = "researcher"33elif "write" in task.lower() or "create" in task.lower():34next_agent = "writer"35elif "review" in task.lower() or "analyze" in task.lower():36next_agent = "reviewer"37else:38next_agent = "coordinator"3940return {41"task": task,42"current_agent": next_agent,43"task_output": {},44"messages": messages + [{"supervisor": f"Routing to {next_agent}"}]45}4647def researcher_node(state: AgentState) -> AgentState:48"""Research worker that gathers information."""49# Perform research task50output = perform_research(state["task"])5152return {53"task": state["task"],54"current_agent": "researcher",55"task_output": output,56"messages": state["messages"] + [{"researcher": "Research complete"}]57}5859def writer_node(state: AgentState) -> AgentState:60"""Writer worker that creates content based on research."""61output = create_content(state["task"], state["task_output"])6263return {64"task": state["task"],65"current_agent": "writer",66"task_output": output,67"messages": state["messages"] + [{"writer": "Content created"}]68}6970def build_supervisor_graph():71"""Build the supervisor workflow graph."""72workflow = StateGraph(AgentState)7374# Add nodes75workflow.add_node("supervisor", supervisor_node)76workflow.add_node("researcher", researcher_node)77workflow.add_node("writer", writer_node)7879# Add edges80workflow.add_edge("supervisor", "researcher")81workflow.add_edge("researcher", "supervisor")82workflow.add_edge("supervisor", "writer")83workflow.add_edge("writer", "supervisor")8485# Set entry point86workflow.set_entry_point("supervisor")8788return workflow.compile()89```9091### AutoGen Supervisor9293Implement supervisor using GroupChat pattern:9495```python96from autogen import AssistantAgent, UserProxyAgent, GroupChat9798# Define specialized agents99researcher = AssistantAgent(100name="researcher",101system_message="""You are a research specialist.102Your goal is to gather accurate, comprehensive information103on topics assigned by the supervisor. Always cite sources104and note confidence levels.""",105llm_config=llm_config106)107108writer = AssistantAgent(109name="writer",110system_message="""You are a content creation specialist.111Your goal is to create well-structured content based on112research provided by the supervisor. Follow style guidelines113and ensure factual accuracy.""",114llm_config=llm_config115)116117# Define supervisor118supervisor = AssistantAgent(119name="supervisor",120system_message="""You are the project supervisor.121Your goal is to coordinate researchers and writers to122complete tasks efficiently.123124Process:1251. Break down the task into research and writing phases1262. Route to appropriate specialists1273. Synthesize results into final output1284. Ensure quality before completing""",129llm_config=llm_config130)131132# Configure group chat133group_chat = GroupChat(134agents=[supervisor, researcher, writer],135messages=[],136max_round=20137)138139manager = GroupChatManager(140groupchat=group_chat,141llm_config=llm_config142)143```144145## Swarm Pattern Implementation146147### LangGraph Swarms148149Implement peer-to-peer handoffs:150151```python152def create_agent(name, system_prompt, tools):153"""Create an agent node for the swarm."""154155def agent_node(state):156# Process current state with agent157response = invoke_agent(name, system_prompt, state["input"], tools)158159# Check for handoff160if "handoff" in response:161return {"next_agent": response["handoff"], "output": response["output"]}162else:163return {"next_agent": END, "output": response["output"]}164165return agent_node166167def build_swarm():168"""Build a peer-to-peer agent swarm."""169workflow = StateGraph(State)170171# Create agents172triage = create_agent("triage", TRIAGE_PROMPT, [search, read])173research = create_agent("research", RESEARCH_PROMPT, [search, browse, read])174analysis = create_agent("analysis", ANALYSIS_PROMPT, [calculate, compare])175writing = create_agent("writing", WRITING_PROMPT, [write, edit])176177# Add to graph178workflow.add_node("triage", triage)179workflow.add_node("research", research)180workflow.add_node("analysis", analysis)181workflow.add_node("writing", writing)182183# Define handoff edges184workflow.add_edge("triage", "research")185workflow.add_edge("triage", "analysis")186workflow.add_edge("research", "writing")187workflow.add_edge("analysis", "writing")188189workflow.set_entry_point("triage")190191return workflow.compile()192```193194## Hierarchical Pattern Implementation195196### CrewAI-Style Hierarchy197198```python199class ManagerAgent:200def __init__(self, name, system_prompt, llm):201self.name = name202self.system_prompt = system_prompt203self.llm = llm204self.workers = []205206def add_worker(self, worker):207"""Add a worker agent to the team."""208self.workers.append(worker)209210def delegate(self, task):211"""212Analyze task and delegate to appropriate worker.213214Returns work assignment and expected output format.215"""216# Analyze task requirements217requirements = analyze_task_requirements(task)218219# Select best worker220best_worker = select_worker(self.workers, requirements)221222# Create assignment223assignment = {224"worker": best_worker.name,225"task": task,226"context": self.get_relevant_context(task),227"output_format": requirements.output_format,228"deadline": requirements.deadline229}230231return assignment232233def review_output(self, worker_output, requirements):234"""235Review worker output against requirements.236237Returns approval or revision request.238"""239quality_score = assess_quality(worker_output, requirements)240241if quality_score >= requirements.threshold:242return {"status": "approved", "output": worker_output}243else:244return {245"status": "revision_requested",246"feedback": generate_feedback(worker_output, requirements),247"revise_worker": requirements.revise_worker248}249```250251## Context Isolation Patterns252253### Full Context Delegation254255```python256def delegate_with_full_context(planner_state, subagent):257"""258Pass entire planner context to subagent.259260Use for complex tasks requiring complete understanding.261"""262return {263"context": planner_state,264"subagent": subagent,265"isolation_mode": "full"266}267```268269### Instruction Passing270271```python272def delegate_with_instructions(task_spec, subagent):273"""274Pass only instructions to subagent.275276Use for simple, well-defined subtasks.277"""278return {279"instructions": {280"objective": task_spec.objective,281"constraints": task_spec.constraints,282"inputs": task_spec.inputs,283"outputs": task_spec.output_schema284},285"subagent": subagent,286"isolation_mode": "minimal"287}288```289290### File System Coordination291292```python293class FileSystemCoordination:294def __init__(self, workspace_path):295self.workspace = workspace_path296297def write_shared_state(self, key, value):298"""Write state accessible to all agents."""299path = f"{self.workspace}/{key}.json"300with open(path, 'w') as f:301json.dump(value, f)302return path303304def read_shared_state(self, key):305"""Read state written by any agent."""306path = f"{self.workspace}/{key}.json"307with open(path, 'r') as f:308return json.load(f)309310def acquire_lock(self, resource, agent_id):311"""Prevent concurrent access to shared resources."""312lock_path = f"{self.workspace}/locks/{resource}.lock"313if os.path.exists(lock_path):314return False315with open(lock_path, 'w') as f:316f.write(agent_id)317return True318```319320## Consensus Mechanisms321322### Weighted Voting323324```python325def weighted_consensus(agent_outputs, weights):326"""327Calculate weighted consensus from agent outputs.328329Weight = verbalized_confidence * domain_expertise330"""331weighted_sum = sum(332output.vote * weights[output.agent_id]333for output in agent_outputs334)335total_weight = sum(weights[output.agent_id] for output in agent_outputs)336337return weighted_sum / total_weight338```339340### Debate Protocol341342```python343class DebateProtocol:344def __init__(self, agents, max_rounds=5):345self.agents = agents346self.max_rounds = max_rounds347self.history = []348349def run_debate(self, topic):350"""Execute structured debate on topic."""351# Initial statements352statements = {agent.name: agent.initial_statement(topic)353for agent in self.agents}354355for round_num in range(self.max_rounds):356# Generate critiques357critiques = {}358for agent in self.agents:359critiques[agent.name] = agent.critique(360topic,361statements,362exclude=[agent.name]363)364365# Update statements with critique integration366for agent in self.agents:367statements[agent.name] = agent.integrate_critique(368statements[agent.name],369critiques370)371372# Check for convergence373if self.check_convergence(statements):374break375376# Final evaluation377return self.evaluate_final(statements)378```379380## Failure Recovery381382### Circuit Breaker383384```python385class AgentCircuitBreaker:386def __init__(self, failure_threshold=3, timeout_seconds=60):387self.failure_count = {}388self.failure_threshold = failure_threshold389self.timeout_seconds = timeout_seconds390391def call(self, agent, task):392"""Execute agent task with circuit breaker protection."""393if self.is_open(agent.name):394raise CircuitBreakerOpen(f"Agent {agent.name} temporarily unavailable")395396try:397result = agent.execute(task)398self.record_success(agent.name)399return result400except Exception as e:401self.record_failure(agent.name)402if self.failure_count[agent.name] >= self.failure_threshold:403self.open_circuit(agent.name)404raise405```406407### Checkpoint and Resume408409```python410class CheckpointManager:411def __init__(self, checkpoint_dir):412self.checkpoint_dir = checkpoint_dir413os.makedirs(checkpoint_dir, exist_ok=True)414415def save_checkpoint(self, workflow_id, step, state):416"""Save workflow state for potential resume."""417checkpoint = {418"workflow_id": workflow_id,419"step": step,420"state": state,421"timestamp": time.time()422}423path = f"{self.checkpoint_dir}/{workflow_id}.json"424with open(path, 'w') as f:425json.dump(checkpoint, f)426427def load_checkpoint(self, workflow_id):428"""Load last saved checkpoint for workflow."""429path = f"{self.checkpoint_dir}/{workflow_id}.json"430with open(path, 'r') as f:431return json.load(f)432```433434