ในบทความนี้
- 1. ทำไม Agent ตัวเดียวไม่พอ?
- 2. Multi-Agent Architecture — แนวคิดการแบ่งงาน
- 3. สถาปัตยกรรม Agent Team
- 4. ออกแบบทีม — ตัวอย่างจริง
- 5. Model Routing & Cost Optimization
- 6. sessions_spawn ในทางปฏิบัติ
- 7. Communication Patterns
- 8. ตัวอย่างจริง: Coding Team Pipeline
- 9. ข้อจำกัดและ Lessons Learned
- 10. Key Takeaways
In this post
- 1. Why One Agent Is Not Enough
- 2. Multi-Agent Architecture — How the Work Gets Divided
- 3. Agent Team Architecture
- 4. Designing a Team — Real Examples
- 5. Model Routing & Cost Optimization
- 6. sessions_spawn in Practice
- 7. Communication Patterns
- 8. A Real Example: The Coding Team Pipeline
- 9. Limitations and Lessons Learned
- 10. Key Takeaways
1. ทำไม Agent ตัวเดียวไม่พอ?
หลังจากที่เราได้รู้จัก OpenClaw ในโพสต์แรกแล้ว คุณอาจจะเริ่มใช้ single agent และรู้สึกว่า "โอเค มันดีแล้ว แต่..." คือมันยังมีปัญหาอยู่ ใช่ไหม?
ปัญหาของ Generalist AI: Agent ตัวเดียวที่ต้องทำทุกอย่างเหมือนคนที่ต้องเป็นทั้ง programmer, researcher, writer, designer และ project manager ในคนเดียว มันเก่งหลายอย่าง แต่ไม่ได้เซี่ยวชาญในอะไรเป็นพิเศษ
ลองนึกดู:
- Task Switching Overhead: เปลี่ยนจาก coding mode ไป research mode แล้วไป writing mode มันต้อง context switch ทุกครั้ง
- Quality Inconsistency: บางครั้งเขียนโค้ดได้ดี บางครั้งเขียน research paper ได้ดี แต่ไม่ได้คงที่
- Memory Conflicts: Context ที่เกี่ยวกับ coding project อาจจะรบกวนการทำ research ใน domain ต่างกัน
- Prompt Engineering Complexity: ยิ่งให้ทำหลายอย่าง instruction ก็ยิ่งซับซ้อน บางครั้ง confusing
นี่คือเหตุผลที่บริษัทจริงไม่มีพนักงานคนเดียวทำทุกอย่าง — พวกเขามี teams of specialists แทน
🎯 Specialist vs Generalist
การวิจัยใน cognitive science บอกว่าการมี specialized agents ที่มี focused context และ clear responsibilities จะให้ output quality ที่ดีกว่าการมี general-purpose agent ที่ต้องสลับ context บ่อยๆ
2. Multi-Agent Architecture — แนวคิดการแบ่งงาน
Multi-Agent Architecture ไม่ใช่แค่การมี AI หลายตัว แต่เป็นการออกแบบ system of intelligent agents ที่แต่ละตัวมี specialization และ collaborate กันเพื่อทำงานที่ซับซ้อน
Core Concepts:
🎭 Agent Specialization: แต่ละ agent มี domain expertise และ personality ที่เหมาะกับงานนั้นๆ เช่น research agent ที่เก่งในการหาข้อมูลและ synthesis หรือ code-review agent ที่เข้าใจ coding standards อย่างลึกซึ้ง
🎯 Orchestrator Pattern: มี main agent หรือ orchestrator ที่ทำหน้าที่ project manager รับงานจาก user แล้วแบ่งเป็น subtasks และ delegate ให้ specialized agents แต่ละตัว
📡 Communication Protocol: Agents สื่อสารกันผ่าน structured messages, file sharing ใน workspace และ memory sharing ทำให้ knowledge ที่ได้จากงานหนึ่งสามารถนำไปใช้ในงานอื่นได้
🧠 Collective Intelligence: ผลลัพธ์รวมของทีม agents มักจะดีกว่าผลลัพธ์จาก agent เดียว เพราะ diverse perspectives และ specialized knowledge
เปรียบเทียบกับทีมคนจริง:
| Aspect | Human Team | Agent Team | Advantages |
|---|---|---|---|
| Specialization | Years of training & experience | Model + prompt engineering + memory | Instant expertise, no learning curve |
| Communication | Meetings, Slack, email | sessions_send, workspace files | Zero latency, perfect information transfer |
| Memory | Individual notes, documents | Shared memory system, vector search | Perfect recall, searchable knowledge |
| Availability | 8 hours/day, sick days | 24/7, no downtime | Always available, no human limitations |
| Scalability | Linear cost per person | API costs, parallel execution | Can spawn multiple instances instantly |
| Quality Control | Code review, peer feedback | Cross-agent validation, automated QA | Consistent standards, no emotional bias |
3. สถาปัตยกรรม Agent Team
🏗️ Multi-Agent Flow Architecture
"Build a feature"
Receives & analyzes
Plans & delegates
Execute subtasks
Combine results
OpenClaw Multi-Agent Implementation:
📊 sessions_spawn: Main function สำหรับสร้าง sub-agents ระบุ label, model, instructions และ mode (run vs session)
# Spawn specialized agents
subagents spawn research-lead "Academic research on transformer optimization"
subagents spawn code-review "Review Python ML pipeline code"
subagents spawn docs-writer "Document API endpoints"
# Check running agents
subagents list
# Steer agent direction
subagents steer research-lead "Focus on recent 2024 papers"
# Terminate when done
subagents kill docs-writer
🔄 Workflow Orchestration: Main agent รับ complex request → แบ่งเป็น subtasks → spawn appropriate specialists → monitor progress → combine results → deliver final output
💾 Memory Sharing: Agents share workspace files และ memory system ผลงานของ research agent สามารถ access ได้โดย writing agent
⚡ Parallel Execution: Multiple agents ทำงาน parallel ลดเวลา total execution time อย่างมาก
4. ออกแบบทีม — ตัวอย่างจริง
จากประสบการณ์การใช้งาน OpenClaw ในองค์กรต่างๆ เราได้ identify ทีม patterns ที่ effective และใช้ได้จริง นี่คือ 5 ทีมหลักที่พิสูจน์ตัวเองแล้ว:
✍️ Writing Team (8 agents)
- editor-chief - content strategy & oversight Opus
- research-writer - factual content creation Sonnet
- copywriter - marketing & persuasive copy Sonnet
- technical-writer - documentation & guides Sonnet
- translator - multi-language content Sonnet
- proofreader - grammar & style checks Sonnet
- seo-optimizer - search optimization Sonnet
- fact-checker - verification & citations Opus
🔬 Academic Team (10 agents)
- research-lead - project coordination Opus
- literature-reviewer - paper analysis Opus
- methodology-expert - experimental design Opus
- data-analyst - statistical analysis Sonnet
- paper-writer - manuscript drafting Sonnet
- citation-manager - references & bibliography Sonnet
- peer-reviewer - quality assurance Opus
- visual-designer - figures & charts Sonnet
- submission-manager - journal formatting Sonnet
- grant-writer - funding proposals Opus
💻 Coding Team (8 agents)
- tech-lead - architecture & planning Opus
- code-reviewer - quality & standards Opus
- backend-dev - API & server logic Sonnet
- frontend-dev - UI & client-side Sonnet
- db-specialist - database design & queries Sonnet
- test-engineer - automated testing Sonnet
- devops-engineer - deployment & CI/CD Sonnet
- docs-writer - technical documentation Sonnet
🎓 Course Team (10 agents)
- curriculum-designer - learning objectives Opus
- content-creator - lesson materials Sonnet
- slide-builder - presentation design Sonnet
- exercise-writer - practice problems Sonnet
- quiz-generator - assessments Sonnet
- video-scripter - lecture scripts Sonnet
- handout-writer - study guides Sonnet
- accessibility-expert - inclusive design Sonnet
- learning-analyst - pedagogy optimization Opus
- quality-reviewer - content validation Opus
🌐 Translation Team (8 agents)
- translation-lead - project coordination Opus
- english-translator - EN translation Sonnet
- thai-translator - TH translation Sonnet
- chinese-translator - ZH translation Sonnet
- cultural-adapter - localization Sonnet
- quality-checker - accuracy review Opus
- style-harmonizer - consistency Sonnet
- technical-validator - domain accuracy Sonnet
🎨 Team Design Principles
Clear Roles: แต่ละ agent มี specific responsibility ไม่ overlap
Model Matching: ใช้ Opus สำหรับ complex reasoning, Sonnet สำหรับ execution
Quality Gates: มี reviewer agents เพื่อ quality control
Scalability: สามารถเพิ่ม/ลด agents ตาม workload
5. Model Routing & Cost Optimization
หนึ่งในประเด็นสำคัญของ multi-agent architecture คือการเลือกใช้ AI model ให้เหมาะสมกับงาน เพื่อให้ได้ quality ที่ดีแต่ cost ที่ reasonable
Model Selection Strategy:
🧠 Claude Opus (Complex Reasoning):
- Orchestrator agents ที่ต้องวางแผนและแบ่งงาน
- Code review และ architecture decisions
- Research coordination และ methodology design
- Quality assurance และ final review
- Complex problem solving และ creative tasks
⚡ Claude Sonnet (Execution & Routine):
- Content writing และ documentation
- Code implementation และ testing
- Data processing และ analysis
- Translation และ formatting
- Repetitive tasks และ standard procedures
| Use Case | Model Choice | Cost per 1K tokens | Reasoning |
|---|---|---|---|
| Project Planning | Claude Opus | $0.015 / $0.075 | Needs strategic thinking |
| Code Writing | Claude Sonnet | $0.003 / $0.015 | Clear specifications, execution-focused |
| Code Review | Claude Opus | $0.015 / $0.075 | Critical analysis, pattern recognition |
| Documentation | Claude Sonnet | $0.003 / $0.015 | Structured, predictable output |
| Research Synthesis | Claude Opus | $0.015 / $0.075 | Complex reasoning, connections |
| Content Translation | Claude Sonnet | $0.003 / $0.015 | Pattern-based, well-defined task |
Cost Analysis Example (Monthly):
# Organization with active agent teams
Research Team: ~200K tokens/day × 30 days × $0.045 avg = $270/month
Coding Team: ~150K tokens/day × 22 workdays × $0.025 avg = $82.5/month
Writing Team: ~100K tokens/day × 30 days × $0.020 avg = $60/month
# Total estimated monthly cost: ~$412.5
# Compared to 2 full-time employees: ~$8,000+/month
ROI: 20x cost savings with 24/7 availability
Cost Optimization Strategies:
- Smart Caching: เก็บ common responses และ reuse เมื่อเจอ similar queries
- Batch Processing: รวม similar tasks ให้ agent ทำพร้อมกัน
- Progressive Enhancement: เริ่มด้วย Sonnet แล้วค่อยใช้ Opus ถ้าจำเป็น
- Context Optimization: ลด unnecessary context ใน prompts
- Task Complexity Assessment: วิเคราะห์งานก่อนเลือก model
6. sessions_spawn ในทางปฏิบัติ
การ spawn sub-agents เป็น core feature ที่ทำให้ OpenClaw มี multi-agent capabilities นี่คือ patterns และ best practices ที่ได้จากการใช้งานจริง:
Basic Spawning Patterns:
# แบบ run-and-return (fire-and-forget)
subagents spawn research-lead
"Research transformer optimization papers from 2024"
--mode run --timeout 600
# แบบ interactive session
subagents spawn code-reviewer
"Review the ML pipeline code in ./src/"
--mode session --label "code-review-v1"
# แบบ batch processing
subagents spawn translator
"Translate all .md files in ./docs/ to Thai"
--mode run --label "docs-translation"
Orchestrator Delegation Example:
# Main orchestrator receives complex request
User: "Build a customer feedback analysis dashboard"
# Orchestrator analyzes and delegates
subagents spawn tech-lead
"Design architecture for feedback analysis dashboard
- React frontend with data visualization
- Python backend with NLP sentiment analysis
- Database schema for feedback storage
- API design for frontend-backend communication"
# Tech-lead further delegates to specialists
subagents spawn backend-dev
"Implement Python FastAPI backend:
- Sentiment analysis endpoint using transformers
- CRUD operations for feedback data
- Database models with SQLAlchemy
- Authentication and rate limiting"
subagents spawn frontend-dev
"Build React dashboard:
- Responsive layout with Tailwind CSS
- Charts using Chart.js or D3
- Real-time updates via WebSocket
- Filtering and search functionality"
subagents spawn test-engineer
"Create comprehensive test suite:
- Unit tests for backend API endpoints
- Integration tests for database operations
- Frontend component testing with Jest
- End-to-end testing with Playwright"
Advanced Patterns:
# Conditional spawning based on results
if research_findings.confidence_score < 0.8:
subagents spawn fact-checker
"Verify claims in research report: ${findings_file}"
# Sequential dependency chains
research_done = subagents spawn research-lead --wait
design_done = subagents spawn ui-designer
"Design based on: ${research_done.output_file}" --wait
subagents spawn frontend-dev
"Implement: ${design_done.mockups}"
# Parallel execution with synchronization
content_team = [
subagents spawn writer --label "content-writer",
subagents spawn editor --label "content-editor",
subagents spawn designer --label "visual-designer"
]
subagents wait content_team
subagents spawn publisher "Combine all content outputs"
Monitoring & Control:
# Check all running sub-agents
subagents list
┌─────────────┬──────────────┬─────────┬──────────┬─────────────┐
│ ID │ Label │ Status │ Runtime │ Progress │
├─────────────┼──────────────┼─────────┼──────────┼─────────────┤
│ research-01 │ literature │ running │ 5min 23s │ 📚 Paper 15/30 │
│ code-rev-02 │ backend │ running │ 2min 45s │ 🔍 Function 8/12│
│ writer-03 │ documentation│ done │ 12min 3s │ ✅ Complete │
└─────────────┴──────────────┴─────────┴──────────┴─────────────┘
# Steer agent in new direction
subagents steer research-01
"Focus on papers with code implementations"
# Kill stuck or unnecessary agents
subagents kill code-rev-02
# Get detailed status
subagents status research-01 --verbose
⚡ Performance Tips
Timeouts: ตั้ง reasonable timeout เพื่อป้องกัน stuck agents
Labels: ใช้ meaningful labels เพื่อ tracking ง่าย
Resource Limits: จำกัดจำนวน concurrent agents ตาม server capacity
Progress Monitoring: Check status เป็นระยะ แทน busy-wait polling
7. Communication Patterns
Agent-to-agent communication เป็นหัวใจสำคัญของ multi-agent system การ design communication patterns ที่ดีจะทำให้ทีม agents ทำงานร่วมกันได้อย่างมีประสิทธิภาพ
🔄 Message Passing Patterns:
# Direct messaging between agents
sessions_send code-reviewer
"Please review the changes in commit abc123f"
# Broadcasting to multiple agents
sessions_broadcast writing-team
"Style guide updated: use active voice, 1500-word max"
# Status updates with structured data
sessions_send orchestrator
"{
'task': 'backend-development',
'status': 'completed',
'output_file': './src/api.py',
'test_coverage': 95,
'next_steps': ['frontend-integration', 'deployment']
}"
📁 File-based Communication:
Agents share artifacts ผ่าน workspace files ซึ่งเป็นวิธีที่ reliable และ persistent:
# Research agent outputs structured findings
research-lead → outputs/research_findings.json
{
"topic": "transformer optimization",
"papers": [...],
"key_insights": [...],
"recommendations": [...]
}
# Writing agent consumes research data
technical-writer → read outputs/research_findings.json
technical-writer → generates/technical_report.md
# Code agents share implementation artifacts
backend-dev → src/models/transformer.py
frontend-dev → read src/models/ (for API integration)
test-engineer → tests/test_transformer.py (based on implementation)
🧠 Shared Memory Patterns:
Memory sharing ช่วยให้ agents สามารถเรียนรู้จากการทำงานของกันและกัน และ maintain context ระหว่าง sessions:
# Memory layered by scope
Global Memory: Company coding standards, style guides
Project Memory: Current project context, decisions made
Team Memory: Team-specific patterns, lessons learned
Agent Memory: Individual agent's learning and preferences
# Cross-pollination examples
code-reviewer learns from previous reviews → improves suggestions
research-lead remembers effective search strategies → better results
writer adapts style based on feedback → consistent voice
⚙️ Workflow Coordination:
# State-based coordination
Project State: "research" → "design" → "implementation" → "testing" → "deployment"
# Event-driven triggers
on research_complete:
spawn technical-writer "Write implementation guide"
spawn ui-designer "Create user interface mockups"
on code_review_passed:
spawn test-engineer "Run comprehensive test suite"
spawn docs-writer "Update API documentation"
# Dependency management
backend_api.depends_on(database_schema, auth_system)
frontend_ui.depends_on(backend_api, design_mockups)
deployment.depends_on(backend_api, frontend_ui, tests_passed)
🔗 Communication Best Practices
Structured Messages: ใช้ JSON หรือ YAML สำหรับ complex data
File Conventions: ตั้งชื่อไฟล์และ directory structure ให้ชัดเจน
Status Updates: ส่ง progress reports เป็นระยะ
Error Handling: มี fallback mechanism เมื่อ communication ล้มเหลว
8. ตัวอย่างจริง: Coding Team Pipeline
มาดูตัวอย่างการทำงานของ Coding Team ตั้งแต่เริ่มต้นจนเสร็จสิ้น เพื่อให้เห็นภาพรวมของ multi-agent workflow:
📋 Initial Request:
User: "สร้าง API สำหรับ sentiment analysis ของ customer feedback พร้อม dashboard แสดงผล"
🎯 Step 1: Tech Lead Planning
# Tech Lead Agent (Opus) analyzes requirements
Analysis:
- Backend API: Python FastAPI + transformers library
- Database: PostgreSQL for feedback storage
- Frontend: React dashboard with Chart.js
- Infrastructure: Docker containerization
- Testing: Unit + integration + E2E tests
Architecture Decision:
- Microservices approach: API + Dashboard + DB
- CI/CD pipeline with GitHub Actions
- Monitoring with logging and metrics
# Output: architecture_plan.md
⚡ Step 2: Parallel Delegation
# Tech Lead spawns specialized agents simultaneously
subagents spawn backend-dev
"Implement FastAPI backend for sentiment analysis:
- Endpoint: POST /analyze with text input
- Use huggingface transformers (sentiment-pipeline)
- PostgreSQL models with SQLAlchemy
- Async processing for large batches
- Input validation and error handling
- OpenAPI documentation generation"
subagents spawn frontend-dev
"Build React sentiment dashboard:
- Text input form for new feedback analysis
- Real-time chart showing sentiment distribution
- Historical trends visualization
- Responsive design with Tailwind CSS
- API integration with error handling
- Loading states and user feedback"
subagents spawn db-specialist
"Design database schema:
- feedback table: id, text, sentiment, confidence, timestamp
- users table: id, name, email (if needed)
- indexes for performance on timestamp queries
- Migration scripts with Alembic
- Sample data for testing"
subagents spawn devops-engineer
"Setup deployment infrastructure:
- Dockerfile for FastAPI backend
- Docker-compose for local development
- GitHub Actions CI/CD pipeline
- Environment configuration management
- Health check endpoints"
🔄 Step 3: Parallel Development (30 minutes)
# Backend Developer Output
Files Created:
- src/main.py (FastAPI application)
- src/models.py (SQLAlchemy models)
- src/sentiment.py (sentiment analysis logic)
- src/database.py (database connection)
- requirements.txt (dependencies)
- .env.example (environment template)
# Frontend Developer Output
Files Created:
- src/App.js (main dashboard component)
- src/components/SentimentChart.js
- src/components/FeedbackForm.js
- src/api/sentimentApi.js (API client)
- package.json (dependencies)
- tailwind.config.js (styling setup)
# Database Specialist Output
Files Created:
- migrations/001_initial_schema.sql
- migrations/002_add_indexes.sql
- scripts/seed_sample_data.sql
- database_design.md (documentation)
# DevOps Engineer Output
Files Created:
- Dockerfile (backend container)
- docker-compose.yml (full stack)
- .github/workflows/ci.yml (CI pipeline)
- deploy.sh (deployment script)
🔍 Step 4: Code Review & Integration
# Tech Lead spawns code reviewer
subagents spawn code-reviewer
"Review all code from backend, frontend, and devops teams:
- Check adherence to coding standards
- Security vulnerabilities scan
- Performance optimization suggestions
- Integration compatibility review
- Documentation completeness check"
# Code Reviewer Findings
Issues Found:
- Backend: Missing input validation on text length
- Frontend: No error boundary for API failures
- Database: Missing foreign key constraints
- DevOps: Production secrets hardcoded
Recommendations:
- Add pydantic validators for input
- Implement React error boundaries
- Update database schema with constraints
- Use environment variables for secrets
🧪 Step 5: Testing & Quality Assurance
# Spawn testing agents after code review fixes
subagents spawn test-engineer
"Create comprehensive test suite:
- Backend: pytest with test_main.py, test_sentiment.py
- Frontend: Jest tests for components
- Integration: API endpoint testing
- E2E: Playwright full user journey tests
- Performance: Load testing with locust"
subagents spawn docs-writer
"Generate project documentation:
- API documentation from OpenAPI spec
- Frontend component documentation
- Deployment guide with step-by-step instructions
- User manual for dashboard usage
- Developer setup guide"
✅ Step 6: Final Integration & Delivery
# Tech Lead coordinates final assembly
Integration Tasks:
- Merge all code into main repository
- Run complete test suite (all tests pass ✅)
- Deploy to staging environment
- Smoke test critical user journeys
- Generate final project report
# Deliverables
Output Files:
- sentiment_analysis_api/ (complete codebase)
- docker-compose.yml (one-command setup)
- README.md (comprehensive setup guide)
- API_DOCS.md (endpoint documentation)
- USER_GUIDE.md (dashboard usage)
- deployment_report.pdf (project summary)
# Total Time: ~45 minutes (vs 2-3 days for single developer)
# Quality: Enterprise-grade with comprehensive testing
🚀 Pipeline Benefits
Speed: 8x faster than sequential development
Quality: Built-in code review and testing from start
Consistency: Standardized patterns across all components
Documentation: Generated automatically, always up-to-date
Knowledge Transfer: Complete project context preserved in memory
9. ข้อจำกัดและ Lessons Learned
หลังจากใช้งาน multi-agent systems ในโปรเจ็กต์จริงมาหลายเดือน เราได้เรียนรู้ข้อจำกัดและ challenges ที่ควรรู้ก่อนลงมือทำ:
🔒 Sandbox Limitations
Isolation Problems: Sub-agents ทำงานใน sandbox environments ที่แยกจากกัน ทำให้การ share state และ coordinate ซับซ้อน
- File sharing ผ่าน workspace เท่านั้น — ไม่มี shared memory โดยตรง
- Network access จำกัด — ไม่สามารถ connect กับ external services ได้ทั้งหมด
- Process isolation — agents ไม่สามารถ monitor หรือ control กันโดยตรง
# Workaround patterns ที่ใช้ได้
File-based coordination: agents write status to shared files
Message queues: use workspace files as message buffers
Polling strategies: periodic check for updates (not ideal)
Gateway coordination: main agent as message broker
💾 Memory Isolation Issues
Context Loss: แต่ละ agent มี memory context ของตัวเอง ทำให้ transfer knowledge ระหว่าง agents ไม่ seamless
- Agent A เรียนรู้ pattern ใหม่ แต่ Agent B ไม่ได้รับ knowledge นี้
- Conversation history ไม่ carry over ระหว่าง different agents
- Global project context ต้อง manually maintain
# Memory sharing strategies
Explicit context passing: include relevant memory in spawn messages
Shared knowledge files: maintain project_context.md
Memory consolidation: periodic sync sessions between agents
Vector embeddings: use semantic search for knowledge retrieval
💰 Cost Control Challenges
Exponential Cost Growth: Multi-agent systems สามารถกิน API costs เป็น exponential ถ้าไม่ระวัง
- Agent spawning ที่ไม่มี upper bounds
- Recursive delegation ที่ไม่มี termination conditions
- Over-communication between agents
- Inefficient prompt engineering ที่ใช้ token มากเกินไป
# Cost control measures
Max concurrent agents: limit to 5-10 simultaneously
Budget per task: set token limits for each spawned agent
Smart caching: reuse responses for similar tasks
Model tiering: use cheaper models for routine tasks
Monitoring: track costs in real-time with alerts
🤖 When NOT to Use Multi-Agent
Multi-agent architecture ไม่ใช่ silver bullet บางครั้งการใช้ single agent หรือ traditional approach ดีกว่า:
❌ Over-engineering Scenarios:
- Simple tasks: การแปล 1 ประโยค ไม่ต้องการ translation team
- Linear workflows: งานที่ต้องทำทีละขั้นตอน sequential
- Single-domain tasks: งานที่ไม่ต้องการ cross-functional expertise
- Time-sensitive: การ setup agents อาจช้ากว่าทำเองโดยตรง
- Low-stakes outputs: draft emails, quick notes ใช้ simple agent พอ
# Decision Framework
Use Multi-Agent When:
✅ Task complexity > 30 minutes of work
✅ Requires multiple skill sets
✅ Quality is critical (code, research, publications)
✅ Parallel execution provides benefits
✅ Ongoing project with multiple iterations
Use Single Agent When:
❌ Task duration < 5 minutes
❌ Single domain expertise sufficient
❌ Quick draft or exploratory work
❌ Simple Q&A or information lookup
❌ Real-time conversation requirements
🔧 Technical Complexity
Debugging Nightmares: เมื่อมี 8 agents ทำงานพร้อมกัน การ debug ปัญหาซับซ้อนมาก
- ไม่รู้ว่าปัญหามาจาก agent ไหน
- Logs กระจัดกระจายใน multiple sessions
- Timing issues และ race conditions
- Dependency hell ระหว่าง agents
🎯 Best Practices from Experience
Start Small: เริ่มด้วย 2-3 agents ก่อนขยาย
Clear Boundaries: กำหนด responsibilities อย่างชัดเจน
Monitoring: implement comprehensive logging และ status tracking
Fallback Plans: มี single-agent backup สำหรับ critical tasks
Regular Reviews: ประเมิน team performance และปรับปรุงเป็นระยะ
10. Key Takeaways
🎯 สิ่งสำคัญที่ควรจำ
1. Why One Agent Is Not Enough
Now that we have met OpenClaw in the first post, you have probably started using a single agent and found yourself thinking "okay, this is good, but…" — because something is still not right, is it?
The generalist AI problem: one agent that has to do everything is like one person being programmer, researcher, writer, designer and project manager all at once. It is good at many things, but not truly expert at any of them.
Consider what that costs:
- Task Switching Overhead: moving from coding mode to research mode to writing mode means a context switch every single time
- Quality Inconsistency: sometimes it writes good code, sometimes it writes a good research paper — but never dependably
- Memory Conflicts: context belonging to a coding project can interfere with research in an entirely different domain
- Prompt Engineering Complexity: the more jobs you hand it, the more tangled the instructions become — and sometimes confusing
This is exactly why no real company puts one employee on everything — they build teams of specialists instead
🎯 Specialist vs Generalist
Research in cognitive science tells us that specialized agents with focused context and clear responsibilities deliver better output quality than a general-purpose agent that has to switch context over and over.
2. Multi-Agent Architecture — How the Work Gets Divided
Multi-Agent Architecture is not simply having several AIs around. It is designing a system of intelligent agents in which each one has a specialization and they collaborate to get complex work done
Core Concepts:
🎭 Agent Specialization: each agent carries the domain expertise and the personality that its work calls for — a research agent that is strong at finding and synthesizing information, say, or a code-review agent with a deep grasp of coding standards
🎯 Orchestrator Pattern: a main agent, or orchestrator, acts as project manager: it takes the request from the user, breaks it into subtasks, and delegates each one to the right specialist
📡 Communication Protocol: agents talk to each other through structured messages, shared files in the workspace, and shared memory — so knowledge earned on one job can be spent on another
🧠 Collective Intelligence: the team's combined result is usually better than what a single agent produces, because of the diverse perspectives and specialized knowledge in the room
Compared with a team of people:
| Aspect | Human Team | Agent Team | Advantages |
|---|---|---|---|
| Specialization | Years of training & experience | Model + prompt engineering + memory | Instant expertise, no learning curve |
| Communication | Meetings, Slack, email | sessions_send, workspace files | Zero latency, perfect information transfer |
| Memory | Individual notes, documents | Shared memory system, vector search | Perfect recall, searchable knowledge |
| Availability | 8 hours/day, sick days | 24/7, no downtime | Always available, no human limitations |
| Scalability | Linear cost per person | API costs, parallel execution | Can spawn multiple instances instantly |
| Quality Control | Code review, peer feedback | Cross-agent validation, automated QA | Consistent standards, no emotional bias |
3. Agent Team Architecture
🏗️ Multi-Agent Flow Architecture
"Build a feature"
Receives & analyzes
Plans & delegates
Execute subtasks
Combine results
OpenClaw Multi-Agent Implementation:
📊 sessions_spawn: the main function for creating sub-agents — you give it a label, a model, instructions, and a mode (run vs session)
# Spawn specialized agents
subagents spawn research-lead "Academic research on transformer optimization"
subagents spawn code-review "Review Python ML pipeline code"
subagents spawn docs-writer "Document API endpoints"
# Check running agents
subagents list
# Steer agent direction
subagents steer research-lead "Focus on recent 2024 papers"
# Terminate when done
subagents kill docs-writer
🔄 Workflow Orchestration: the main agent takes a complex request → breaks it into subtasks → spawns the appropriate specialists → monitors progress → combines the results → delivers the final output
💾 Memory Sharing: agents share workspace files and the memory system, so what the research agent produces is available to the writing agent
⚡ Parallel Execution: multiple agents working in parallel cut total execution time dramatically
4. Designing a Team — Real Examples
From using OpenClaw across a number of organizations, we have identified the team patterns that are effective and hold up in practice. These are the five core teams that have proven themselves:
✍️ Writing Team (8 agents)
- editor-chief - content strategy & oversight Opus
- research-writer - factual content creation Sonnet
- copywriter - marketing & persuasive copy Sonnet
- technical-writer - documentation & guides Sonnet
- translator - multi-language content Sonnet
- proofreader - grammar & style checks Sonnet
- seo-optimizer - search optimization Sonnet
- fact-checker - verification & citations Opus
🔬 Academic Team (10 agents)
- research-lead - project coordination Opus
- literature-reviewer - paper analysis Opus
- methodology-expert - experimental design Opus
- data-analyst - statistical analysis Sonnet
- paper-writer - manuscript drafting Sonnet
- citation-manager - references & bibliography Sonnet
- peer-reviewer - quality assurance Opus
- visual-designer - figures & charts Sonnet
- submission-manager - journal formatting Sonnet
- grant-writer - funding proposals Opus
💻 Coding Team (8 agents)
- tech-lead - architecture & planning Opus
- code-reviewer - quality & standards Opus
- backend-dev - API & server logic Sonnet
- frontend-dev - UI & client-side Sonnet
- db-specialist - database design & queries Sonnet
- test-engineer - automated testing Sonnet
- devops-engineer - deployment & CI/CD Sonnet
- docs-writer - technical documentation Sonnet
🎓 Course Team (10 agents)
- curriculum-designer - learning objectives Opus
- content-creator - lesson materials Sonnet
- slide-builder - presentation design Sonnet
- exercise-writer - practice problems Sonnet
- quiz-generator - assessments Sonnet
- video-scripter - lecture scripts Sonnet
- handout-writer - study guides Sonnet
- accessibility-expert - inclusive design Sonnet
- learning-analyst - pedagogy optimization Opus
- quality-reviewer - content validation Opus
🌐 Translation Team (8 agents)
- translation-lead - project coordination Opus
- english-translator - EN translation Sonnet
- thai-translator - TH translation Sonnet
- chinese-translator - ZH translation Sonnet
- cultural-adapter - localization Sonnet
- quality-checker - accuracy review Opus
- style-harmonizer - consistency Sonnet
- technical-validator - domain accuracy Sonnet
🎨 Team Design Principles
Clear Roles: every agent has one specific responsibility, with no overlap
Model Matching: Opus for complex reasoning, Sonnet for execution
Quality Gates: reviewer agents in place for quality control
Scalability: add or remove agents as the workload demands
5. Model Routing & Cost Optimization
One of the decisive questions in a multi-agent architecture is picking the right AI model for each job — good quality at a cost that stays reasonable
Model Selection Strategy:
🧠 Claude Opus (Complex Reasoning):
- Orchestrator agents that have to plan and divide the work
- Code review and architecture decisions
- Research coordination and methodology design
- Quality assurance and final review
- Complex problem solving and creative tasks
⚡ Claude Sonnet (Execution & Routine):
- Content writing and documentation
- Code implementation and testing
- Data processing and analysis
- Translation and formatting
- Repetitive tasks and standard procedures
| Use Case | Model Choice | Cost per 1K tokens | Reasoning |
|---|---|---|---|
| Project Planning | Claude Opus | $0.015 / $0.075 | Needs strategic thinking |
| Code Writing | Claude Sonnet | $0.003 / $0.015 | Clear specifications, execution-focused |
| Code Review | Claude Opus | $0.015 / $0.075 | Critical analysis, pattern recognition |
| Documentation | Claude Sonnet | $0.003 / $0.015 | Structured, predictable output |
| Research Synthesis | Claude Opus | $0.015 / $0.075 | Complex reasoning, connections |
| Content Translation | Claude Sonnet | $0.003 / $0.015 | Pattern-based, well-defined task |
Cost Analysis Example (Monthly):
# Organization with active agent teams
Research Team: ~200K tokens/day × 30 days × $0.045 avg = $270/month
Coding Team: ~150K tokens/day × 22 workdays × $0.025 avg = $82.5/month
Writing Team: ~100K tokens/day × 30 days × $0.020 avg = $60/month
# Total estimated monthly cost: ~$412.5
# Compared to 2 full-time employees: ~$8,000+/month
ROI: 20x cost savings with 24/7 availability
Cost Optimization Strategies:
- Smart Caching: keep common responses and reuse them when a similar query turns up
- Batch Processing: group similar tasks so one agent handles them together
- Progressive Enhancement: start with Sonnet and escalate to Opus only when you have to
- Context Optimization: strip unnecessary context out of prompts
- Task Complexity Assessment: size up the work before choosing the model
6. sessions_spawn in Practice
Spawning sub-agents is the core feature that gives OpenClaw its multi-agent capabilities. These are the patterns and best practices that came out of real use:
Basic Spawning Patterns:
# run-and-return style (fire-and-forget)
subagents spawn research-lead
"Research transformer optimization papers from 2024"
--mode run --timeout 600
# interactive session style
subagents spawn code-reviewer
"Review the ML pipeline code in ./src/"
--mode session --label "code-review-v1"
# batch processing style
subagents spawn translator
"Translate all .md files in ./docs/ to Thai"
--mode run --label "docs-translation"
Orchestrator Delegation Example:
# Main orchestrator receives complex request
User: "Build a customer feedback analysis dashboard"
# Orchestrator analyzes and delegates
subagents spawn tech-lead
"Design architecture for feedback analysis dashboard
- React frontend with data visualization
- Python backend with NLP sentiment analysis
- Database schema for feedback storage
- API design for frontend-backend communication"
# Tech-lead further delegates to specialists
subagents spawn backend-dev
"Implement Python FastAPI backend:
- Sentiment analysis endpoint using transformers
- CRUD operations for feedback data
- Database models with SQLAlchemy
- Authentication and rate limiting"
subagents spawn frontend-dev
"Build React dashboard:
- Responsive layout with Tailwind CSS
- Charts using Chart.js or D3
- Real-time updates via WebSocket
- Filtering and search functionality"
subagents spawn test-engineer
"Create comprehensive test suite:
- Unit tests for backend API endpoints
- Integration tests for database operations
- Frontend component testing with Jest
- End-to-end testing with Playwright"
Advanced Patterns:
# Conditional spawning based on results
if research_findings.confidence_score < 0.8:
subagents spawn fact-checker
"Verify claims in research report: ${findings_file}"
# Sequential dependency chains
research_done = subagents spawn research-lead --wait
design_done = subagents spawn ui-designer
"Design based on: ${research_done.output_file}" --wait
subagents spawn frontend-dev
"Implement: ${design_done.mockups}"
# Parallel execution with synchronization
content_team = [
subagents spawn writer --label "content-writer",
subagents spawn editor --label "content-editor",
subagents spawn designer --label "visual-designer"
]
subagents wait content_team
subagents spawn publisher "Combine all content outputs"
Monitoring & Control:
# Check all running sub-agents
subagents list
┌─────────────┬──────────────┬─────────┬──────────┬─────────────┐
│ ID │ Label │ Status │ Runtime │ Progress │
├─────────────┼──────────────┼─────────┼──────────┼─────────────┤
│ research-01 │ literature │ running │ 5min 23s │ 📚 Paper 15/30 │
│ code-rev-02 │ backend │ running │ 2min 45s │ 🔍 Function 8/12│
│ writer-03 │ documentation│ done │ 12min 3s │ ✅ Complete │
└─────────────┴──────────────┴─────────┴──────────┴─────────────┘
# Steer agent in new direction
subagents steer research-01
"Focus on papers with code implementations"
# Kill stuck or unnecessary agents
subagents kill code-rev-02
# Get detailed status
subagents status research-01 --verbose
⚡ Performance Tips
Timeouts: set a sensible timeout so no agent can get stuck
Labels: use meaningful labels to make tracking easy
Resource Limits: cap concurrent agents to what your server can carry
Progress Monitoring: check status periodically rather than busy-wait polling
7. Communication Patterns
Agent-to-agent communication is the heart of a multi-agent system. Design the communication patterns well and the team of agents genuinely works together
🔄 Message Passing Patterns:
# Direct messaging between agents
sessions_send code-reviewer
"Please review the changes in commit abc123f"
# Broadcasting to multiple agents
sessions_broadcast writing-team
"Style guide updated: use active voice, 1500-word max"
# Status updates with structured data
sessions_send orchestrator
"{
'task': 'backend-development',
'status': 'completed',
'output_file': './src/api.py',
'test_coverage': 95,
'next_steps': ['frontend-integration', 'deployment']
}"
📁 File-based Communication:
Agents share artifacts through workspace files — a method that is both reliable and persistent:
# Research agent outputs structured findings
research-lead → outputs/research_findings.json
{
"topic": "transformer optimization",
"papers": [...],
"key_insights": [...],
"recommendations": [...]
}
# Writing agent consumes research data
technical-writer → read outputs/research_findings.json
technical-writer → generates/technical_report.md
# Code agents share implementation artifacts
backend-dev → src/models/transformer.py
frontend-dev → read src/models/ (for API integration)
test-engineer → tests/test_transformer.py (based on implementation)
🧠 Shared Memory Patterns:
Memory sharing lets agents learn from each other's work and hold context across sessions:
# Memory layered by scope
Global Memory: Company coding standards, style guides
Project Memory: Current project context, decisions made
Team Memory: Team-specific patterns, lessons learned
Agent Memory: Individual agent's learning and preferences
# Cross-pollination examples
code-reviewer learns from previous reviews → improves suggestions
research-lead remembers effective search strategies → better results
writer adapts style based on feedback → consistent voice
⚙️ Workflow Coordination:
# State-based coordination
Project State: "research" → "design" → "implementation" → "testing" → "deployment"
# Event-driven triggers
on research_complete:
spawn technical-writer "Write implementation guide"
spawn ui-designer "Create user interface mockups"
on code_review_passed:
spawn test-engineer "Run comprehensive test suite"
spawn docs-writer "Update API documentation"
# Dependency management
backend_api.depends_on(database_schema, auth_system)
frontend_ui.depends_on(backend_api, design_mockups)
deployment.depends_on(backend_api, frontend_ui, tests_passed)
🔗 Communication Best Practices
Structured Messages: use JSON or YAML for complex data
File Conventions: keep file names and directory structure unambiguous
Status Updates: send progress reports at intervals
Error Handling: have a fallback mechanism for when communication fails
8. A Real Example: The Coding Team Pipeline
Let us walk a Coding Team through a job from start to finish, so the shape of a multi-agent workflow becomes concrete:
📋 Initial Request:
User: "Build an API for sentiment analysis of customer feedback, with a dashboard to display the results"
🎯 Step 1: Tech Lead Planning
# Tech Lead Agent (Opus) analyzes requirements
Analysis:
- Backend API: Python FastAPI + transformers library
- Database: PostgreSQL for feedback storage
- Frontend: React dashboard with Chart.js
- Infrastructure: Docker containerization
- Testing: Unit + integration + E2E tests
Architecture Decision:
- Microservices approach: API + Dashboard + DB
- CI/CD pipeline with GitHub Actions
- Monitoring with logging and metrics
# Output: architecture_plan.md
⚡ Step 2: Parallel Delegation
# Tech Lead spawns specialized agents simultaneously
subagents spawn backend-dev
"Implement FastAPI backend for sentiment analysis:
- Endpoint: POST /analyze with text input
- Use huggingface transformers (sentiment-pipeline)
- PostgreSQL models with SQLAlchemy
- Async processing for large batches
- Input validation and error handling
- OpenAPI documentation generation"
subagents spawn frontend-dev
"Build React sentiment dashboard:
- Text input form for new feedback analysis
- Real-time chart showing sentiment distribution
- Historical trends visualization
- Responsive design with Tailwind CSS
- API integration with error handling
- Loading states and user feedback"
subagents spawn db-specialist
"Design database schema:
- feedback table: id, text, sentiment, confidence, timestamp
- users table: id, name, email (if needed)
- indexes for performance on timestamp queries
- Migration scripts with Alembic
- Sample data for testing"
subagents spawn devops-engineer
"Setup deployment infrastructure:
- Dockerfile for FastAPI backend
- Docker-compose for local development
- GitHub Actions CI/CD pipeline
- Environment configuration management
- Health check endpoints"
🔄 Step 3: Parallel Development (30 minutes)
# Backend Developer Output
Files Created:
- src/main.py (FastAPI application)
- src/models.py (SQLAlchemy models)
- src/sentiment.py (sentiment analysis logic)
- src/database.py (database connection)
- requirements.txt (dependencies)
- .env.example (environment template)
# Frontend Developer Output
Files Created:
- src/App.js (main dashboard component)
- src/components/SentimentChart.js
- src/components/FeedbackForm.js
- src/api/sentimentApi.js (API client)
- package.json (dependencies)
- tailwind.config.js (styling setup)
# Database Specialist Output
Files Created:
- migrations/001_initial_schema.sql
- migrations/002_add_indexes.sql
- scripts/seed_sample_data.sql
- database_design.md (documentation)
# DevOps Engineer Output
Files Created:
- Dockerfile (backend container)
- docker-compose.yml (full stack)
- .github/workflows/ci.yml (CI pipeline)
- deploy.sh (deployment script)
🔍 Step 4: Code Review & Integration
# Tech Lead spawns code reviewer
subagents spawn code-reviewer
"Review all code from backend, frontend, and devops teams:
- Check adherence to coding standards
- Security vulnerabilities scan
- Performance optimization suggestions
- Integration compatibility review
- Documentation completeness check"
# Code Reviewer Findings
Issues Found:
- Backend: Missing input validation on text length
- Frontend: No error boundary for API failures
- Database: Missing foreign key constraints
- DevOps: Production secrets hardcoded
Recommendations:
- Add pydantic validators for input
- Implement React error boundaries
- Update database schema with constraints
- Use environment variables for secrets
🧪 Step 5: Testing & Quality Assurance
# Spawn testing agents after code review fixes
subagents spawn test-engineer
"Create comprehensive test suite:
- Backend: pytest with test_main.py, test_sentiment.py
- Frontend: Jest tests for components
- Integration: API endpoint testing
- E2E: Playwright full user journey tests
- Performance: Load testing with locust"
subagents spawn docs-writer
"Generate project documentation:
- API documentation from OpenAPI spec
- Frontend component documentation
- Deployment guide with step-by-step instructions
- User manual for dashboard usage
- Developer setup guide"
✅ Step 6: Final Integration & Delivery
# Tech Lead coordinates final assembly
Integration Tasks:
- Merge all code into main repository
- Run complete test suite (all tests pass ✅)
- Deploy to staging environment
- Smoke test critical user journeys
- Generate final project report
# Deliverables
Output Files:
- sentiment_analysis_api/ (complete codebase)
- docker-compose.yml (one-command setup)
- README.md (comprehensive setup guide)
- API_DOCS.md (endpoint documentation)
- USER_GUIDE.md (dashboard usage)
- deployment_report.pdf (project summary)
# Total Time: ~45 minutes (vs 2-3 days for single developer)
# Quality: Enterprise-grade with comprehensive testing
🚀 Pipeline Benefits
Speed: 8x faster than sequential development
Quality: Built-in code review and testing from start
Consistency: Standardized patterns across all components
Documentation: Generated automatically, always up-to-date
Knowledge Transfer: Complete project context preserved in memory
9. Limitations and Lessons Learned
After several months of running multi-agent systems on real projects, we have learned the limitations and the challenges worth knowing before you begin:
🔒 Sandbox Limitations
Isolation Problems: sub-agents run in sandbox environments that are separated from one another, which makes sharing state and coordinating harder than it looks
- File sharing happens through the workspace only — there is no direct shared memory
- Network access is limited — agents cannot reach every external service
- Process isolation — agents cannot monitor or control each other directly
# Workaround patterns that do work
File-based coordination: agents write status to shared files
Message queues: use workspace files as message buffers
Polling strategies: periodic check for updates (not ideal)
Gateway coordination: main agent as message broker
💾 Memory Isolation Issues
Context Loss: every agent has its own memory context, so transferring knowledge between agents is never seamless
- Agent A learns a new pattern, but Agent B never receives that knowledge
- Conversation history does not carry over between different agents
- Global project context has to be maintained by hand
# Memory sharing strategies
Explicit context passing: include relevant memory in spawn messages
Shared knowledge files: maintain project_context.md
Memory consolidation: periodic sync sessions between agents
Vector embeddings: use semantic search for knowledge retrieval
💰 Cost Control Challenges
Exponential Cost Growth: a multi-agent system can eat API budget exponentially if you are not careful
- Agent spawning with no upper bounds
- Recursive delegation with no termination conditions
- Over-communication between agents
- Inefficient prompt engineering that burns far too many tokens
# Cost control measures
Max concurrent agents: limit to 5-10 simultaneously
Budget per task: set token limits for each spawned agent
Smart caching: reuse responses for similar tasks
Model tiering: use cheaper models for routine tasks
Monitoring: track costs in real-time with alerts
🤖 When NOT to Use Multi-Agent
Multi-agent architecture is not a silver bullet. Sometimes a single agent, or a traditional approach, is simply better:
❌ Over-engineering Scenarios:
- Simple tasks: translating one sentence does not call for a translation team
- Linear workflows: work that has to proceed one sequential step at a time
- Single-domain tasks: work that needs no cross-functional expertise
- Time-sensitive: setting the agents up may take longer than doing it yourself
- Low-stakes outputs: draft emails and quick notes — a simple agent is plenty
# Decision Framework
Use Multi-Agent When:
✅ Task complexity > 30 minutes of work
✅ Requires multiple skill sets
✅ Quality is critical (code, research, publications)
✅ Parallel execution provides benefits
✅ Ongoing project with multiple iterations
Use Single Agent When:
❌ Task duration < 5 minutes
❌ Single domain expertise sufficient
❌ Quick draft or exploratory work
❌ Simple Q&A or information lookup
❌ Real-time conversation requirements
🔧 Technical Complexity
Debugging Nightmares: when eight agents are working at once, debugging a problem gets very hard
- You do not know which agent the problem came from
- Logs are scattered across multiple sessions
- Timing issues and race conditions
- Dependency hell between agents
🎯 Best Practices from Experience
Start Small: begin with 2-3 agents before scaling up
Clear Boundaries: define responsibilities unambiguously
Monitoring: implement comprehensive logging and status tracking
Fallback Plans: keep a single-agent backup for critical tasks
Regular Reviews: assess team performance and improve it at intervals