Hermes Agent - AI Orchestrator dengan Integrasi Telegram

Technical reference for building multi-agent systems with Hermes Agent, covering delegation, Telegram gateway, kanban coordination, cron automation, and production patterns.

hermes-agent telegram multi-agent orchestration reference doc

1. Apa itu AI Orchestration

AI Orchestration adalah koordinasi multiple AI agents untuk menyelesaikan task kompleks yang terlalu besar atau terlalu beragam untuk single agent. Satu orchestrator memecah task, mendistribusikan subtask ke specialist agents, dan menyatukan hasilnya.

Problem vs Solution

ProblemOrchestration Solution
Single agent kehabisan context window pada task besarOrchestrator memecah task, setiap sub-agent punya context sendiri
Satu model tidak optimal untuk semua jenis taskRouter mengirim coding ke model A, research ke model B
Task membutuhkan berbagai tools/permissionsLeaf agents dengan toolset terbatas sesuai peran
Parallelisasi tidak mungkin dengan single agentFan-out: N subtask berjalan bersamaan
Long-running task memblokir interaksi userBackground delegation: agent bekerja async
Error di satu step menghancurkan seluruh pipelineSupervisor pattern: retry, fallback, checkpoint

2. Hermes Agent Delegation System

Hermes menggunakan delegate_task() sebagai API utama untuk mendelegasikan work ke sub-agent. Setiap delegation menghasilkan session terisolasi dengan context, tools, dan model config sendiri.

Delegation Modes

ModeKapan PakaiSifat
delegate_task(task="...", mode="single")Task sekali jalan, butuh hasil sekarangBlocking, tunggu sampai selesai
delegate_task(task="...", mode="batch")Multiple task paralelBlocking semua, selesai bersamaan
delegate_task(task="...", mode="background")Task lama, user tidak perlu tungguNon-blocking, hasil kembali nanti

Orchestrator vs Leaf Roles

Orchestrator (parent agent) bertugas: menerima user request, memecah task, delegate ke children, merge hasil. Tidak melakukan work berat sendiri.

Leaf agent (child) bertugas: eksekusi spesifik (coding, research, scraping). Punya toolset terbatas, context terisolasi, tidak bisa delegate lebih lanjut kecuali max_spawn_depth mengizinkan.

Configuration

# ~/.hermes/config.yaml
delegation:
  max_iterations: 50          # max tool calls per sub-agent session
  max_concurrent_children: 3  # paralel sub-agents
  max_spawn_depth: 2          # orchestrator -> child -> grandchild (max)

# Setiap sub-agent bisa override model:
delegate_task(
  task="Research competitors",
  model="claude-sonnet-4-20250514",
  tools=["web_search", "web_extract"],
  max_iterations=20
)
Key Insight max_spawn_depth=2 berarti orchestrator bisa delegate ke child, child bisa delegate ke grandchild. Lebih dari 2 level = token cost explosion dan control loss.

3. Telegram Integration

Hermes berjalan sebagai Telegram bot melalui gateway layer. User berinteraksi via chat biasa, agent merespons dengan full tool access.

Gateway Setup

# Install gateway
hermes gateway install

# Configure (set bot token, allowed users)
hermes gateway setup

# Start gateway
hermes gateway start

# Check status
hermes gateway status

# View logs
hermes gateway logs

Environment Variables

VariableRequiredDescription
TELEGRAM_BOT_TOKENYesBot token dari @BotFather
TELEGRAM_ALLOWED_USERSNoComma-separated user IDs yang boleh interaksi
TELEGRAM_GROUP_ALLOWED_CHATSNoChat IDs grup yang diizinkan
TELEGRAM_ALLOW_ALL_USERSNotrue untuk buka akses ke semua user (hati-hati)
TELEGRAM_REQUIRE_MENTIONNotrue = bot hanya merespons jika di-mention di grup
TELEGRAM_FREE_RESPONSE_CHATSNoChat IDs di mana bot merespons tanpa mention

Bot API vs User API

