How to Design the Message Pipeline and Caching for Coding Agents
This article explains how coding agents assemble request payloads from the system prompt, tool definitions, and message history. It covers how an internal message pipeline maps to provider APIs and how prompt caching depends on a stable prefix. It is aimed at developers who already know at least one LLM chat API and are building or evaluating a coding agent.
This article is for readers who already know at least one LLM chat API and are building or evaluating a coding agent. It does not discuss model capabilities. It covers only how request data is assembled and how that data is cached.
1. What the Model Actually Receives
Before sending a request, a coding tool assembles the payload through a parameter-building function. The payload has three main parts:
- System prompt: Defines the role, the working environment, and behavioral rules. It usually stays stable throughout a session.
- Tools: JSON Schema definitions of callable tools, such as reading files, running commands, and searching code.
- Messages: The history of conversation and events, including user input, model replies, tool call requests, tool results, and system reminders. Content is appended every turn, which makes this the fastest-changing part.
No standard ratio exists for how these three parts divide the token budget. The split depends on the number of tools, the length of the history, and the product configuration. In sessions with many tools and long histories, Messages usually takes a larger share, but you need to measure the exact numbers yourself. To measure, count the tokens in each part and divide by the total token count of the same request. Record the session length and the number of tools as well, so results can be compared across sessions.
2. The Message Pipeline: Mapping Internal Types to APIs
Coding tools typically distinguish several message types internally. The table below shows a common breakdown, using a Messages-style API as the example.
| Internal Type | Meaning | Target API Representation | Validation Points |
|---|---|---|---|
| User input | Text the user types in the chat box | user role, text block | Filter out blank content |
| Model reply | Text generated by the model | assistant role, text block | Preserve the original order |
| Tool call request | A function call initiated by the model | assistant role, tool_use block | Each call needs a unique id |
| Tool execution result | Output returned by a tool | user role, tool_result block, referencing the same id | If a result is missing, add an error placeholder |
| System reminder | Retry, timeout, and status notices | user role, text block | Place after the tool_result block |
Different providers define roles quite differently, so the mapping logic should live in an adapter layer rather than being hardcoded into business code. OpenAI’s Chat Completions API uses four roles: system, user, assistant, and tool. Tool results come back as separate tool messages linked by tool_call_id. Anthropic’s Messages API places system as a top-level field, and its messages contain only user and assistant roles. Tool results appear as tool_result blocks inside user messages. The two APIs also differ in their rules for merging messages and enforcing role alternation. Check the official documentation for the target API version for the exact rules.
The sanitization pipeline does three main jobs:
- Merging: When a model calls several tools in a row with interleaved thinking content, the pipeline must merge the discrete internal records into complete assistant messages for each turn. If the target API requires strict role alternation, the pipeline also merges adjacent messages with the same role.
- Preserving signed content: Some APIs require thinking blocks and their signatures to be sent back unchanged during tool-call turns. Rewriting or dropping these blocks causes the request to fail.
- Format downgrading: Some APIs accept content only as a string, while others accept arrays of content blocks. The safest approach keeps a structured array internally and outputs it in the target schema in the adapter layer. Content the schema cannot represent is converted into text. The payload is validated against the schema before it is sent.
3. Hidden Injection: The Model Sees More Than the Input Box
When a user selects a block of code with an error in the IDE and types only “fix this,” the tool typically attaches the selected code, the file path, the line range, and the project structure. Common injected content includes:
- Environment information: The current date, the operating system, the Git branch, and a summary of uncommitted changes.
- Project rules: Rule files in the repository that record code style, architectural constraints, and dependency preferences.
- Tool feedback: Tool execution results appended to Messages automatically. Multi-step reasoning and self-correction depend on this mechanism.
Injected content improves the model’s understanding, but it also creates privacy and security risks. The boundaries should be explicit:
- Authorization: Before reading files outside the workspace or sending project structure to a remote service, obtain the user’s consent or provide an explicit switch.
- Redaction: Scan for API keys, access tokens, private keys, and database connection strings before sending. If a match is found, replace it or refuse to send the request.
- Scope: Read only files inside the current workspace. Do not follow symbolic links that leave the project directory.
- Logging: By default, request logs should not record full injected content, so sensitive code is not written to disk.
4. Caching Strategy: The Hit Rate Depends on the Prefix
Most LLM prompt caching works through prefix matching. The reusable cache length is determined by the first position in the request that changes. Messages grows every turn. Recalculating everything each time would make latency and cost high, so caching is a key optimization for coding agents.
1. Common Causes of Cache Invalidation
- The system prompt contains a current timestamp or a random ID, which differs on every request. Moving dynamic information into later messages fixes this.
- The tool list order is unstable, so the same tools may serialize into different byte sequences. Sort the tools in a fixed order.
- Deleting or modifying messages in the middle of the history invalidates all cache entries after that point.
- Environment information that changes every turn, such as the list of uncommitted changes, invalidates the cache from the point of change onward.
2. Using Placeholder Replacement Correctly
When the context grows too long, you can replace old tool results with short placeholders such as “[Tool result omitted]”. Keep two points in mind:
- Replacement position: Replacing content in the prefix changes the prefix, which invalidates all cache entries after it. Replace only content that comes after the already cached prefix, or accept that computation restarts from the replacement point.
