AI & Machine Learning Architecture DevOps

คู่มือ OpenClaw Subagent

คู่มือฉบับสมบูรณ์สำหรับระบบอาเจนต์อัจฉริยะแบบกระจายที่สามารถปรับแต่งได้ตามความต้องการ

บทนำ (Introduction)

OpenClaw Subagent เป็นระบบอาเจนต์อัจฉริยะแบบกระจายที่ออกแบบมาเพื่อจัดการงานที่ซับซ้อนโดยการแบ่งงานออกเป็นงานย่อยและส่งมอบให้กับอาเจนต์หลายตัวประมวลผลพร้อมกันหรือตามลำดับ ระบบเรามุ่งมั่นที่จะให้ความยืดหยุ่น สเกลได้ และสามารถปรับแต่งได้ตามความต้องการของผู้ใช้งาน

💡 ทำไมต้อง OpenClaw Subagent?

  • ประสิทธิภาพสูง: ประมวลผลงานหลายชิ้นพร้อมกันผ่าน parallel execution
  • ⚙️ ยืดหยุ่น: สามารถกำหนด role และ task ให้กับแต่ละ subagent ได้
  • 🔄 Workflow หลากหลาย: รองรับทั้ง sequential และ parallel workflow
  • 🛠️ Open Source: โค้ดเปิด ชุมชนที่แข็งแรง และเอกสารที่ครบถ้วน
  • 📈 สเกลได้: สามารถเพิ่ม subagent ได้ตามความต้องการของ workload

ในคู่มือนี้ เราจะพาคุณไปตั้งแต่แนวคิดพื้นฐานไปจนถึงการใช้งานขั้นสูงของ OpenClaw Subagent ทุกขั้นตอนจะมีตัวอย่างโค้ดและ diagram เพื่อช่วยให้เข้าใจได้ง่ายยิ่งขึ้น

ประวัติความเป็นมา

OpenClaw Subagent พัฒนาขึ้นเพื่อตอบโจทย์ความซับซ้อนของงาน AI และ automation ในยุคปัจจุบัน ที่ต้องการการทำงานร่วมกันระหว่างหลายระบบอย่างมีประสิทธิภาพ ตั้งแต่การวิเคราะห์ข้อมูล การเขียนแอปพลิเคชัน ไปจนถึงการจัดการโครงสร้างพื้นฐาน

เป้าหมายของคู่มือนี้

คู่มือนี้จะช่วยให้คุณ:

  • เข้าใจแนวคิดพื้นฐานของ OpenClaw Subagent
  • ตั้งค่าและใช้งานระบบได้อย่างถูกต้อง
  • ออกแบบ workflow ที่เหมาะสมกับงานของคุณ
  • เรียนรู้ best practices และ common patterns
  • แก้ไขปัญหาเบื้องต้นเมื่อเกิดข้อผิดพลาด

แนวคิดพื้นฐาน (Basic Concepts)

1. OpenClaw Architecture

สถาปัตยกรรมของ OpenClaw ประกอบด้วย Coordinator และหลาย Subagents ที่ทำงานร่วมกันแบบกระจาย (distributed) ซึ่งแต่ละส่วนมีบทบาทที่สำคัญต่อระบบโดยรวม

รูปที่ 1: สถาปัตยกรรมของ OpenClaw Subagent
Coordinator Task Planner Workflow Manager Researcher Web Scraping Data Mining Writer Content Gen Copywriting Analyst Data Analysis Pattern Rec Developer Code Generation Debugging
指挥
Coordinator (ผู้ประสานงาน)
เป็นศูนย์กลางที่จัดการทั้งระบบ รับผิดชอบในการแบ่งงาน กำหนดลำดับงาน และรวมผลลัพธ์จาก subagents ทั้งหมด
🔍
Researcher Agent (ตัววิจัย)
รับผิดชอบการค้นหาข้อมูลจากแหล่งต่างๆ ทั้ง web scraping, API calls, และ data mining เพื่อนำมาใช้ในการตัดสินใจ
📝
Writer Agent (ตัวเขียน)
สร้างเนื้อหาที่มีคุณภาพ เช่น blog posts, documentation, reports และสคริปต์ต่างๆ ด้วยภาษาไทยและภาษาอังกฤษ
📊
Analyst Agent (ตัววิเคราะห์)
วิเคราะห์ข้อมูลเชิงลึก สกัด Extract patterns และสร้าง insights จากข้อมูลดิบเพื่อใช้ในการตัดสินใจ
💻
Developer Agent (ตัวพัฒนา)
เขียนและแก้ไขโค้ด สร้างแอปพลิเคชัน และตรวจสอบความถูกต้องด้วยการรัน test cases อัตโนมัติ