FeatureBot API (@BotFather)User API (Telethon)
Baca chat historyTidak bisaBisa
Join grup sendiriTidak bisa, harus diinviteBisa
Rate limit30 msg/detik per grupFLOOD_WAIT (berfluktuasi)
Setup complexityRendahButuh phone number + session file
Forum topic supportPenuhPenuh
Inline queryDidukungTidak
Risk banN/A (bot account)User account bisa kena ban
CRITICAL LIMITATION Telegram TIDAK mengirimkan pesan bot-ke-bot. Jika dua bot (atau orchestrator + child bot) perlu berkomunikasi, mereka TIDAK bisa saling kirim pesan. Solusi: gunakan shared context file (JSON/markdown) yang ditulis satu bot dan dibaca bot lain.

4. Multi-Agent Patterns

Hermes mendukung beberapa pattern koordinasi multi-agent. Pilih berdasarkan struktur task, bukan preferensi aesthetic.

Fan-Out Pattern

Orchestrator memecah task identik menjadi N subtask paralel. Cocok untuk: batch processing, multi-source research, parallel testing.

User Request | Orchestrator / | \ A B C (parallel sub-agents) | | | v v v Merge Results -> Response

Pipeline Pattern

Output agent A menjadi input agent B. Cocok untuk: research -> outline -> draft -> review -> publish.

Task -> [Research Agent] -> data | [Writer Agent] -> draft | [Reviewer Agent] -> final

Supervisor Pattern

Satu supervisor mengawasi quality output worker agents, bisa retry atau redirect. Cocok untuk: high-quality output yang butuh review loop.

User -> Supervisor | +-----+-----+ | | | W1 W2 W3 (workers) | | | +-----+-----+ | Supervisor (review, retry if needed) | Response

Hub-Spoke Pattern

Satu central agent (hub) memiliki akses ke specialist agents (spokes). Hub routing berdasarkan intent classification.

User -> [Hub Agent] | | | v v v [Code] [Research] [Browser] Agent Agent Agent

5. Telegram-Specific Features

Topic Routing (Forum Mode)

Telegram grup bisa diaktifkan sebagai forum dengan topik terpisah. Hermes bisa route pesan ke agent berbeda berdasarkan message_thread_id.

Penting Topic IDs TIDAK sekuensial. Jangan asumsikan topic 1, 2, 3 berurutan. Selalu cek ID aktual dari Telegram.

Example Topic Routing Table

Topic NameThread IDAgent/ModelPurpose
#general1defaultGeneral conversation
#code-review108coding modelCode review requests
#research215research modelDeep research tasks
#devops342default + ssh toolServer management
#content419defaultContent writing pipeline
#monitoring587script-onlyCron-driven alerts
#store623store agentE-commerce automation

Cron Jobs

Hermes mendukung scheduled tasks yang berjalan tanpa user trigger. Bisa full agent mode atau script-only (tanpa LLM).

# Server monitoring setiap 5 menit (script-only, hemat token)
*/5 * * * * hermes cron run server-health --no_agent

# Daily digest jam 9 pagi (full agent mode)
0 9 * * * hermes cron run daily-digest

# Weekly report setiap Senin
0 10 * * 1 hermes cron run weekly-report

Script-only mode (no_agent=True)

Untuk task mekanis yang tidak butuh reasoning (health check, disk usage, restart service), script-only mode menjalankan bash/python script tanpa LLM. Token cost = 0.

Skills, Memory, dan Kanban

Skills

Skills adalah procedural memory dalam format markdown. Disimpan di ~/.hermes/skills/. Setiap skill berisi: trigger conditions, numbered steps, pitfalls, verification. Agent auto-load skill yang relevan sebelum execute.

Memory

Session-based dan persistent memory. Agent bisa menyimpan context antar session (memories/ directory). Berguna untuk preference, project context, learned patterns.

Kanban (SQLite-backed)

Task board built-in untuk koordinasi multi-agent. Mendukung 8 coordination patterns:

