Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
466 changes: 94 additions & 372 deletions README.md

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions examples/dynamic-agents/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Dynamic agents workspace directory
workspace/
175 changes: 175 additions & 0 deletions examples/dynamic-agents/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
# Dynamic Agents Examples

This directory contains examples demonstrating the dynamic agent creation capability in FastAgent. Dynamic agents can be created at runtime based on task analysis, allowing for adaptive team composition.

## Features

- **Runtime Agent Creation**: Create specialized agents on-the-fly
- **Parallel Execution**: Multiple agents can work simultaneously
- **Lifecycle Management**: Create, use, and terminate agents as needed
- **Tool Access**: Dynamic agents can use MCP servers and tools
- **Tree Display**: Visual representation of agent hierarchy

## Available Examples

### 1. Project Manager (`project_manager.py`)
Demonstrates a project manager that creates and coordinates development teams for software projects.

```bash
# Run the full demo
python project_manager.py

# Interactive mode
python project_manager.py interactive
```

### 2. Simple Demo (`simple_demo.py`)
Basic demonstration of dynamic agent concepts with easy-to-understand examples.

```bash
# Run all simple examples
python simple_demo.py

# Run just the basic example
python simple_demo.py basic

# Run just the delegation example
python simple_demo.py delegation
```

### 3. Code Review Demo (`code_review_demo.py`)
Shows specialized code review teams that analyze code from different perspectives.

```bash
# Run all review examples
python code_review_demo.py

# Run just security-focused review
python code_review_demo.py security

# Run comprehensive review
python code_review_demo.py comprehensive
```

### 4. Interactive Demo (`interactive_demo.py`)
Interactive playground for experimenting with dynamic agents.

```bash
# Interactive mode
python interactive_demo.py

# Guided scenarios
python interactive_demo.py guided

# Quick demonstration
python interactive_demo.py quick
```

### 5. Original Example (`example.py`)
The original comprehensive example with multiple scenarios in one file.

```bash
# Full demo
python example.py

# Simple example
python example.py simple

# Interactive mode
python example.py interactive
```

## How It Works

### 1. Enable Dynamic Agents
```python
@fast.agent(
name="project_manager",
dynamic_agents=True, # Enable dynamic agent creation
max_dynamic_agents=5, # Limit to 5 agents
servers=["filesystem", "fetch"] # MCP servers available to dynamic agents
)
```

### 2. Create Dynamic Agents
The agent uses tools to create specialists:
```python
# Creates a frontend developer agent
dynamic_agent_create({
"name": "frontend_dev",
"instruction": "You are a React/TypeScript expert...",
"servers": ["filesystem"],
"tools": {"filesystem": ["read*", "write*"]}
})
```

### 3. Delegate Tasks
```python
# Send task to specific agent
dynamic_agent_send({
"agent_id": "frontend_dev_abc123",
"message": "Create the main App component"
})

# Broadcast to multiple agents (parallel execution)
dynamic_agent_broadcast({
"message": "Review this code for issues",
"agent_ids": ["security_expert", "performance_expert"],
"parallel": true
})
```

## Available Tools

When `dynamic_agents=True`, the agent gets these tools:

- **dynamic_agent_create**: Create new specialized agents
- **dynamic_agent_send**: Send messages to specific agents
- **dynamic_agent_broadcast**: Send messages to multiple agents in parallel
- **dynamic_agent_list**: List all active dynamic agents
- **dynamic_agent_terminate**: Clean up agents when done

## Use Cases

### 1. Development Teams
- Frontend/Backend/Database specialists
- Code reviewers with different focuses
- DevOps and QA specialists

### 2. Content Creation
- Writers, editors, fact-checkers
- Specialized content for different audiences

### 3. Data Analysis
- Data collectors, cleaners, analyzers
- Visualization and reporting specialists

### 4. Research Projects
- Domain experts for different topics
- Fact-checkers and synthesizers

## Architecture

Dynamic agents follow the same patterns as parallel agents:
- **Same Process**: All run in the same Python process
- **Shared Context**: Use the same MCP connections
- **Separate LLM Contexts**: Each has its own conversation history
- **Parallel Execution**: Use `asyncio.gather()` like ParallelAgent
- **Tree Display**: Extend parallel agent display patterns

## Configuration

