← ls ./blog

The Context Injection Pattern

One of the mistakes I see often is folks writing agent definitions that include everything an agent needs to do it’s job well.

On the surface it seems harmless, and even responsible.

In truth, there are several problems with this approach, and the one I wanted to focus on in this post is around cost.

As we know, new tokens increase in cost for every token currently held in your context window. While prompt caching reduces this substantially by storing pre-computed Query values, any calls that fall outside the boundaries of your caching logic or that take place in a large context window incur meaningful cost.

In many cases, that cost can be reduced by using injection patterns. By using SDK tooling, such as skills and hooks, we can serve context to our agents at the moment when they need it.

For example, we can instruct our agents to use github CLI in their agent definition files, and then when they eventually use the command to write a commit, we can use the Claude Agents SDK ‘PreToolUse’ hook to provide deterministic context injection to the agent at both a time when it is:

  1. Most likely to adhere to the instructions we provide, and
  2. To minimize compute costs by keeping the pre-tool-call context window as small as possible

These two benefits come at the cost of increased complexity, which we can transform into an advantage by leveraging what my next post will discuss: Agent Context Composition.

Andrew Dunne · andrewdunne.com more writing →