2. หน้าที่ของแต่ละ Subagent

Agent Type หน้าที่หลัก เครื่องมือที่ใช้ Output Format
Researcher ค้นหาข้อมูล, Scraping web, API calls BeautifulSoup, Requests, API Clients Text, JSON, CSV
Writer เขียนบทความ, สร้างโค้ด, Copywriting LLM, Template Engine Markdown, HTML, Code
Analyst วิเคราะห์ข้อมูล, ตรวจสอบ trends Pandas, NumPy, Stats Insights, Charts, JSON
Developer เขียนโค้ด, Debug, Testing Code LLM, Testing Frameworks Source Code, Test Results
Reviewer ตรวจสอบคุณภาพ, อ่านความคิดเห็น Quality Checkers, Linting Feedback, Fixes

3. การสื่อสารระหว่าง Agents

แต่ละ subagent สื่อสารกับ coordinator ผ่าน Message Queue หรือ HTTP APIs ซึ่งรองรับ both synchronous และ asynchronous communication เพื่อความยืดหยุ่นสูงสุด

🔹 Communication Pattern

Asynchronous (แนะนำสำหรับ production): ใช้ message queue เช่น Redis, RabbitMQ หรือ Kafka สำหรับงานที่ใช้เวลานาน

Synchronous (สำหรับ development): ใช้ HTTP API calls โดยตรงสำหรับงานที่ใช้เวลาน้อยกว่า วินาที

คู่มือตั้งค่า openclaw.json (Configuration Guide)

การตั้งค่าของ OpenClaw ทำผ่านไฟล์ openclaw.json ซึ่งเป็นไฟล์ JSON ที่กำหนด configuration ทั้งหมดของระบบ ไฟล์นี้ควรอยู่ที่ root directory ของโปรเจค

1. โครงสร้างพื้นฐานของ openclaw.json

openclaw.json
{
  "version": "1.0.0",
  "name": "OpenClaw Project",
  "description": "การตั้งค่าระบบ OpenClaw Subagent",
  
  // ตั้งค่า coordinator
  "coordinator": {
    "task_interval_ms": 1000,
    "max_tasks": 100,
    "timeout_ms": 30000,
    "retry_count": 3,
    "log_level": "info"
  },

  // ตั้งค่า subagents
  "agents": {
    "researcher": {
      "enabled": true,
      "max_parallel": 3,
      "tools": ["web_search", "api_call", "data_scraper"],
      "api_keys": ["OPENAI_API_KEY", "SERPAPI_KEY"]
    },
    
    "writer": {
      "enabled": true,
      "max_parallel": 2,
      "tools": ["text_generation", "markdown_conversion"],
      "default_model": "gpt-4"
    },
    
    "analyst": {
      "enabled": true,
      "max_parallel": 2,
      "tools": ["data_analysis", "pattern_recognition"],
      "max_data_points": 10000
    },
    
    "developer": {
      "enabled": true,
      "max_parallel": 2,
      "tools": ["code_generation", "debugging", "testing"],
      "supported_languages": ["python", "javascript", "typescript"]
    }
  },

  // ตั้งค่า output
  "output": {
    "directory": "./output",
    "format": "markdown",
    "include_timestamp": true,
    "compact_output": false
  },

  // ตั้งค่า logging
  "logging": {
    "enabled": true,
    "level": "INFO",
    "directory": "./logs",
    "max_file_size_mb": 50
  },

  // ตั้งค่า security
  "security": {
    "rate_limit_ms": 100,
    "max_concurrent_requests": 10,
    "allow_http": false
  }
}

2.Parameter หลักที่ต้องเข้าใจ

