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

A newer version of the Gradio SDK is available: 6.1.0

Upgrade

Agents vs Modules - Hiểu Sự Khác Biệt 🎯

TL;DR

agents/  = "Não" (Conversation + Orchestration)
modules/ = "Tay chân" (Calculations + Business Logic)

📊 So Sánh Nhanh

Aspect agents/ modules/
Mục đích Nói chuyện với user Tính toán, xử lý data
Công nghệ OpenAI LLM Pure Python
Input Natural language Structured data (dict, list)
Output Conversational text Data (numbers, dict, list)
Ví dụ "Bạn bao nhiêu tuổi?" calculate_bmi(70, 1.75)
Test Integration test Unit test

🧠 agents/ - Conversation Layer

Mục Đích

Hiểu user muốn gì, hỏi thông tin, format response đẹp

Khi Nào Dùng

  • ✅ Cần hỏi user thêm thông tin
  • ✅ Cần hiểu ngữ cảnh (context)
  • ✅ Cần format response theo cách dễ đọc
  • ✅ Cần handle conversation flow

Ví Dụ

# agents/nutrition_agent.py

class NutritionAgent:
    def handle(self, parameters, chat_history):
        # 1. Hiểu user muốn gì
        user_query = parameters['user_query']
        
        # 2. Extract data từ conversation
        user_data = self._extract_from_history(chat_history)
        
        # 3. Check xem đủ data chưa
        if not user_data.get('weight'):
            return "Bạn nặng bao nhiêu kg?" # ← Hỏi user
        
        # 4. Gọi module để tính toán
        bmi = self.advisor.calculate_bmi(
            user_data['weight'], 
            user_data['height']
        )
        
        # 5. Format response đẹp
        return f"""📊 **Phân tích BMI**
        
BMI của bạn: {bmi}
Đánh giá: Bình thường

Bạn có muốn tư vấn thêm về chế độ ăn không? 😊"""

Agents làm gì:

  • 🗣️ Nói chuyện với user
  • 🎯 Hiểu intent
  • 📝 Hỏi thông tin còn thiếu
  • 🎨 Format response đẹp
  • 🔗 Gọi modules khi cần tính toán

🔧 modules/ - Business Logic Layer

Mục Đích

Tính toán, xử lý data, business rules - KHÔNG nói chuyện

Khi Nào Dùng

  • ✅ Cần tính toán (BMI, calories, etc.)
  • ✅ Cần generate data (meal plan, workout plan)
  • ✅ Cần validate data
  • ✅ Cần apply business rules

Ví Dụ

# modules/nutrition.py

class NutritionAdvisor:
    def calculate_bmi(self, weight, height):
        """
        Calculate BMI
        
        Args:
            weight (float): Weight in kg
            height (float): Height in meters
        
        Returns:
            float: BMI value
        """
        if height <= 0:
            raise ValueError("Height must be positive")
        
        return round(weight / (height ** 2), 1)
    
    def calculate_calories(self, user_data):
        """Calculate daily calorie needs"""
        # Complex calculation
        bmr = self._calculate_bmr(user_data)
        activity_factor = self._get_activity_factor(user_data['activity_level'])
        
        return bmr * activity_factor
    
    def generate_meal_plan(self, user_data):
        """Generate personalized meal plan"""
        calories = self.calculate_calories(user_data)
        
        # Business logic to create meal plan
        return {
            'breakfast': [...],
            'lunch': [...],
            'dinner': [...]
        }

Modules làm gì:

  • 🧮 Tính toán (BMI, calories, macros)
  • 📋 Generate plans (meal, workout)
  • ✅ Validate data
  • 📏 Apply business rules
  • 🔄 Reusable functions

🎯 Workflow: User Muốn Giảm Cân

Flow Hoàn Chỉnh

User: "Tôi muốn giảm cân"
    ↓
[agents/nutrition_agent.py]
    → Hiểu: User muốn nutrition advice
    → Check: Có đủ data chưa? (tuổi, cân nặng, chiều cao)
    → Không đủ → Hỏi: "Bạn bao nhiêu tuổi, nặng bao nhiêu?"
    ↓
User: "25 tuổi, 70kg, 175cm"
    ↓
[agents/nutrition_agent.py]
    → Extract: age=25, weight=70, height=1.75
    → Gọi modules để tính toán:
    ↓
[modules/nutrition.py]
    → calculate_bmi(70, 1.75) = 22.9
    → calculate_calories({age: 25, weight: 70, ...}) = 1800
    → generate_meal_plan(...) = {breakfast: [...], ...}
    ↓
[agents/nutrition_agent.py]
    → Nhận kết quả từ modules
    → Format đẹp:
    ↓
Response: "📊 BMI: 22.9 (Bình thường)
          🎯 Calo: 1800 kcal/ngày
          🍽️ Thực đơn: [...]"

💡 Ví Dụ Thực Tế

