my-gradio-app / agents /README.md
Nguyen Trong Lap
Recreate history without binary blobs
eeb0f9c

A newer version of the Gradio SDK is available: 6.1.0

Upgrade

Agents Package Structure πŸ—οΈ

πŸ“ Directory Structure

agents/
β”œβ”€β”€ README.md                    # This file
β”œβ”€β”€ AGENT_ARCHITECTURE.md        # Full architecture documentation
β”‚
β”œβ”€β”€ core/                        # Core infrastructure
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ router.py               # OpenAI function calling router
β”‚   β”œβ”€β”€ coordinator.py          # Multi-agent coordinator
β”‚   └── base_agent.py           # Base class for all agents
β”‚
└── specialized/                 # Domain-specific agents
    β”œβ”€β”€ __init__.py
    β”œβ”€β”€ nutrition_agent.py      # Nutrition & diet advice
    β”œβ”€β”€ exercise_agent.py       # Exercise & fitness plans
    β”œβ”€β”€ symptom_agent.py        # Symptom assessment
    β”œβ”€β”€ mental_health_agent.py  # Mental health support
    └── general_health_agent.py # General health queries

🎯 Purpose of Each Component

Core Components (core/)

1. router.py

  • Purpose: Routes user queries to appropriate agents
  • Technology: OpenAI Function Calling
  • Key Features:
    • Context-aware routing (10 exchanges history)
    • Last agent tracking
    • Improved accuracy: 80-85% for ambiguous questions

2. coordinator.py

  • Purpose: Orchestrates multiple agents with shared memory
  • Key Features:
    • Shared conversation memory
    • Agent handoffs
    • Multi-agent collaboration
    • Memory persistence across turns

3. base_agent.py

  • Purpose: Base class providing common functionality
  • Key Features:
    • Memory access helpers
    • Agent handoff detection**
    • Agent-to-agent communication
    • Context awareness methods
    • Handoff detection logic
    • Context awareness methods
    • User data extraction

Specialized Agents (specialized/)

1. nutrition_agent.py

  • Domain: Nutrition, diet, BMI, calories
  • Capabilities:
    • Calculate BMI and calorie needs
    • Generate meal plans
    • Provide dietary advice
    • Handle weight loss/gain goals

2. exercise_agent.py

  • Domain: Exercise, fitness, workout plans
  • Capabilities:
    • Create personalized workout plans
    • Suggest exercises based on fitness level
    • Provide form guidance
    • Track progress

3. symptom_agent.py

  • Domain: Symptom assessment, health concerns
  • Capabilities:
    • OPQRST symptom assessment
    • Red flag detection
    • Triage recommendations
    • Medical advice (when to see doctor)

4. mental_health_agent.py

  • Domain: Mental health, stress, anxiety
  • Capabilities:
    • Stress assessment
    • Coping strategies
    • Mindfulness techniques
    • Crisis detection

5. general_health_agent.py

  • Domain: General health queries
  • Capabilities:
    • Answer general health questions
    • Provide health tips
    • Fallback for unclear queries

πŸ”„ How It Works

1. User Query Flow

User Input
    ↓
helpers.py (chat_logic)
    ↓
AgentCoordinator
    ↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Shared Memory          β”‚
β”‚  - User Profile         β”‚
β”‚  - Conversation State   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
    ↓
Router (Function Calling)
    ↓
Specialized Agent(s)
    ↓
Response (with memory)

2. Import Structure

# From outside agents package
from agents import (
    route_to_agent,          # Router function
    AgentCoordinator,        # Coordinator class
    BaseAgent,               # Base agent class
    NutritionAgent,          # Specialized agents
    get_agent                # Agent factory
)

# Within agents package
from agents.core import router, coordinator, base_agent
from agents.specialized import nutrition_agent, exercise_agent

πŸš€ Usage Examples

Example 1: Using Coordinator (Recommended)

from agents import AgentCoordinator

coordinator = AgentCoordinator()

# Handle query with memory
response = coordinator.handle_query(
    "TΓ΄i 25 tuα»•i, muα»‘n giαΊ£m cΓ’n",
    chat_history
)

# Memory persists!
response2 = coordinator.handle_query(
    "TΓ΄i nΓͺn Δƒn gΓ¬?",  # Knows age=25, goal=weight_loss
    chat_history
)

Example 2: Using Router Directly

from agents import route_to_agent, get_agent

# Route to agent
routing = route_to_agent("TΓ΄i muα»‘n giαΊ£m cΓ’n", chat_history)
# β†’ {'agent': 'nutrition_agent', 'parameters': {...}}

# Get agent instance
agent = get_agent(routing['agent'])

# Handle request
response = agent.handle(routing['parameters'], chat_history)

Example 3: Creating Custom Agent

from agents.core import BaseAgent

class MyCustomAgent(BaseAgent):
    def __init__(self, memory=None):
        super().__init__(memory)
        self.agent_name = 'my_custom_agent'
        self.system_prompt = "Your custom prompt..."
    
    def handle(self, parameters, chat_history=None):
        # Access shared memory
        user_profile = self.get_user_profile()
        
        # Your logic here
        response = self._generate_response(parameters)
        
        # Save to memory
        self.save_agent_data('key', 'value')
        
        return response

πŸ“Š Key Benefits of This Structure

βœ… Separation of Concerns

  • Core infrastructure separate from domain logic
  • Easy to maintain and test

βœ… Scalability

  • Add new agents without touching core
  • Easy to extend functionality

βœ… Reusability

  • BaseAgent provides common functionality
  • Coordinator handles all agents uniformly

βœ… Memory Management

  • Shared memory across all agents
  • No repeated questions
  • Full context awareness

βœ… Clean Imports

  • Clear import paths
  • No circular dependencies
  • Well-organized namespaces

πŸ”§ Adding a New Agent

Step 1: Create Agent File

# agents/specialized/my_agent.py
from agents.core import BaseAgent

class MyAgent(BaseAgent):
    def __init__(self, memory=None):
        super().__init__(memory)
        self.agent_name = 'my_agent'
        self.system_prompt = "..."
    
    def handle(self, parameters, chat_history=None):
        # Your implementation
        return "Response"

Step 2: Register in specialized/__init__.py

from .my_agent import MyAgent

AGENTS = {
    # ... existing agents
    "my_agent": MyAgent,
}

Step 3: Register in core/router.py

AVAILABLE_FUNCTIONS = [
    # ... existing functions
    {
        "name": "my_agent",
        "description": "Your agent description",
        "parameters": {...}
    }
]

Step 4: Add to Coordinator

# agents/core/coordinator.py
from agents.specialized.my_agent import MyAgent

self.agents = {
    # ... existing agents
    'my_agent': MyAgent()
}

πŸ“š Documentation

  • Full Architecture: See AGENT_ARCHITECTURE.md
  • Implementation Guide: See PART1_IMPLEMENTATION.md (if exists)
  • API Reference: See individual agent files

🎯 Best Practices

  1. Always extend BaseAgent for new agents (unless you have a good reason not to)
  2. Use coordinator for production (enables memory & multi-agent)
  3. Keep agents focused - One domain per agent
  4. Document your prompts - Clear system prompts are crucial
  5. Test thoroughly - Test routing, memory, and handoffs

Last Updated: Oct 11, 2025
Version: 2.0 (with Memory & Coordination)