Agent Main Loop
源码版本v2026.7.20
Responsibility
run_conversation is the heart of Hermes: given a user message, it repeatedly calls the model + tools until the iteration budget is exhausted or the task completes. It coordinates context construction, tool dispatch, stop-condition handling, and fallback on failure.
The file is ~5800 lines and dense — this page covers only the main thread; details go to sub-pages.
Key Files
run_conversation entry:588-720— function signature, init, pre-loop setupwhile main loop:721-760— conditionapi_call_count < agent.max_iterations and agent.iteration_budget.remaining > 0, with grace callAPI call retry sub-loop:1227-1280—while retry_count < max_retriesbuild_turn_context— per-turn context assemblyprompt_builder— system prompt assemblymoa_loop— Mixture-of-Agents aggregation pathcontext_compressor— compresses history when threshold hitIterationBudget— budget accounting core
Data Flow
run_agent.py AIAgentis a thin forwarder; actual dependency injection lives ininit_agent.- The caller passes
user_message;run_conversationfirst runsbuild_turn_contextto assemble the turn context (api_messages). - Enters the
whilemain loop: interrupt check → decrement budget (iteration_budget.consume()) → build/sanitizeapi_messages→ pre-compression → drain/steertext → MoA aggregation → enter the API call retry sub-loop. - After the model responds, validate the response and handle
finish_reason; on failure, callagent._try_activate_fallback(). - When the compression threshold is hit, run
context_compressorto reclaim space. - When the loop exits (budget exhausted / task complete / interrupted), the final message is returned and delivered by the gateway (see Gateway).
Summary
The main loop only orchestrates: turn driving, budget control, retry and fallback. The real capability comes from tools and skills; multi-platform delivery is handled by the gateway; self-improvement is driven by the learning loop.
For the official Chinese intro, see README.zh-CN and website/i18n/zh-Hans/.