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
class TurnContext:242-268— per-turn context dataclassdef build_turn_context:268-400— assembly entrycompose_user_api_content:44-79— user message content assemblysubstitute_api_content:79-101— placeholder substitutionconsume_gateway_turn_context_notes:124-164— consume gateway-side attached notes and inject into multimodal contentreanchor_current_turn_user_idx:164-210— re-anchor this turn's user message index (post-compression fix)compression progress estimate:190-242—_compression_made_progress/_should_run_preflight_estimateprompt_builder— system prompt assembly (referenced by this page)
Data Flow
- Each turn the main loop calls
build_turn_context:268to produce aTurnContext. compose_user_api_content(agent/turn_context.py:44) pieces the user's raw input into API content.- 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 viaappend_notes_to_multimodal_content. substitute_api_content(agent/turn_context.py:79) substitutes placeholders;drop_stale_api_contentcleans stale content.- 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. - The assembled
api_messagesentersAPI 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.