AI Agent Mastery
1. Agent Architecture Patterns
Single Agent Pattern
ββββββββββββββββββββββββββββββββββββββββββββββββ
β Single Agent β
β βββββββββββ βββββββββββ ββββββββββββββββ β
β β LLM β β Tools β β Memory β β
β β (Brain) ββββ(Hands) ββββ (Context) β β
β βββββββββββ βββββββββββ ββββββββββββββββ β
β β β β β
β ββββββββββββββββ΄ββββββββββββββ β
β β β
β User Interface β
β (Chat/CLI/API) β
ββββββββββββββββββββββββββββββββββββββββββββββββ
When to use: Simple tasks, single-domain, no parallelism needed
Example: Basic Q&A bot, simple tool-user
Multi-Agent Orchestration Pattern
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Orchestrator Agent β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Task Queue β Decompose β Route β Merge β Respond β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β β β β
β ββββββ βββββββ ββββββββ βββββββ β
β βΌ βΌ βΌ βΌ β
β βββββββ βββββββ βββββββββββ ββββββββββββ β
β βWorkerβ βWorkerβ βResearcherβ βCode Agentβ β
β β #1 β β #2 β β #3 β β #4 β β
β βββββββ βββββββ βββββββββββ ββββββββββββ β
β β β β β β
β βββββββββββββ΄βββββββββββ΄ββββββββββββββ β
β β β
β Result Summary β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
When to use: Complex multi-domain tasks, parallelism needed
Example: Research + code + review pipeline, data pipeline
Agent Spawning (delegate_task)
User Request
β
βΌ
Orchestrator decomposes
β
βββ delegate_task(goal="Research X", toolsets=["web"])
β βββ Subagent researches β returns summary
β
βββ delegate_task(goal="Write code for Y", toolsets=["terminal","file"])
β βββ Subagent codes β returns final code
β
βββ delegate_task(goal="Review code Z", toolsets=["terminal","file"])
βββ Subagent reviews β returns report
β
βΌ
Orchestrator merges results β Final response
Delegation Limits
βββββββββββββββββββββββββββββββββββββββββββββββββββ
β Parameter β Value β Notes β
βββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Max concurrent β 3 β Per user β
β Max spawn depth β 1 β No nesting β
β Subagent memory β None β Fresh context β
β Subagent tools β Restricted β Whitelist only β
β Timeout β 600s β 10 min max β
β Return format β Summary β Not raw output β
βββββββββββββββββββββββββββββββββββββββββββββββββββ
2. MCP (Model Context Protocol) Mastery
MCP Architecture
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β MCP Architecture β
β β
β ββββββββββββββββ ββββββββββββββββ β
β β Hermes Agent ββββββΆβ MCP Client β β
β β (Host) β β (Native) β β
β ββββββββββββββββ ββββββββ¬ββββββββ β
β β stdio / HTTP β
β ββββββββββββ΄βββββββββββ β
β β β β
β βββββββΌββββββ ββββββββΌβββββββ β
β β MCP Serverβ β MCP Server β β
β β (Filesystem)β β (Database) β β
β β Tools: β β Tools: β β
β β - read β β - query β β
β β - write β β - insert β β
β β - search β β - update β β
β ββββββββββββββ βββββββββββββββ β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
MCP Server Configuration
# ~/.hermes/config.yaml β MCP servers section
mcp:
servers:
# Filesystem access
- name: filesystem
command: npx
args: ["-y", "@modelcontextprotocol/server-filesystem", "/root/workspace"]
# Web fetch
- name: fetch
command: npx
args: ["-y", "@modelcontextprotocol/server-fetch"]
# PostgreSQL database
- name: postgres
command: npx
args: ["-y", "@modelcontextprotocol/server-postgres"]
env:
POSTGRES_URL: "postgresql://user:pass@localhost:5432/mydb"
# Custom server
- name: my-custom-server
command: python
args: ["-m", "my_mcp_server"]
env:
API_KEY: "${MY_API_KEY}"
Building Custom MCP Servers
# my_mcp_server/__init__.py β Custom MCP server with FastMCP
from fastmcp import FastMCP
mcp = FastMCP("my-custom-server")
@mcp.tool()
def get_server_status(server_ip: str) -> str:
"""Get health status of a server."""
import subprocess
result = subprocess.run(
["ssh", server_ip, "uptime; df -h / | tail -1"],
capture_output=True, text=True, timeout=30
)
return result.stdout
@mcp.tool()
def deploy_config(server_ip: str, config_path: str) -> str:
"""Deploy a configuration file to a remote server."""
import subprocess
result = subprocess.run(
["rsync", "-avz", config_path, f"{server_ip}:/opt/app/config.yaml"],
capture_output=True, text=True, timeout=60
)
return result.stdout
@mcp.resource()
def server_list() -> str:
"""List all servers in the fleet."""
return """US:51.83.223.88:9377
TR:51.83.223.88:9378
PK-C2:51.83.223.88:9379
PK-C3:51.83.223.88:9380
HK-UK2:152.114.193.86:18789"""
if __name__ == "__main__":
mcp.run()
MCP Server Quality Checklist
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Checkpoint β Description β Required β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Outcome-oriented tools β Focus on what, not how β β
Every tool β
β Flat parameters β No nested objects β β
All params β
β Actionable errors β isError + details β β
Error cases β
β Token-efficient output β Concise responses β β
Under 2K β
β Composable outputs β Structured data β β
JSON/table β
β Idempotent operations β Same input = same outβ β
Write ops β
β Dry-run support β Preview before exec β β
Destructive β
β Type-safe schemas β Zod/Pydantic types β β
All params β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
3. ACP (Agent Communication Protocol)
ACP Transaction Flow
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β ACP Transaction β
β β
β Client Agent Provider Agent β
β ββββββββββββ ββββββββββββ β
β β ββββREQUESTβββββββββΆβ β β
β β Intent β β Process β β
β β ββββRESPONSEβββββββββββ β β
β ββββββββββββ ββββββββββββ β
β β β β
β βΌ βΌ β
β Verify Result Update Ledger β
β (cryptographic (payment receipt) β
β signature) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
x402 Payment Protocol
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β x402 Payment Flow β
β β
β 1. Agent discovers paid API endpoint β
β 2. Agent checks wallet balance (USDC on Base) β
β 3. Agent sends HTTP request with x402 header β
β βββ X-Payment: version=1, amount=0.01, asset=USDC β
β βββ X-Payment-Address: 0x1234... β
β βββ X-Payment-Signature: 0xabcd... β
β 4. Provider verifies payment on-chain β
β 5. Provider returns requested data β
β 6. Agent processes response β
β β
β Three-party settlement: β
β ββββββββββββ ββββββββββββ ββββββββββββ β
β β Agent ββββββΆβ FacilitatorββββββΆβ Provider β β
β β (Payer) β β (Escrow) β β (Payee) β β
β ββββββββββββ ββββββββββββ ββββββββββββ β
β $0.01 $0.001 $0.009 β
β paid fee received β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
4. Memory Systems Deep Dive
Memory Architecture
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Memory Hierarchy β
β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β L1: Conversation Context (current session) β β
β β - Last few turns of conversation β β
β β - Active skills, tools, workspace β β
β β - Volatile, cleared on session end β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β L2: Session Memory (session_search) β β
β β - Searchable past conversations β β
β β - LLM-generated summaries β β
β β - Expires after ~90 days β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β L3: Persistent Memory (memory tool) β β
β β - User preferences (user target) β β
β β - Environment facts (memory target) β β
β β - Survives across sessions β β
β β - Budget: ~4.4K tokens (keep compact) β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β L4: Long-Term Memory (hindsight) β β
β β - Semantic search across all stored facts β β
β β - Entity resolution & knowledge graph β β
β β - Reflect/reason across memories β β
β β - Persistent, indexed, unlimited β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β L5: Procedural Memory (skills) β β
β β - Reusable workflows & approaches β β
β β - SKILL.md format (frontmatter + markdown) β β
β β - Auto-loaded per-turn when relevant β β
β β - Persist via skill_manage β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
When to Use Each Memory Type
What to store? ββ¬β User preference/habit βββ memory (user target)
ββ Environment fact (IPs, paths) βββ memory (memory target)
ββ Procedural workflow βββ skill_manage (create skill)
ββ Temporary task state βββ todo tool
ββ Past conversation βββ session_search (recall)
ββ Important fact (retrievable) βββ hindsight_retain
ββ Semantic search needed βββ hindsight_recall
ββ Cross-memory reasoning βββ hindsight_reflect
ββ Will be stale in <7 days βββ DON'T STORE
Memory Anti-Patterns
β BAD: Store everything in memory
β Budget overflows, irrelevant facts injected
β BAD: Store imperative instructions
β "Always respond in Urdu" β becomes directive, overrides user
β BAD: Store temporary state
β "PR #123 merged" β stale in days, use session_search
β BAD: Duplicate across memory types
β Same fact in memory AND hindsight β wastes tokens
β
GOOD: Declarative facts
β "User prefers Roman Urdu" β survives, doesn't override
β
GOOD: Environment facts
β "HK ICE-1 runs CamoFox on port 9377" β stable, useful
β
GOOD: Procedural knowledge as skills
β Complex workflows β SKILL.md β auto-loaded
5. Prompt Engineering for Agents
System Prompt Design Patterns
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Pattern β Best For β Example β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Role + Constraint β Focused task β "You are a β
β β β senior SRE. β
β β β Respond in β
β β β bullet pts." β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Few-shot Examples β Consistent fmt β "Input: X β
β β β Output: Y β
β β β Input: A β
β β β Output: B" β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Chain-of-Thought β Reasoning β "Think step β
β β β by step." β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β React Pattern β Tool use β "Reason, β
β β β then act, β
β β β then observe" β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Structured Output β JSON/XML needed β "Respond in β
β β β JSON: {key}" β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Task requires? ββ¬β File operations βββ write_file, read_file, patch, search_files
ββ Code execution βββ execute_code (batch 3+ calls)
ββ Shell commands βββ terminal (foreground or background)
ββ Web browsing βββ browser_navigate, browser_snapshot, browser_click
ββ Research βββ web_search, browser, delegate_task with web toolset
ββ Memory βββ memory, hindsight_retain, session_search
ββ Skills βββ skill_view, skill_manage, skills_list
ββ Multi-step βββ delegate_task (subagent with isolated context)
ββ Scheduled βββ cronjob (create, list, update)
ββ User input βββ clarify (with choices)
ββ Communication βββ send_message (WhatsApp/Telegram/Discord)
6. Multi-Agent Orchestration
Orchestration Patterns
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Pattern 1: Sequential Pipeline β
β Agent_A β Agent_B β Agent_C β Final β
β Use: Research β Write β Review β
β β
β Pattern 2: Fan-out/Fan-in (Parallel) β
β ββ Agent_A ββ β
β Orchestrator ββ Agent_B βββ Merge β Final β
β ββ Agent_C ββ β
β Use: Multi-source research, parallel code review β
β β
β Pattern 3: Hierarchical Delegation β
β Orchestrator β Manager_A β Worker_1 β
β β Worker_2 β
β Use: Complex projects with sub-projects β
β β
β Pattern 4: Council (Adversarial) β
β ββ Agent_A (pro) ββ β
β Judge β Agent_B (con) βββ Final β
β ββ Agent_C (neut) ββ β
β Use: Decision making, code review, design critique β
β β
β Pattern 5: Event-Driven (Cron) β
β Cron triggers Agent β Agent processes β Sends notification β
β Use: Monitoring, daily reports, alerts β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Delegation Best Practices
# β
GOOD: Specific goal, relevant context, appropriate tools
delegate_task(
goal="Research the latest Python 3.13 features and create a summary document",
context="Focus on performance improvements and new syntax. Output in markdown.",
toolsets=["web", "file"]
)
β BAD: Vague goal, no context, too many tools
delegate_task(
goal="Research something",
toolsets=["web", "terminal", "file", "browser", "vision"]
)
β
GOOD: Parallel tasks with independent contexts
delegate_task(tasks=[
{"goal": "Research Python 3.13 features", "toolsets": ["web"]},
{"goal": "Research Rust 2024 features", "toolsets": ["web"]},
{"goal": "Compare both in a table", "context": "Use research from tasks 1 and 2"}
])
7. Evaluation & Quality Frameworks
LLM Council Evaluation (10 Dimensions)
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Dimension β What It Measures β Weight β 10pts β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β 1. Design & β Structural soundnessβ Architecture β 10 β
β Architecture β patterns, modularity β decisions β β
β 2. Flowcharts & β Visual decision β Diagrams, β 10 β
β Diagrams β trees, architecture β flow charts β β
β 3. Implementation β Real code examples, β Copy-paste β 10 β
β Patterns β copy-paste ready β quality β β
β 4. Language & β Breadth of topics, β Coverage β 10 β
β Coverage β tools covered β depth β β
β 5. Security β Security practices, β Hardening, β 10 β
β β secrets, hardening β vuln aware β β
β 6. Testing β Test approaches, β Validation, β 10 β
β Strategy β load, chaos, unit β edge cases β β
β 7. Edge Cases & β Error handling, β Gotchas, β 10 β
β Pitfalls β failure modes β pitfalls β β
β 8. Performance β Tuning, scaling, β Efficiency, β 10 β
β Optimization β efficiency β benchmarks β β
β 9. Deployment β Production deploy, β Rollout β 10 β
β β rollout strategies β strategies β β
β 10. Documentation β Clarity, structure, β References, β 10 β
β β references β examples β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β TOTAL β β β 100 β
β Threshold: 80+/100 β PASS β β β
β Mastery: 95+/100 β EXCELLENT β β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Scoring with OpenRouter
import json, subprocess
def score_skill(skill_name, content, model="google/gemini-2.0-flash-001"):
"""Score a skill using LLM council evaluation."""
prompt = f"""You are an expert evaluator scoring skills for an AI agent.
Evaluate on 10 dimensions (10 points each, 100 total):
Design & Architecture
Flowcharts/Diagrams
Implementation Patterns
Language/Coverage
Security
Testing Strategy
Edge Cases & Pitfalls
Performance Optimization
Deployment
Documentation
Reply ONLY in this format:
DESIGN: N/10
FLOWCHARTS: N/10
IMPLEMENTATION: N/10
COVERAGE: N/10
SECURITY: N/10
TESTING: N/10
EDGE_CASES: N/10
PERFORMANCE: N/10
DEPLOYMENT: N/10
DOCUMENTATION: N/10
TOTAL: N/100
SKILL CONTENT:
{content}"""
result = subprocess.run([
"curl", "-s", "--max-time", "180",
"https://openrouter.ai/api/v1/chat/completions",
"-H", f"Authorization: Bearer {OPENROUTER_KEY}",
"-H", "Content-Type: application/json",
"-d", json.dumps({
"model": model,
"messages": [{"role": "user", "content": prompt}],
"max_tokens": 500,
"temperature": 0.1
})
], capture_output=True, text=True, timeout=200)
return parse_scores(json.loads(result.stdout))
8. Production Deployment
Agent Service Architecture
ββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Production Deployment β
β β
β ββββββββββββ ββββββββββββ ββββββββββββ β
β β Nginx β β Agent β β Redis β β
β β (SSL) ββββΆβ Gateway ββββΆβ (Cache) β β
β β :443 β β :8788 β β :6379 β β
β ββββββββββββ ββββββ¬ββββββ ββββββββββββ β
β β β
β ββββββββββ΄βββββββββ β
β β β β
β ββββββΌβββββ βββββββΌβββββ β
β β Browser β β LLM β β
β β Stack β β Providersβ β
β β :9377-78β β (API) β β
β βββββββββββ ββββββββββββ β
β β
β ββββββββββββ ββββββββββββ ββββββββββββ β
β β MariaDB β β Hindsightβ β WA Bridgeβ β
β β :3306 β β :9077 β β :9375 β β
β ββββββββββββ ββββββββββββ ββββββββββββ β
ββββββββββββββββββββββββββββββββββββββββββββββββββββ
Systemd Service Best Practices
# /etc/systemd/system/hermes-gateway.service
[Unit]
Description=Hermes Agent Gateway
After=network.target
Wants=redis.service
[Service]
Type=simple
User=root
WorkingDirectory=/usr/local/lib/hermes-agent
ExecStart=/usr/local/bin/hermes gateway start
Restart=always
RestartSec=10
KillMode=control-group # Kills gateway + bridge.js together
Environment=NODE_ENV=production
Environment=HERMES_LOG_LEVEL=info
Resource limits
LimitNOFILE=65536
MemoryHigh=4G
MemoryMax=8G
[Install]
WantedBy=multi-user.target
Monitoring & Alerting
#!/bin/bash
/opt/scripts/agent-health-check.sh
Run via cron every 5 minutes
GATEWAY_URL="http://localhost:8788/health"
ALERT_WEBHOOK="https://your-webhook-url"
Check gateway
if ! curl -sf "$GATEWAY_URL" > /dev/null; then
curl -sf "$ALERT_WEBHOOK" -d '{"text":"π¨ Hermes Gateway DOWN!"}'
systemctl restart hermes-gateway
fi
Check disk
DISK_USAGE=$(df -h / | tail -1 | awk '{print $5}' | sed 's/%//')
if [ "$DISK_USAGE" -gt 80 ]; then
curl -sf "$ALERT_WEBHOOK" -d "{\"text\":\"β οΈ Disk usage at ${DISK_USAGE}%\"}"
fi
Check memory
MEM_USAGE=$(free | grep Mem | awk '{print int($3/$2*100)}')
if [ "$MEM_USAGE" -gt 85 ]; then
curl -sf "$ALERT_WEBHOOK" -d "{\"text\":\"β οΈ Memory usage at ${MEM_USAGE}%\"}"
fi
9. Testing Agents
Agent Testing Decision Tree
What to test? ββ¬β Tool invocation βββ Unit test with mocked tools
ββ Prompt adherence βββ Eval rubric with golden outputs
ββ Multi-step reasoning βββ Integration test with real LLM
ββ Error recovery βββ Fault injection test
ββ Memory persistence βββ Session restart test
ββ Subagent delegation βββ Isolation + result verification
ββ Cron job execution βββ Schedule test + verify output
ββ Browser automation βββ Screenshot diff test
Test Patterns
# Unit test: Tool invocation
def test_memory_add():
result = memory(action="add", target="user", content="Test preference")
assert result["status"] == "success"
Integration test: Multi-step agent execution
def test_agent_research_flow():
result = delegate_task(
goal="Research Python 3.13 features",
toolsets=["web"]
)
assert result["status"] == "completed"
assert len(result["summary"]) > 100
Eval rubric: Prompt adherence
def test_prompt_follows_instructions():
response = agent.chat("List 3 things about Python. Respond in JSON.")
data = json.loads(response) # Should be valid JSON
assert len(data) == 3
10. Troubleshooting & Best Practices
Agent Not Responding
Agent not responding? ββ¬β Gateway down? βββ systemctl restart hermes-gateway
ββ Provider error? βββ Check config.yaml, test API key
ββ Context overflow? βββ Clear session, reduce skill count
ββ Tool timeout? βββ Increase timeout, check network
ββ Bridge disconnected? βββ Restart WA bridge, re-scan QR
Memory Issues
Memory issues? ββ¬β Budget overflow? βββ Keep entries under 500 chars
ββ Wrong target? βββ user for preferences, memory for facts
ββ Stale data? βββ Don't store data expiring <7 days
ββ Duplicate entries? βββ Use replace with old_text, not add
Skill Not Loading
Skill not loading? ββ¬β Invalid YAML? βββ Validate frontmatter with yaml.safe_load
ββ No name/description? βββ Add frontmatter fields
ββ Over 100KB? βββ Split into multiple skills
ββ Wrong directory? βββ Check ~/.hermes/skills/ vs optional-skills/
ββ Gateway not restarted? βββ systemctl restart hermes-gateway
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Practice β Impact β Priority β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Keep memory under 4.4K β Stable context β CRITICAL β
β Use delegate_task for 3+ β -70% context usage β HIGH β
β tool calls β β β
β Batch with execute_code β -60% round-trips β HIGH β
β Use patch over write_file β Smaller diffs β HIGH β
β Use search_files over grep β Faster + less outputβ MEDIUM β
β Read files with limit/offset β Don't read 100K β MEDIUM β
β Lazy-load skills per-turn β -20K context β MEDIUM β
β Use background terminal β Non-blocking ops β LOW β
β Cache browser snapshots β -90% tokens β LOW β
β Compress old sessions β -50% context β LOW β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