Parameter ประเภท ค่าเริ่มต้น คำอธิบาย
version String "1.0.0" เวอร์ชันของ configuration schema
name String - ชื่อของโปรเจค OpenClaw
coordinator.task_interval_ms Number 1000 Interval ในการตรวจสอบงานใหม่ (มิลลิวินาที)
coordinator.timeout_ms Number 30000 Timeout สำหรับงานแต่ละงาน (มิลลิวินาที)
coordinator.retry_count Number 3 จำนวนครั้งที่จะลองใหม่เมื่อเกิด error
agents.{name}.enabled Boolean true เปิด/ปิด agent ตัวนี้
agents.{name}.max_parallel Number 1 จำนวนสูงสุดของ instance ที่จะรันพร้อมกัน
output.directory String "./output" Directory ที่จะบันทึกผลลัพธ์

3. ตัวอย่าง Configuration จริง

openclaw.json (Production)
{
  "version": "1.0.0",
  "name": "OpenClaw Production Config",
  "description": "Configuration สำหรับ production environment",

  "coordinator": {
    "task_interval_ms": 500,
    "max_tasks": 500,
    "timeout_ms": 60000,
    "retry_count": 5,
    "log_level": "info"
  },

  "agents": {
    "researcher": {
      "enabled": true,
      "max_parallel": 5,
      "tools": ["web_search", "api_call", "data_scraper", "database_query"],
      "api_keys": ["OPENAI_API_KEY", "SERPAPI_KEY", "GOOGLE_CSE_ID"],
      "rate_limit": {
        "requests_per_minute": 60
      }
    },

    "writer": {
      "enabled": true,
      "max_parallel": 3,
      "tools": ["text_generation", "markdown_conversion", "code_documentation"],
      "default_model": "gpt-4-turbo",
      "temperature": 0.7,
      "max_tokens": 4096
    },

    "analyst": {
      "enabled": true,
      "max_parallel": 4,
      "tools": ["data_analysis", "pattern_recognition", "statistical_analysis"],
      "max_data_points": 50000,
      "time_window_seconds": 3600
    },

    "developer": {
      "enabled": true,
      "max_parallel": 3,
      "tools": ["code_generation", "debugging", "testing", "code_review"],
      "supported_languages": ["python", "javascript", "typescript", "java", "go"],
      "code_generation": {
        "max_lines": 500,
        "include_tests": true,
        "inline_comments": true
      }
    }
  },

  "output": {
    "directory": "/var/www/outputs/openclaw",
    "format": "markdown",
    "include_timestamp": true,
    "compact_output": false,
    "separate_logs": true
  },

  "logging": {
    "enabled": true,
    "level": "INFO",
    "directory": "/var/log/openclaw",
    "max_file_size_mb": 100,
    "rotate_count": 5,
    "json_format": true
  },

  "security": {
    "rate_limit_ms": 200,
    "max_concurrent_requests": 20,
    "allow_http": false,
    "allowed_origins": ["https://example.com"],
    "api_secret_key": "${SECRET_KEY_ENV}"
  },

  "monitoring": {
    "enabled": true,
    "metrics_endpoint": "/metrics",
    "health_check_interval_ms": 30000,
    "alert_thresholds": {
      "task_timeout_rate_percent": 10,
      "error_rate_percent": 5
    }
  }
}

⚠️ เคล็ดลับการตั้งค่า

  • Production: ตั้ง max_parallel ให้สูงขึ้นและ timeout_ms ให้นานขึ้น
  • Development: ตั้ง max_parallel: 1 เพื่อ debug ง่ายขึ้น
  • Security: อย่าลืม set allow_http: false ใน production

รูปแบบการทำงาน (Working Patterns)

OpenClaw Subagent รองรับหลาย pattern ของการทำงาน ซึ่งแต่ละ pattern มีความเหมาะสมกับงานที่ต่างกัน การเลือก pattern ที่ถูกต้องจะช่วยให้ระบบทำงานได้อย่างมีประสิทธิภาพสูงสุด

1. Parallel Execution Pattern