Dynamic agents can only use MCP servers defined in `fastagent.config.yaml`. They cannot create new MCP connections, but can be configured with:

- **Different instruction/role**
- **Subset of MCP servers**
- **Filtered tools from those servers**
- **Different models**
- **Own conversation context**

## Limitations

- Maximum number of agents enforced
- Can only use pre-configured MCP servers
- Exist only during parent agent's lifetime
- No persistence across sessions
155 changes: 155 additions & 0 deletions examples/dynamic-agents/code_review_demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
"""
Code Review Team Dynamic Agents Example

This example demonstrates creating specialized code review teams that can analyze
code from different perspectives simultaneously.
"""

import asyncio

from mcp_agent.core.fastagent import FastAgent

# Create the application
fast = FastAgent("Code Review Team Demo")


# Sample problematic code for review
SAMPLE_CODE = '''
import hashlib
import sqlite3
import os

def authenticate_user(username, password):
conn = sqlite3.connect('users.db')
cursor = conn.cursor()
query = f"SELECT * FROM users WHERE username='{username}'"
cursor.execute(query)
user = cursor.fetchone()

if user and user[2] == password:
return True
return False

def create_user(username, password):
conn = sqlite3.connect('users.db')
cursor = conn.cursor()
cursor.execute(f"INSERT INTO users VALUES ('{username}', '{password}')")
conn.commit()
conn.close()

def process_large_dataset(data):
results = []
for item in data:
# Inefficient nested loops
for i in range(len(data)):
for j in range(len(data)):
if data[i] == data[j]:
results.append(item)
return results

class UserManager:
def __init__(self):
self.users = []

def add_user(self, user):
self.users.append(user)

def find_user(self, username):
for user in self.users:
if user.username == username:
return user
'''


@fast.agent(
name="review_coordinator",
instruction="""You are a code review coordinator that creates specialized review teams.

When given code to review, you should:
1. Create different types of reviewers with specific expertise
2. Have them analyze the code in parallel from their perspectives
3. Consolidate their findings into a comprehensive report

Types of reviewers you can create:
- Security Reviewer: Focuses on vulnerabilities, injection attacks, authentication
- Performance Reviewer: Looks for optimization opportunities, bottlenecks
- Code Quality Reviewer: Examines maintainability, readability, best practices
- Architecture Reviewer: Analyzes design patterns, structure, scalability

Use dynamic agent tools to create and coordinate the review team.""",
servers=["filesystem"],
dynamic_agents=True,
max_dynamic_agents=6,
model="haiku"
)
async def main():
async with fast.run() as agent:
print("=== Code Review Team Demo ===\n")

await agent.review_coordinator(f"""
I have a Python codebase that needs a comprehensive review.
Create a specialized code review team with different focuses:
1. Security reviewer for vulnerability assessment
2. Performance reviewer for optimization opportunities
3. Code quality reviewer for maintainability
4. Architecture reviewer for design patterns

Then have them review this sample code in parallel and provide a consolidated report:

```python
{SAMPLE_CODE}
```

Each reviewer should focus on their specialty and provide specific recommendations.
""")


@fast.agent(
name="security_focused_reviewer",
instruction="""You are a security-focused code reviewer that creates specialized
security analysis teams.

Create agents that focus on different security aspects:
- Input validation specialist
- Authentication security expert
- Database security analyst
- General security vulnerability scanner""",
servers=["filesystem"],
dynamic_agents=True,
max_dynamic_agents=4,
model="haiku"
)
async def security_review_example():
async with fast.run() as agent:
print("\n=== Security-Focused Review Example ===\n")

await agent.security_focused_reviewer(f"""
Create a specialized security review team to analyze this code for vulnerabilities:

```python
{SAMPLE_CODE}
```

Create different security specialists and have them each focus on their area of expertise.
Provide a detailed security assessment with risk levels and remediation steps.
""")


async def run_all_reviews():
"""Run all code review examples."""
print("Running Code Review Examples...\n")

await main()
print("\n" + "="*60 + "\n")
await security_review_example()


if __name__ == "__main__":
import sys

if len(sys.argv) > 1 and sys.argv[1] == "security":
asyncio.run(security_review_example())
elif len(sys.argv) > 1 and sys.argv[1] == "comprehensive":
asyncio.run(main())
else:
asyncio.run(run_all_reviews())
Loading
Loading