PatternDescription
Fan-outSplit task ke N parallel cards
PipelineCard berpindah kolom (todo -> doing -> done)
VotingMultiple agents vote on best option
JournalAppend-only log of decisions dan progress
Human-in-loopCard menunggu approval user sebelum lanjut
@mentionRoute card ke agent spesifik via mention
Thread-scopedCard terikat ke Telegram topic/thread
Fleet farmingDistribute work across multiple Hermes instances

Shared Context Flow

Ketika bot-ke-bot communication tidak mungkin, gunakan shared context file:

# shared-context.json - flow states:
planning -> build_needed -> building -> test_needed -> testing -> done

# Orchestrator menulis:
{"task": "build login page", "status": "build_needed", "assigned_to": "builder-bot"}

# Builder bot membaca, menulis:
{"task": "build login page", "status": "test_needed", "output": "/tmp/login.html"}

6. Real-World Use Cases

Customer Support Automation

Telegram bot sebagai first-line support. Agent classify intent, answer FAQ dari knowledge base, escalate ke human jika confidence rendah. Skill: firecrawl-knowledge-ingest untuk build knowledge base dari docs.

Content Pipeline

Research agent gather sources, writer agent draft, editor agent review, publisher agent format dan post. Pipeline pattern dengan kanban tracking. Setiap stage checkpoint ke shared context.

Code Review

Telegram topic #code-review menerima PR link. Agent fetch diff, run multi-dimensional review (security, performance, style), post inline comments. Skill: claude-code-review.

Research Assistant

Deep research dengan fan-out: 9 angle research (economic, technical, social, ...) dijalankan paralel, hasil di-synthesize oleh orchestrator. Skills: deep-research, firecrawl-deep-research.

DevOps Monitoring

Cron-driven monitoring: health check setiap 5 menit, alert ke Telegram topic #monitoring jika anomali. Script-only mode untuk checks, agent mode hanya untuk alert formatting dan root cause analysis.

Store Automation

Telegram digital store: catalog management, order processing, payment tracking. Skill: telegram-digital-store. SQLite-backed product DB, inline keyboard untuk browsing.

7. Architecture Patterns

Single Bot Architecture

Satu bot token, satu Hermes instance. Semua routing via topic/thread_id atau intent classification. Simplest setup, cocok untuk personal use atau small team.

# Config
TELEGRAM_BOT_TOKEN=your_token
TELEGRAM_ALLOWED_USERS=user_id_1,user_id_2

# Routing: topic-based
# All tools available to single bot

Multi-Bot Shared Context

Multiple bot tokens, setiap bot punya Hermes instance terpisah. Komunikasi via shared context file. Cocok untuk: specialization (coding bot vs research bot) dengan different model configs.

# Bot 1 (orchestrator): delegates, routes, merges
# Bot 2 (builder): coding, file operations
# Bot 3 (researcher): web search, scraping

# Shared context di /tmp/hermes-shared/
# File watcher trigger coordination

Cron-Driven Architecture

Tidak ada persistent bot. Cron jobs trigger Hermes agent secara periodik. Cocok untuk: monitoring, reporting, batch processing yang tidak butuh real-time response.

# Script-only (no LLM cost):
*/5 * * * *  hermes cron run disk-check --no_agent
0 */6 * * *  hermes cron run backup --no_agent

# Agent-mode (LLM reasoning):
0 9 * * *    hermes cron run daily-report
0 8 * * 1    hermes cron run weekly-summary

Event-Driven Architecture

Webhook-triggered: external events (GitHub push, form submission, payment callback) trigger Hermes task. Cocok untuk: CI/CD integration, automated workflows. Combine dengan background delegation.

8. Comparison with Alternatives