รูปที่ 2: Parallel Execution - ระบบประมวลผลแบบขนาน
Coordinator Task Splitter Agent 1 Process A Agent 2 Process B Agent 3 Process C Agent 4 Process D Result Aggregator
Parallel Execution Pattern
Coordinator แบ่งงานออกเป็นหลายชิ้นและส่งให้ subagents หลายตัวประมวลผลพร้อมกัน แต่ละ agent ทำงานบนส่วนของงานที่ได้รับมอบหมายและส่งผลลัพธ์กลับมาที่ coordinator สำหรับการรวมผล

适用场景 (适用场景)

  • การวิเคราะห์ข้อมูลขนาดใหญ่
  • การสร้างเนื้อหาจำนวนมาก
  • การรัน test cases พร้อมกัน
  • การ scrap ข้อมูลจากหลายแหล่ง
Sequential Workflow Pattern
งานถูกส่งผ่านจาก agent หนึ่งไปยังอีก agent หนึ่งตามลำดับที่กำหนด โดยผลลัพธ์ของงานก่อนหน้าจะเป็น input ของงานถัดไป สร้าง pipeline ที่ชัดเจนในการประมวลผล

适用场景 (适用场景)

  • Content creation pipeline
  • Data processing workflow
  • Code generation & testing
  • Multi-stage analysis

2. Sequential Workflow Pattern

รูปที่ 3: Sequential Workflow - ระบบทำงานตามลำดับ
Researcher Gather Data Step 1 Analyst Analyze Data Step 2 Writer Create Content Step 3 Developer Generate Code Step 4
openclaw.json - Sequential Pattern
{
  "workflow": {
    "sequential": {
      "enabled": true,
      "stages": [
        {
          "name": "research",
          "agent": "researcher",
          "input_transform": "raw_query",
          "output_transform": "structured_data"
        },
        {
          "name": "analysis",
          "agent": "analyst",
          "input_transform": "raw_data",
          "output_transform": "insights"
        },
        {
          "name": "writing",
          "agent": "writer",
          "input_transform": "insights",
          "output_transform": "content"
        },
        {
          "name": "development",
          "agent": "developer",
          "input_transform": "content_spec",
          "output_transform": "executable_code"
        }
      ],
      "transition_delay_ms": 500,
      "on_error": "stop"  // or "continue"
    }
  }
}

3. Hierarchical Structure Pattern

รูปที่ 4: Hierarchical Structure - ระบบหลายระดับชั้น
Master Super Coordinator Group A Group B Group C Worker 1 Worker 2 Worker 3 Worker 4 Worker 5 Worker 6 Worker 7 Expert Debug Agent

💡 Pattern Recommendation

ใช้ Hierarchical Structure เมื่อ:

  • มีงานจำนวนมากที่ต้องจัดการพร้อมกัน
  • ต้องการ scale ระบบไปยังทีมขนาดใหญ่
  • ต้องการจัดการงานหลายประเภทพร้อมกัน
  • ต้องการ fallback เมื่อ task หนึ่งล้มเหลว

ตัวอย่างโค้ด (Code Examples)

ในส่วนนี้ เราจะแสดงตัวอย่างการใช้งาน OpenClaw Subagent ผ่านโค้ดจริง ตั้งแต่การตั้งค่าง่ายๆ ไปจนถึงการใช้งานขั้นสูง

1. Quick Start - Basic Setup

quickstart.py
import json
from openclaw import OpenClaw, Coordinator

# Load configuration
with open('openclaw.json') as f:
    config = json.load(f)

# Initialize OpenClaw
client = OpenClaw(config)

# Create a simple task
task = client.create_task(
    name='research_summary',
    description='Research latest AI trends and summarize',
    input_data={
        'topic': 'AI Subagents',
        'keywords': ['OpenClaw', 'Architecture']
    }
)

# Execute task
result = client.execute(task)
print(result.summary)
print(result.aggregated_data)

2. Parallel Execution Example

parallel_execution.py
import asyncio
from openclaw import OpenClaw, Task

# Initialize client
client = OpenClaw('openclaw.json')

# Create multiple research tasks
topics = ['AI Agents', 'Parallel Processing', 
          'Workflow Management', 'System Architecture']

