Skip to content

turn_context & Prompt Assembly

源码版本v2026.7.20

Responsibility

Before each API call, assemble "history messages + this turn's user input + gateway-side attached context + compression markers" into the api_messages sent to the provider. TurnContext is the container for this turn's output; build_turn_context is the assembly entry. It also injects notes collected by the gateway into multimodal content.

Key Files

Data Flow

  1. Each turn the main loop calls build_turn_context:268 to produce a TurnContext.
  2. compose_user_api_content (agent/turn_context.py:44) pieces the user's raw input into API content.
  3. If the gateway side has accumulated notes (from attachments, context hints), consume_gateway_turn_context_notes (agent/turn_context.py:124) pulls them out and injects them via append_notes_to_multimodal_content.
  4. substitute_api_content (agent/turn_context.py:79) substitutes placeholders; drop_stale_api_content cleans stale content.
  5. If the previous turn triggered compression, reanchor_current_turn_user_idx (agent/turn_context.py:164) fixes this turn's user message position in history.
  6. The assembled api_messages enters API call retry sub-loop:1227.

Summary

turn_context is "a per-turn snapshot factory": it freezes dynamic context into a sendable structure. It works in tandem with Context Compression — once compression rewrites history, turn_context re-aligns the pointers.

Unofficial community learning site. Content based on the MIT-licensed NousResearch/hermes-agent source.