FeatureHermes Agentn8nLangChainCrewAI
Multi-agent delegationBuilt-in, recursiveVia workflow nodesLangGraphBuilt-in (Crew/Agent)
Telegram nativeFirst-class gatewayVia webhook/nodeNo (custom build)No (custom build)
Terminal/shell accessBuilt-in toolSSH nodeCustom toolCustom tool
File operationsBuilt-in (read/write/patch)Via nodesCustom toolCustom tool
Skill/memory systemMarkdown skills + SQLiteWorkflow storageMemory modulesBuilt-in memory
Cron/schedulingBuilt-in cron systemNative schedulerNoNo
Self-hostedYes (single binary)Yes (Docker)Library (you host)Library (you host)
Code executionexecute_code toolCode nodeCustomCustom
Learning curveLow (chat interface)Medium (visual editor)High (code-first)Medium (code-first)
Visual workflow editorNoYesLangGraph StudioNo

9. Best Practices

Delegation Rules

RuleWhy
Set max_iterations per delegationPrevent runaway agent loops burning tokens
Use execute_code for mechanical pipelinesToken-efficient: single code block vs N tool calls
Limit max_concurrent_children to 3-5Too many = context explosion + rate limits
Always provide constraints in task description"Write to /tmp/out.md, max 500 words" vs vague "write something"
Use background mode for tasks > 30 detikUser tidak perlu tunggu, agent report selesai
Check sub-agent output before mergingSub-agents hallucinate; orchestrator validates

Multi-Agent Rules

RuleWhy
One orchestrator per task treeDua orchestrator = conflicting instructions
Leaf agents get minimal toolsPrinciple of least privilege + lower token cost
Use shared context file, not message passingTelegram blocks bot-to-bot messages
Set spawn depth limit (2 max)Deeper = more control loss + token cost
Log delegation chainDebug: who did what, where did it fail
Use kanban for multi-step workflowsPersistence across crashes, visibility of progress

Anti-Patterns

Anti-PatternDamageFix
2+ bots di free-response chat3-10x token burn (bot reply loops)Set TELEGRAM_REQUIRE_MENTION=true atau limit FREE_RESPONSE_CHATS
Restart Hermes setiap config changeDowntime, lost contextGunakan hermes gateway reload (hot reload)
Test bot via curl getUpdatesSteals updates dari polling botGunakan hermes gateway logs untuk debug
SOUL.md terlalu panjangToken waste setiap requestMax 200-300 baris, gunakan skills untuk detail
Delegation tanpa constraintsSub-agent bikin file random, loop foreverAlways set max_iterations, output path, scope limits
cURL getUpdates saat polling aktifConflict: kedua consumer berebut updatesHanya satu consumer per bot token

10. Limitations

Token Costs

Setiap delegation = new session = full system prompt + context. Orchestrator dengan 5 children bisa menghabiskan 5-10x token dibanding single agent. Mitigate: constrain max_iterations, use execute_code untuk task mekanis, use script-only cron jobs.

Rate Limits

LLM providers: RPM/TPM limits berbeda per provider. Fan-out 10 concurrent agents bisa trigger rate limit. Mitigate: max_concurrent_children=3, stagger batch tasks.

Telegram: Bot API ~30 msg/detik per grup. User API FLOOD_WAIT unpredictable. Mitigate: queue messages, respect retry-after header.

Context Window

Model context window (128K-200K) terasa besar tapi cepat habis dengan tool outputs (file contents, search results, code blocks). Sub-agent yang membaca file besar bisa kehabisan context sebelum selesai. Mitigate: chunk reads (offset/limit), summarize before delegate.

Telegram Platform Limits

LimitValueImpact
Message length4096 charsLong responses dipotong, perlu split
File upload (bot)50 MBBatas upload file
Inline keyboard buttons100 per messagePractically ~20-30 sebelum UI buruk
Bot-to-bot messagingTidak didukungPerlu shared context workaround
Group join (bot)Must be invitedCannot self-join groups
Forum topic IDsNot sequentialMust query actual IDs, cannot guess

Security

MechanismDescription
secret_redactionAuto-redact API keys, tokens, passwords dari agent output sebelum kirim ke Telegram
command_approvalMode: manual (user approve setiap command), smart (approve safe, flag risky), off (auto-execute)
User allowlistTELEGRAM_ALLOWED_USERS - whitelist user IDs
Chat blocklistBlacklist specific chat IDs dari akses
File path restrictionsLimit read/write path ke allowed directories