How to Assemble the Message Pipeline in Your Coding Agent's Model Requests
Every time a coding agent calls a model, it assembles conversation history, tool results, IDE context, and system reminders into a single request body. This article breaks down how that pipeline works: how internal message types map to API roles, how content parts carry multimodal data and tool calls, where hidden injections happen, and why trimming tool results can break prompt caching. It also includes a field comparison between OpenAI and Anthropic APIs plus a checklist of common mistakes to help you avoid pitfalls when building your own agent.
Introduction: How a Single Message Gets Assembled
When a user types “help me find the performance bottleneck in this function” into a coding agent, the model receives far more than those few words. The request also contains conversation history, results from the previous turn’s tool executions, the code selection or cursor position in the editor, system instructions, tool definitions, and sometimes injected prompt text the user never typed directly.
All of this must ultimately land in a structured request body. Understanding how that body is composed—and how messages are assembled—is the foundation of any context strategy for a coding agent. This article uses common JSON-based model APIs as examples to walk through the full path from internal events to the final request. Specific field names referenced here follow each provider’s official documentation; details may change as API versions evolve.
1. Where Messages Sit in the Request Parameters
A model call’s request parameters typically consist of three parts: system instructions, a message list, and tool definitions. In OpenAI’s Chat Completions API, system instructions appear inside the messages array as messages with the system or developer role. In Anthropic’s Messages API, system instructions are a top-level system parameter, separate from the messages array.
The proportion each part occupies depends on the scenario. The following is a hypothetical example to illustrate structure, not measured data:
| Part | Typical Role | Hypothetical Share |
|---|---|---|
| system | Identity, behavioral rules, environment info | ~20%–30% |
| messages | Conversation history, tool results, injected text | Grows with turns; may dominate |
| tools | Tool names, descriptions, parameter schemas | Small when few tools |
The share of messages varies significantly with conversation length, tool result size, and trimming strategy. With few turns it may be tiny; in long tasks it is usually the fastest-growing part. For capacity planning, rely on actual token counts from real requests rather than fixed ratios.
Messages travel through roughly three stages from creation to sending: internal construction, cleaning and mapping, and API transmission. Internal construction preserves rich semantic information; cleaning and mapping converts it into structures the target API accepts; transmission finally sends the request.
2. Mapping Internal Types to API Roles
Coding agents typically use semantic message types internally, making it easier to distinguish content sources for logging, UI display, and trimming strategies. A common division includes five categories:
- User messages: keyboard input, voice transcription, pasted text.
- Assistant messages: model replies, possibly containing both text and tool calls.
- Tool messages: tool execution results, such as code search results, file contents, and command output.
- System reminders: text the agent inserts to keep its runtime logic on track—for example, reminding the model it can give a final answer once it has enough information.
- Environment context (UserContext): selected code in the IDE, current file path, recent edit history, and so on.
How these five categories map to API roles depends on the target API and your adapter design—there is no universal standard. Here is how the two mainstream APIs handle it:
- OpenAI Chat Completions: supports the system, developer, user, assistant, and tool roles. Assistant messages can carry a tool_calls array; tool results are returned as standalone messages with role set to tool, linked to their calls via tool_call_id.
- Anthropic Messages: the messages array contains only user and assistant roles, with system instructions in the top-level system parameter. Tool calls appear as tool_use content blocks in assistant messages; tool results appear as tool_result content blocks in the next user message, linked via tool_use_id.
So the internal “tool message” lands differently depending on the API. On APIs that support a tool role, use the proper tool message format with call IDs. Only on APIs offering just user and assistant roles should you place tool results in dedicated content blocks within user messages. And only on APIs with no structured tool result field at all should you fall back to plain text—while retaining enough identifiers, such as tool name, call ID, and status.
System reminders and environment context are handled similarly. In the Anthropic API, they typically go in as text blocks inside user messages, or get folded into the system parameter. In the OpenAI API, they can be part of a system, developer, or user message. Mapping them uniformly to the user role and distinguishing them with special markers is a convention some in-house adapters adopt—not a general requirement of external APIs.
Note that keeping rich types internally pays off in manageability and debugging. But the degradation and merging done before sending must strictly follow the target API’s format rules, or the server will reject the request.
3. Content Parts: Structured Units Inside a Message
Most modern APIs do not treat message content as a plain string. Instead, content is an array of blocks, each with its own type, independently carrying one modality or one piece of semantics.
Common part types in coding agents, and their fields in the two mainstream APIs, are as follows:
| Internal Part | OpenAI Chat Completions | Anthropic Messages |
|---|---|---|
| Text part | The message’s content string, or a content item with type text | A content block with type text |
| Image part | A content item with type image_url, via URL or Base64 | A content block with type image; source can be Base64 or a URL |
| Tool call part | The assistant message’s tool_calls array, with id, function.name, and arguments as a string | A tool_use block in the assistant message, with id, name, and input as an object |
| Tool result part | A message with role tool, containing tool_call_id and content | A tool_result block in the user message, with tool_use_id, content, and optional is_error |
A few field requirements deserve special attention:
- Call IDs must match one-to-one. Every tool call generated by the model has a unique ID, and the tool result must carry back the same ID.
- Parallel calls must all be answered. When an assistant message contains multiple tool calls, the next turn must provide a result for every one of them. Missing entries usually cause the request to be rejected.
- Argument formats must follow the API spec. OpenAI’s arguments is a JSON string; Anthropic’s input is a JSON object. Mixing them up causes parsing failures.
Here is an illustrative Anthropic message structure showing a text-plus-tool-call message and the corresponding tool result:
{"role": "assistant","content": [{ "type": "text", "text": "Let me search for the function definition first." },{ "type": "tool_use", "id": "toolu_001", "name": "code_search", "input": { "keyword": "performance_bottleneck" } }]}
{"role": "user","content": [{ "type": "tool_result", "tool_use_id": "toolu_001", "content": "File: /src/worker.js, line 14..." }]}
Tool result content should be truncated or summarized before being written into a message—never drop an entire file or full log directly into the request.
4. Hidden Injection Points: Content the Model Reads Every Turn
Hidden injections are content the user never typed directly but that gets included in every model call. They are a common design pattern in coding agents and fall into four main categories.
The first is IDE context. The current file in the editor, the cursor’s line, the selected code snippet, and the project root can be summarized into a structured text block, placed at the front of the user message or in a separate text block. This lets the model focus on the code the user is looking at. Such information can improve answer quality, but whether it actually helps depends on the task type and the model’s capabilities—validate it with evaluations rather than assuming it works.
The second is attachment expansion. Files, images, or logs the user references usually don’t enter the request in raw form; they are preprocessed first. Code files may get line numbers and language tags, PDFs may be parsed down to titles and summaries, and oversized logs may keep only the beginning, end, and key lines. Preprocessing controls token consumption but can lose detail—factor that into your design.
The third is system reminders. These usually appear near the end of the context, close to where the model is about to generate its reply. Typical content includes output format requirements and restrictions on write operations. System reminders provide soft constraints only; they cannot guarantee compliance. Security-related restrictions should be enforced with permission checks at the tool layer, not left to prompt text alone.
The fourth is tool result metadata. Timestamps, execution status, data size, and truncation flags can be used to filter results before they enter the context. For example, results exceeding a length limit can be truncated with a note like “truncated, 3000 total lines,” so the model knows the content is incomplete.
5. Trimming Tool Results and Prompt Caching
A coding agent’s context grows with every turn. Retaining the full history each round quickly exhausts the context window. A common practice is to trim or summarize older tool results, keeping only what’s still useful.
This intersects with caching. Most providers’ prompt caching is prefix-based: previously computed content can only be reused when the prefix is completely identical. So if trimming modifies earlier content, everything after it loses its cache.
Trimming the tail—or results positioned later in the middle—generally won’t break an existing prefix cache when these conditions hold:
- System instructions, tool definitions, and early history remain byte-for-byte identical.
- The trimmed content sits after the cache breakpoint, or in a portion of the new request that is allowed to change.
- Cache breakpoints are set consistently with the provider’s documentation and meet the model’s minimum cacheable length.
These conditions don’t hold on every service, and cache granularity, TTL, and billing vary by provider. For example, Anthropic’s prompt caching uses cache_control markers for breakpoints and entries expire over time; OpenAI’s automatic caching has its own minimum length and hit conditions. Always defer to the official documentation and verify with actual cache-hit metrics from real requests.
A common trap: putting the current timestamp at the start of the system instructions changes the prefix on every request, making cache hits nearly impossible. Place time information later in the request, or inject it only when needed.
Trimming tool results also carries risk. Once raw output is deleted, the model may lose key details. A safer approach: keep the tool name, call ID, status code, and a summary, while writing the full result to retrievable storage. When the model needs details, it can re-read them via a new tool call.
6. The Context Governance Pipeline and Common Mistakes
Putting the pieces together, a message goes through roughly six steps from creation to entering a request:
- Event capture: user input, tool callbacks, or IDE events produce messages, tagged with semantic types.
- Part assembly: text, tool calls, images, and other content are packed into content block arrays.
- Context merging: IDE context, system reminders, and other injections are added, forming the complete message sequence.
- Type mapping and cleaning: content is converted according to the target API’s role and field rules, ensuring call IDs are correctly paired.
- Cache optimization and trimming: the cache prefix is checked, tail messages are truncated, and historical tool results are replaced with summaries.
- Request sending: system instructions, the message list, and tool definitions are assembled and sent.
The most error-prone spots in this pipeline typically fall into these categories:
- Mapping errors: sending tool results as plain user text without preserving call IDs, so the model can’t link results to calls.
- Broken pairing: trimming removes a tool_use’s corresponding tool_result—or only one of several results—triggering a format error from the API.
- Modified prefix: timestamps, random IDs, or dynamic ordering placed early in the request invalidate the cache every turn.
- Untrimmed results: a single oversized tool output consumes much of the window in one request, forcing repeated trimming in later turns.
- Poor injection placement: a system reminder inserted before the user’s question may be ignored—or mistaken for user speech and answered.
- Argument format errors: OpenAI’s arguments isn’t valid JSON string, or Anthropic’s input is written as a string, causing parsing failures.
Conclusion: The Message Pipeline Determines Stability and Cost
A coding agent’s performance depends heavily on how it acquires information, compresses it, organizes it into requests, and keeps the cache valid across turns. Model capability and the tool ecosystem certainly matter, but the message pipeline’s design directly affects whether requests succeed, how high latency is, and how much you pay.
If you’re building your own coding agent, start with three things: consult the target API’s official documentation and build a role-and-field mapping table; write pairing checks for tool calls and results to catch errors before sending; and log token counts and cache-hit rates from real requests before deciding on a trimming strategy. These steps will do more for stability than chasing any fixed message structure.