async def run_parallel_research():
    tasks = []
    for topic in topics:
        task = Task(
            agent='researcher',
            action='gather_info',
            input_data={'topic': topic},
            priority=2
        )
        tasks.append(task)
    
    # Execute all tasks in parallel
    # This will spawn multiple researcher agents simultaneously
    results = await client.execute_parallel(tasks, max_parallel=4)
    
    # Analyze and combine results
    combined_results = {
        'topics': topics,
        'total_researched': len(results),
        'data_points': sum(r.data_points for r in results)
    }
    
    return combined_results

# Run the parallel execution
if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    final_results = loop.run_until_complete(run_parallel_research())
    print(json.dumps(final_results, indent=2))

3. Sequential Workflow Example

sequential_workflow.py
from openclaw import OpenClaw, Workflow, Task

# Initialize client
client = OpenClaw('openclaw.json')

# Define sequential workflow
workflow = Workflow(name='content_pipeline')

# Step 1: Research
workflow.add_stage(
    agent='researcher',
    action='gather_research',
    name='research',
    input_transform={'topic': 'input.topic'}
)

# Step 2: Analysis
workflow.add_stage(
    agent='analyst',
    action='analyze_data',
    name='analysis',
    input_transform={'data': 'research.output'}
)

# Step 3: Writing
workflow.add_stage(
    agent='writer',
    action='write_content',
    name='writing',
    input_transform={'insights': 'analysis.output'}
)

# Step 4: Code Generation
workflow.add_stage(
    agent='developer',
    action='generate_code',
    name='code',
    input_transform={'spec': 'writing.output'}
)

# Execute the complete workflow
result = client.execute_workflow(
    workflow=workflow,
    input_data={'topic': 'AI Subagents'}
)

print("Research:", result.stages.research.output)
print("Content:", result.stages.writing.output)
print("Code:", result.stages.code.output)

4. Hierarchical Structure Example

hierarchical_structure.py
from openclaw import OpenClaw, HierarchicalClient

# Initialize hierarchical client
# This creates a master coordinator with multiple sub-coordinators
client = HierarchicalClient(
    name='production-hierarchy',
    num_groups=3,
    agents_per_group=5
)

# The client automatically creates a tree structure:
# Master Coordinator (1)
#   Group Coordinator A (3)
#     Workers 1-5 (5 each)
#   Group Coordinator B (3)
#     Workers 6-10 (5 each)
#   Group Coordinator C (3)
#     Workers 11-15 (5 each)

# Submit tasks to the hierarchical system
tasks = []
for i in range(15):
    task = {
        'name': f'task_{i}',
        'type': 'analysis',
        'priority': i % 3,
        'data': {'id': i}
    }
    tasks.append(task)

# Execute with automatic hierarchical scheduling
results = client.execute_hierarchical(tasks)

# Check group distribution
print("Group A tasks:", len(results.groups.group_a))
print("Group B tasks:", len(results.groups.group_b))
print("Group C tasks:", len(results.groups.group_c))

# Access specialized expert agents when needed
if results.overall_status == 'error':
    expert_result = client.call_expert_agent(
        task_id=results.failed_tasks[0],
        expert_type='debugger'
    )
    print("Expert debug:", expert_result.fix)

5. Agent-Specific Examples

agent_examples.py
from openclaw.agents import Researcher, Writer, Analyst, Developer

# === RESEARCHER EXAMPLE ===
researcher = Researcher(api_keys=['OPENAI_KEY', 'SERPAPI_KEY'])

research_result = researcher.run_research(
    topic='Latest AI Trends 2025',
    sources=['web', 'academic', 'news'],
    filters={
        'date_range': {'from': '2024-01-01'},
        'lang': ['en', 'th']
    }
)

# === WRITER EXAMPLE ===
writer = Writer(model='gpt-4', temperature=0.7)

content = writer.generate_content(
    content_type='blog_post',
    topic='OpenClaw Subagent',
    outline=research_result.outline,
    tone='professional',
    target_audience='developers',
    include_examples=True
)

# === ANALYST EXAMPLE ===
analyst = Analyst()

analysis_results = analyst.analyze_data(
    data=research_result.data,
    methods=['trends', 'clustering', 'correlation'],
    output_format='json'
)

# === DEVELOPER EXAMPLE ===
developer = Developer(supported_languages=['python', 'typescript'])

