Multi-Agent Systems

Build sophisticated systems where multiple agents collaborate, compete, or work in parallel to solve complex problems.

Agents as First-Class Citizens

In AA Kit, agents can use other agents as tools. This enables natural hierarchies, delegation patterns, and complex workflows that mirror real-world team dynamics.

Why Multi-Agent Systems?

Specialization

Each agent can be optimized for specific tasks with tailored instructions, models, and tools.

Parallelization

Multiple agents can work simultaneously on different aspects of a problem.

Resilience

If one agent fails, others can compensate. Different models provide fallback options.

Implementation Examples

Agent Collaboration

python
from aakit import Agent

# Create specialized agents
researcher = Agent(
    name="researcher",
    instruction="You excel at finding and analyzing information",
    model="gpt-4",
    tools=[web_search, extract_data, analyze_trends]
)

writer = Agent(
    name="writer", 
    instruction="You create clear, engaging content",
    model="claude-3-opus",
    tools=[format_markdown, check_grammar]
)

editor = Agent(
    name="editor",
    instruction="You coordinate research and writing tasks",
    model="gpt-4",
    tools=[researcher, writer]  # Agents as tools!
)

# The editor delegates to specialists
result = await editor.chat(
    "Create a comprehensive report on AI trends in healthcare"
)
# Editor automatically:
# 1. Asks researcher to gather data
# 2. Passes findings to writer
# 3. Reviews and finalizes the report

Parallel Agent Execution

python
from aakit import Agent, parallel_chat

# Create multiple agents for different tasks
agents = {
    "market_analyst": Agent(
        name="market_analyst",
        instruction="You analyze market data",
        model="gpt-4"
    ),
    "tech_reviewer": Agent(
        name="tech_reviewer", 
        instruction="You evaluate technical feasibility",
        model="gpt-4"
    ),
    "risk_assessor": Agent(
        name="risk_assessor",
        instruction="You identify potential risks",
        model="gpt-3.5-turbo"
    )
}

# Execute all agents in parallel
results = await parallel_chat(
    agents=agents,
    message="Evaluate launching a new AI product",
    timeout=30
)

# Aggregate results
for agent_name, response in results.items():
    print(f"{agent_name}: {response}")

Agent Pipeline

python
from aakit import Agent, Pipeline

# Create a processing pipeline
pipeline = Pipeline([
    Agent(
        name="translator",
        instruction="You translate text to English",
        model="gpt-3.5-turbo"
    ),
    Agent(
        name="summarizer",
        instruction="You create concise summaries",
        model="gpt-4"
    ),
    Agent(
        name="categorizer",
        instruction="You categorize content by topic",
        model="gpt-3.5-turbo"
    )
])

# Process through the pipeline
result = await pipeline.process(
    "Un article français sur l'intelligence artificielle..."
)
# Output: Categorized English summary

Hierarchical Agent Teams

python
from aakit import Agent, Team

# Create a hierarchical team structure
manager = Agent(
    name="project_manager",
    instruction="You manage AI development projects",
    model="gpt-4"
)

team = Team(
    manager=manager,
    members=[
        Agent("frontend_dev", "You build user interfaces", "gpt-4"),
        Agent("backend_dev", "You build APIs and services", "gpt-4"), 
        Agent("ml_engineer", "You develop ML models", "gpt-4"),
        Agent("qa_tester", "You ensure quality", "gpt-3.5-turbo")
    ],
    coordination_strategy="manager_led"  # or "consensus", "round_robin"
)

# Manager coordinates the team
result = await team.execute_project(
    "Build a chatbot application with sentiment analysis"
)

Agent Negotiation

python
from aakit import Agent, Negotiation

# Create agents with different objectives
buyer = Agent(
    name="buyer",
    instruction="You negotiate to minimize cost",
    model="gpt-4",
    context={"budget": 10000, "requirements": ["fast", "reliable"]}
)

seller = Agent(
    name="seller",
    instruction="You negotiate to maximize profit",
    model="gpt-4",
    context={"min_price": 8000, "features": ["fast", "reliable", "support"]}
)

# Set up negotiation
negotiation = Negotiation(
    agents=[buyer, seller],
    max_rounds=5,
    success_criteria="agreement_reached"
)

# Agents negotiate automatically
result = await negotiation.start()
print(f"Final agreement: {result.agreement}")
print(f"Rounds taken: {result.rounds}")

Dynamic Agent Spawning

python
from aakit import Agent, AgentPool

# Create an agent pool for scaling
pool = AgentPool(
    template=Agent(
        name="worker",
        instruction="You process data tasks",
        model="gpt-3.5-turbo"
    ),
    min_agents=2,
    max_agents=10,
    scale_factor="queue_length"  # Auto-scale based on workload
)

# Submit tasks - agents are spawned as needed
tasks = ["task1", "task2", "task3", ...]
results = await pool.process_batch(tasks)

# Pool automatically:
# - Spawns new agents when load increases
# - Terminates idle agents
# - Balances work across agents

Common Patterns

Delegation Pattern

One agent coordinates others

Manager → [Specialist 1, Specialist 2, Specialist 3]

Use case: Complex projects requiring multiple skills

Pipeline Pattern

Sequential processing through agents

Input → Agent 1 → Agent 2 → Agent 3 → Output

Use case: Multi-step transformations

Consensus Pattern

Multiple agents vote on decisions

Agents → Vote → Consensus → Decision

Use case: Critical decisions requiring validation

Competition Pattern

Agents compete to provide best solution

Problem → [Agent 1, Agent 2, Agent 3] → Best Solution

Use case: Optimization problems

Communication Strategies

StrategyDescriptionBest For
Direct MessageAgents communicate directly via tool callsSimple delegation
Shared MemoryAgents read/write to common memory storeCollaborative work
Message QueueAsync communication via queuesHigh-volume processing
Event StreamAgents subscribe to event topicsReal-time systems

Advanced Architectures

Swarm Intelligence

Multiple simple agents work together to solve complex problems:

swarm = AgentSwarm(size=50, behavior="emergent")
solution = await swarm.optimize(problem)

Recursive Agent Networks

Agents that can spawn sub-agents dynamically:

meta_agent = Agent(name="meta", can_spawn=True)
result = await meta_agent.solve_recursively(task)

Best Practices

Design Principles

  • • Keep agents focused on specific roles
  • • Use appropriate models for each task
  • • Design clear communication protocols
  • • Implement proper error handling
  • • Monitor inter-agent performance

Common Pitfalls

  • • Over-engineering simple problems
  • • Creating circular dependencies
  • • Ignoring rate limits with parallel agents
  • • Not handling partial failures
  • • Excessive inter-agent communication

Real-World Examples

Customer Support System

Triage Agent
Technical Agent
Billing Agent
Escalation Agent

Triage agent analyzes customer issues and routes to specialized agents based on the problem type.

Content Creation Pipeline

Research
Writing
Editing
SEO

Sequential pipeline where each agent enhances the content before passing it to the next stage.

Next Steps

Learn how to customize agent reasoning patterns for complex decision-making.

Continue to Custom Reasoning →