Topic 4 of 5 · 4 min read
Latency and token cost of lookups
Goal: Estimate the turn, token and latency cost of a lookup strategy and cut it by limiting result size and repeat searches.
Every lookup is a model turn, a tool call and a block of result text, so budget lookups the way you budget any other cost. Just-in-time retrieval saves tokens only if the results are small and the agent does not search in circles.
Check yourself · 1 of 3
A grep tool returns 600 matching lines into the conversation. What is the main cost?
Where the cost comes from
One lookup has three parts:
- A turn. The model decides to call the tool, waits for the result, then reads it. Agents re-send the conversation each turn (usually served partly from cache), so a long loop of small lookups adds up.
- Result tokens. Whatever the tool returns goes into context and stays there for later turns. A grep that returns 400 matching lines puts 400 lines into every following turn.
- Wall-clock time. Network search, database queries and web fetches are slower than a local read. Several in sequence mean the user waits.
Estimating a strategy
Write it down as arithmetic. Say a task needs about 6 lookups. If each returns about 2,000 tokens, that is roughly 12,000 tokens added to context. If a tighter tool returns about 300 tokens each, it is 1,800. These numbers are your measurements or estimates for your tool, not a rule; log real ones.
Ways to cut cost
- Cap results. Return at most N matches and say how many more exist, so the agent can narrow instead of reading all.
- Filter at the source. Search with a path, file type or date range, not the whole corpus.
- Return snippets, not documents. Give file, line and a few lines of context. The agent reads the full file only when needed.
- Summarize before it enters context. A sub-agent or a cheap model reads the bulk output and returns a short answer. Anthropic's context engineering article describes sub-agents that explore at length and return condensed summaries.
- Stop repeat searches. Note what was already searched, and cache results within the session.
- Batch independent lookups in one turn instead of one per turn.
Before and after
Weak tool result handling:
def grep_code(pattern):
return run(["grep", "-rn", pattern, "."]) # may return thousands of lines
Better:
def grep_code(pattern, path=".", limit=20):
lines = run(["grep", "-rn", "--include=*.py", pattern, path]).splitlines()
shown = lines[:limit]
note = f"\n[{len(lines) - limit} more matches; narrow with path]" if len(lines) > limit else ""
return "\n".join(shown) + note
What goes wrong
- Unbounded output. One broad grep fills the window and pushes out the task.
- Loops. The agent runs the same query with slightly different words, never deciding.
- Over-summarizing. A summary that drops the exact error line makes the next step a guess. Keep identifiers and numbers intact.
Examples
Comparing two strategies
A table for a docs agent answering a question.
| Strategy | Lookups | Tokens per result | Added context |
|---|---|---|---|
| Return full articles | 4 | 3,000 | 12,000 |
| Return top 3 snippets, open one article | 2 | 500 then 3,000 | 4,000 |
The second uses half the lookups and about a third of the context. Figures are illustrative; measure your own.
Breaking a search loop
The agent greps for retry, retries, retry_count, then Retry one after another. Add a rule: "If two searches for the same concept return nothing useful, list the directory or ask." Also log queries so a repeated one is returned from cache.
Key points
- Each lookup costs a model turn, result tokens that stay in context, and wall-clock time.
- Estimate cost as lookups times average result size, using numbers you measured for your own tools.
- Cap results and report how many more exist, so the agent narrows rather than reads everything.
- Filter at the source and return snippets with locations, not whole documents.
- Summarize bulk output outside the main context, but keep exact identifiers and error lines.
Common mistakes
- Letting tools return unlimited output into the conversation.
- Searching the whole corpus when a path or date filter would narrow it.
- Summarizing so hard that exact error messages and ids are lost.
- Measuring only token cost and ignoring the extra turns and waiting time.
Check yourself · 2 of 3
Which change most reduces the size of lookup results without losing the ability to dig deeper?
Check yourself · 3 of 3
An agent runs the same search five times with small wording changes and finds nothing. Which fix helps most?
Practice items, not counted towards your mastery.
Start here
- Effective context engineering for AI agents (Anthropic) (opens in a new tab)ArticleFree
Defines just-in-time context, light references and the hybrid of pre-loaded data plus agent exploration.
- Context engineering for agents (LangChain) (opens in a new tab)ArticleFree
A vendor-neutral map of writing, selecting, compressing and isolating context for agents.
- Best practices for Claude Code (Claude Code docs) (opens in a new tab)DocsFree
Practical advice on instruction files, exploring code and verifying work with a coding agent.