code = developer.generate_code(
    specification=content.specification,
    language='python',
    framework='fastapi',
    include_tests=True,
    inline_comments=True,
    max_lines=500
)

# Run tests
test_results = developer.run_tests(code='generated_code.py')

ขั้นสูง (Advanced)

ส่วนนี้จะอธิบายถึงเทคนิคขั้นสูงในการใช้งาน OpenClaw Subagent รวมถึงการปรับแต่งระบบ การใช้งาน custom agents และการ integrate กับระบบอื่นๆ

1. Custom Agent Development

custom_agent.py
from openclaw import BaseAgent, AgentConfig
from typing import Dict, Any, Optional
import json

# Custom Agent Example: SEO Optimizer
class SEOOptimizer(BaseAgent):
    """Custom agent สำหรับวิเคราะห์และปรับปรุง SEO"""
    
    _agent_type = 'seo_optimizer'
    
    def __init__(self, config: AgentConfig):
        super().__init__(config)
        self.keywords_database = {}  # Load keywords from database
    
    async def analyze(self, content: str) -> Dict[str, Any]:
        # วิเคราะห์ SEO metrics
        metrics = {
            'keyword_density': await self._calculate_keyword_density(content),
            'readability_score': await self._calculate_readability(content),
            'semantic_structure': await self._analyze_semantic(content),
            'seo_score': await self._calculate_seo_score(content)
        }
        return metrics
    
    async def recommend(self, metrics: Dict[str, Any]) -> Dict[str, Any]:
        # สร้าง recommendations
        recommendations = []
        
        if metrics['keyword_density'] < 0.01:
            recommendations.append('Increase keyword density')
        
        if metrics['readability_score'] < 60:
            recommendations.append('Improve readability')
        
        return {
            'metrics': metrics,
            'recommendations': recommendations,
            'priority': await self._prioritize(recommendations)
        }
    
    async def optimize(self, content: str) -> str:
        # Auto-optimize content
        return await self._rewrite_with_seo(content)
    
    async def _calculate_keyword_density(self, content: str) -> float:
        # Implementation
        return 0.05  # Example density
    
    async def _calculate_readability(self, content: str) -> int:
        # Implementation
        return 75  # Example score
    
    async def _analyze_semantic(self, content: str) -> Dict[str, Any]:
        # Implementation
        return {'topics': ['AI', 'Technology']}
    
    async def _calculate_seo_score(self, content: str) -> int:
        # Calculate overall SEO score
        keywords_density = await self._calculate_keyword_density(content)
        readability = await self._calculate_readability(content)
        
        score = (keywords_density * 1000 + readability) / 2
        return int(score)

2. Integration with External Systems

integration_example.py
from openclaw import OpenClaw
import requests
import json

# Integration with PostgreSQL
class PostgreSQLWriter:
    """Writer agent ที่บันทึกผลลัพธ์ลง PostgreSQL"""
    
    def __init__(self, dsn: str):
        import asyncpg
        self.dsn = dsn
        self.conn = None
    
    async def connect(self):
        self.conn = await asyncpg.connect(self.dsn)
    
    async def save_result(self, result: Dict):
        await self.conn.execute(
            '''INSERT INTO results (data, created_at) VALUES ($1, NOW())''',
            json.dumps(result)
        )
    
    async def close(self):
        if self.conn:
            await self.conn.close()

# Integration with Slack Notifications
class SlackNotifier:
    """ส่งการแจ้งเตือนไปยัง Slack"""
    
    def __init__(self, webhook_url: str):
        self.webhook_url = webhook_url
    
    async def send_task_update(self, task_id: str, status: str, message: str):
        payload = {
            'text': f'{task_id}: {status}',
            'attachments': [{
                'color': '#36a64f' if status == 'success' else '#ff0000',
                'text': message
            }]
        }
        await requests.post(self.webhook_url, json=payload)