Scenario: Thêm Feature "Meal Timing"

❌ SAI - Tất cả trong agents

# agents/nutrition_agent.py

class NutritionAgent:
    def handle(self, parameters, chat_history):
        # ❌ Tính toán trong agent - SAI!
        if workout_time == 'morning':
            breakfast = '7:00 AM'
            pre_workout = '6:00 AM'
        else:
            breakfast = '8:00 AM'
            pre_workout = '5:00 PM'
        
        return f"Ăn sáng: {breakfast}"

Vấn đề:

  • Không test được logic riêng
  • Khó maintain
  • Không reuse được

✅ ĐÚNG - Tách biệt agents và modules

# modules/nutrition.py

class NutritionAdvisor:
    def optimize_meal_timing(self, user_data):
        """Calculate optimal meal times"""
        workout_time = user_data['workout_time']
        
        if workout_time == 'morning':
            return {
                'breakfast': '7:00 AM',
                'pre_workout': '6:00 AM',
                'lunch': '12:00 PM',
                'dinner': '7:00 PM'
            }
        else:
            return {
                'breakfast': '8:00 AM',
                'lunch': '12:00 PM',
                'pre_workout': '5:00 PM',
                'dinner': '8:00 PM'
            }
# agents/nutrition_agent.py

class NutritionAgent:
    def handle(self, parameters, chat_history):
        # Extract data
        user_data = self._extract_data(chat_history)
        
        # Gọi module
        meal_timing = self.advisor.optimize_meal_timing(user_data)
        
        # Format response
        return f"""🕐 **Lịch Ăn Tối Ưu**
        
- Sáng: {meal_timing['breakfast']}
- Trưa: {meal_timing['lunch']}
- Trước tập: {meal_timing['pre_workout']}
- Tối: {meal_timing['dinner']}

Bạn có muốn tư vấn thêm về món ăn không? 😊"""

Lợi ích:

  • ✅ Test được optimize_meal_timing() độc lập
  • ✅ Dễ maintain
  • ✅ Có thể reuse ở agent khác
  • ✅ Clear separation of concerns

🔑 Nguyên Tắc Vàng

Khi code, tự hỏi:

"Đây là conversation hay calculation?"

  • Conversationagents/

    • Hỏi user
    • Hiểu ngữ cảnh
    • Format response
  • Calculationmodules/

    • Tính toán
    • Generate data
    • Business rules

📝 Checklist Nhanh

Thêm Feature Mới

1. Modules (modules/):

# Thêm function tính toán
def calculate_something(user_data):
    # Pure Python logic
    return result

2. Agents (agents/):

# Sử dụng function từ modules
def handle(self, parameters, chat_history):
    # 1. Extract data
    # 2. Call module
    result = self.module.calculate_something(data)
    # 3. Format response
    return f"Kết quả: {result}"

3. Test:

# Test module (unit test)
def test_calculate_something():
    result = calculate_something({'age': 25})
    assert result == expected_value

# Test agent (integration test)
def test_agent_flow():
    response = agent.handle(...)
    assert "Kết quả" in response

❓ FAQ

Q: Tôi nên code ở đâu? A:

  • Tính toán, logic → modules/
  • Nói chuyện, hỏi user → agents/

Q: Module có thể gọi agent không? A: KHÔNG! Chỉ agent gọi module, không ngược lại.

Q: Agent có thể gọi agent khác không? A: Không trực tiếp. Dùng router để chuyển.

Q: Khi nào cần update cả 2? A: Khi thêm feature mới:

  1. Thêm logic vào modules/
  2. Thêm conversation vào agents/

🎓 Tóm Tắt

┌─────────────────────────────────────┐
│  User: "Tôi muốn giảm cân"          │
└──────────────┬──────────────────────┘
               │
┌──────────────▼──────────────────────┐
│  agents/nutrition_agent.py          │
│  - Hiểu user muốn gì                │
│  - Hỏi: tuổi, cân nặng, chiều cao  │
│  - Format response đẹp              │
└──────────────┬──────────────────────┘
               │ calls
┌──────────────▼──────────────────────┐
│  modules/nutrition.py               │
│  - calculate_bmi(70, 1.75)          │
│  - calculate_calories(...)          │
│  - generate_meal_plan(...)          │
└──────────────┬──────────────────────┘
               │ returns data
┌──────────────▼──────────────────────┐
│  agents/nutrition_agent.py          │
│  - Format: "BMI: 22.9, Calo: 1800" │
└──────────────┬──────────────────────┘
               │
┌──────────────▼──────────────────────┐
│  User: "📊 BMI: 22.9..."            │
└─────────────────────────────────────┘

Remember:

  • agents/ = Conversation (Não)
  • modules/ = Calculation (Tay chân)
  • Agent gọi module, không ngược lại
  • Tách biệt rõ ràng = Code dễ maintain

That's it! Simple as that. 🚀