# Integration with Redis Queue
class RedisQueueClient:
    """Use Redis for task queuing"""
    
    def __init__'localhost', port: int = 6379):
        import redis
        self.redis = redis.Redis(host=host, port=port, decode_responses=True)
    
    async def enqueue_task(self, task: Dict):
        self.redis.lpush('openclaw:tasks', json.dumps(task))
    
    async def dequeue_task(self) -> Optional[Dict]:
        task = self.redis.rpop('openclaw:tasks')
        return json.loads(task) if task else None
    
    async mark_task_completed(self, task_id: str, result: Dict):
        self.redis.hset('openclaw:results', task_id, json.dumps(result))

3. Performance Optimization

performance_optimization.py
import asyncio
import time
from openclaw import OpenClaw, PerformanceMetrics

# Performance monitoring decorator
def performance_monitor(func):
    async def wrapper(*args, **kwargs):
        start_time = time.time()
        try:
            result = await func(*args, **kwargs)
            execution_time = time.time() - start_time
            PerformanceMetrics.record_execution(func.__name__, execution_time)
            return result
        except Exception as e:
            PerformanceMetrics.record_error(func.__name__, str(e))
            raise
    return wrapper

# Agent pooling for better performance
class AgentPool:
    """Pool ของ agents เพื่อลด overhead ในการสร้าง agent ใหม่"""
    
    def __init__(self, agent_class, pool_size: int = 5):
        self.pool_size = pool_size
        self.available_agents = []
        self.in_use_agents = []
        self._initialize_pool(agent_class)
    
    def _initialize_pool(self, agent_class):
        for _ in range(self.pool_size):
            self.available_agents.append(agent_class())
    
    async def get_agent(self):
        if self.available_agents:
            agent = self.available_agents.pop()
            self.in_use_agents.append(agent)
            return agent
        return None  # Or wait and retry
    
    async return_agent(self, agent):
        if agent in self.in_use_agents:
            self.in_use_agents.remove(agent)
            self.available_agents.append(agent)

# Async batch processing
async def process_batch(tasks: list, max_concurrent: int = 10):
    semaphore = asyncio.Semaphore(max_concurrent)
    
    async def sem_task(task):
        async with semaphore:
            return await process_single_task(task)
    
    results = await asyncio.gather(*[sem_task(task) for task in tasks])
    return results

💡 Performance Best Practices

  • ใช้ Agent Pool สำหรับลด overhead ในการสร้าง agent ใหม่
  • ตั้ง max_concurrent ให้เหมาะสมกับ resources ที่มี
  • ใช้ async/await สำหรับ I/O-bound operations
  • Monitor memory usage และ scale ตามความต้องการ
  • ใช้ caching สำหรับ results that don't change often

Best Practices

การใช้งาน OpenClaw Subagent ให้ได้ผลลัพธ์ที่ดีที่สุด ต้องปฏิบัติตาม best practices เหล่านี้

1. Task Design

ไม่ควร:

  • สร้าง task ที่ใหญ่เกินไปและซับซ้อน
  • แบ่ง task ไม่ชัดเจน
  • มี dependency ที่ซับซ้อนระหว่าง task

ควร:

  • แบ่ง task ให้เล็กและมี focus ชัดเจน
  • กำหนด input/output ให้ชัดเจน
  • ใช้ error handling อย่างเหมาะสม
2. Agent Management

ไม่ควร:

  • สร้าง agent 太多数量ที่ไม่จำเป็น
  • ไม่ปิด agent ที่ไม่ใช้งาน
  • ไม่ monitor agent's performance

ควร:

  • Reuse agents ผ่าน agent pooling
  • ปิด agents ที่ไม่ใช้งานเพื่อประหยัด resources
  • Monitor resource usage และ scale ตามความต้องการ
3. Configuration

ไม่ควร:

  • Hardcode sensitive ข้อมูลใน config
  • ไม่มี staging configuration
  • ใช้ max_parallel ที่สูงเกินไปใน development

ควร:

  • ใช้ environment variables สำหรับ sensitive data
  • แยก configuration สำหรับ development และ production
  • Document all configuration options
4. Monitoring

ไม่ควร:

  • ไม่มี monitoring system
  • ไม่ตั้ง alert thresholds
  • ไม่ log errors อย่างละเอียด

ควร:

  • Implement comprehensive monitoring
  • Set up alert thresholds และ notifications
  • Log all errors และ warnings
5. Security

ไม่ควร:

  • Store API keys ใน code
  • ไม่ validate input
  • เป็น开放 system โดยไม่มี authentication

ควร:

  • ใช้ secure วิธีในการจัดการ API keys
  • Validate และ sanitize all inputs
  • Implement proper authentication และ authorization
6. Testing

ไม่ควร:

  • Deployโดยไม่มีการ test
  • ไม่มี automated test cases
  • ไม่ test edge cases

ควร:

  • Implement automated test cases
  • Test all edge cases และ error conditions
  • Use CI/CD for deployment

⚠️ Common Pitfalls to Avoid

  • Over-decoupling: แบ่ง task จนเกินไปทำให้ coordination overhead สูง
  • Under-decoupling: Task ใหญ่เกินไปทำให้ parallelization ได้ไม่ดี
  • Ignoring timeout: ไม่ตั้ง timeout จะทำให้ system ค้างเมื่อ agent ล้มเหลว
  • No error recovery: ไม่มี mechanism สำหรับจัดการ error ทำให้ system หยุดเดิน
  • Skipping validation: ไม่ validate input อาจทำให้เกิด unexpected behavior

Troubleshooting

คู่มือแก้ไขปัญหาเมื่อเกิดข้อผิดพลาดในการใช้งาน OpenClaw Subagent

Issue: Task Timeout บ่อย
Tasks หลายอัน timeout ก่อนที่จะเสร็จสมบูรณ์
Potential Causes:
  • Timeout value ตั้งต่ำเกินไป
  • Agent ไม่มี resources พอในการประมวลผล
  • Task มี complexity สูงเกินไป
  • Network latency สูง
Solutions:
  • Increase timeout_ms ใน coordinator config
  • Reduce task complexity หรือแบ่ง task ย่อย
  • เพิ่ม max_parallel ของ agent
  • ใช้ async processing สำหรับ long-running tasks
Issue: Memory Exhaustion
System ใช้ memory เกินขีดจำกัดและเกิด OOM error
Potential Causes:
  • max_parallel ตั้งสูงเกินไป
  • Tasks ที่ใช้ memory มากเกินไป
  • Memory leak ใน agent code
  • ไม่มี garbage collection
Solutions:
  • ลด max_parallel ของ agents
  • Implement batch processing
  • ตรวจสอบและแก้ memory leak
  • Add memory limit check
Issue: Agent Not Responding
Agent บางตัวไม่ตอบสนองต่อ requests
Potential Causes:
  • Agent crashed โดยไม่ได้ตั้งค่า auto-restart
  • Deadlock ใน task dependencies
  • Resource exhaustion
  • Network connectivity issues
Solutions:
  • เปิด auto-restart สำหรับ agents
  • ตรวจสอบ task dependencies
  • Monitor system resources
  • Implement health check endpoints
Issue: Result Loss
Some results หายไปหลังจาก execution เสร็จ
Potential Causes:
  • Output directory ไม่มีสิทธิ์เขียน
  • Concurrent writes causing race condition
  • Result serialization failure
  • Not properly committing results
Solutions:
  • Validate output directory permissions
  • ใช้ file locking สำหรับ concurrent writes
  • Implement result queuing
  • Add result verification
Issue: API Rate Limiting
External API calls ถูก rate limited
Potential Causes:
  • Too many concurrent requests
  • ไม่มี rate limiting control
  • ไม่มี retry mechanism
  • API quota exhausted
Solutions:
  • Implement request throttling
  • ใช้ circuit breaker pattern
  • เพิ่ม retry_with_backoff
  • Monitor API usage และ quotas
Issue: Configuration Errors
System fails to start due to configuration issues
Potential Causes:
  • Invalid JSON syntax
  • Missing required fields
  • Incorrect data types
  • Environment variables not set
Solutions:
  • Use JSON validator
  • Provide default values
  • Add comprehensive error messages
  • Implement config validation

❌ Emergency Recovery Checklist

เมื่อ system หยุดการทำงาน ให้ทำตามขั้นตอนนี้:

  1. Check coordinator และ agent logs
  2. Verify system resources (memory, CPU, disk)
  3. Validate configuration files
  4. Restart failed components
  5. Resume pending tasks
  6. Monitor recovery status