Sub topic 14
Managing the token cost of tools and results
Every tool you define and every result a tool returns uses tokens. A token is the unit a model reads and bills for, roughly four characters of English text. This chapter assumes you know the tool-calling loop and how to write a definition with a name, description, and input schema. It shows where tool tokens go, how to measure them, and how to reduce them without hurting tool selection.
Where the tokens go
Tool definitions are sent as input on every request, not once per conversation. The provider places them in the model's context alongside your system prompt and the message history. A tool the model never calls still costs tokens each turn.
Results add a second cost. Each tool result is appended to the conversation, so it is re-sent on every later turn until you remove it. A 3,000-token result returned on turn 2 of a 10-turn conversation is paid for about nine more times.
Cost is only part of the problem. Large context has these effects too:
- Latency. More input tokens take longer to process.
- Selection accuracy. With dozens of tools, similar descriptions compete, and the model picks the wrong one more often.
- Room for the task. Context is a fixed budget. Tokens spent on unused tools are unavailable for documents, history, and reasoning.
Measure before you cut
Do not guess which tools are expensive. Estimate each definition's size and sort. The function below uses the four-characters-per-token rule. That is only an approximation, so use your provider's token-counting endpoint when you need exact numbers.
import json
def estimate_tokens(text: str) -> int:
"""Rough estimate: about 4 characters per token for English text."""
return max(1, len(text) // 4)
def tool_costs(tools: list[dict]) -> list[tuple[str, int]]:
"""Return (tool name, estimated tokens), largest first."""
rows = [(t["name"], estimate_tokens(json.dumps(t))) for t in tools]
return sorted(rows, key=lambda row: row[1], reverse=True)
if __name__ == "__main__":
tools = [
{
"name": "get_order",
"description": "Fetch one order by ID, for example 'ord_1001'.",
"input_schema": {
"type": "object",
"properties": {"order_id": {"type": "string"}},
"required": ["order_id"],
},
},
{
"name": "search_orders",
"description": "Search a customer's orders by status and date. " * 10,
"input_schema": {"type": "object", "properties": {}},
},
]
total = 0
for name, cost in tool_costs(tools):
total += cost
print(f"{name}: ~{cost} tokens")
print(f"Total per request: ~{total} tokens")Run this against your real tool list. Typical findings are that a few tools account for most of the cost, and that long descriptions, large enums, and deeply nested schemas are the usual causes.
Trimming definitions
Cut tokens that do not change the model's behavior. Keep tokens that do.
Keep these, even though they cost tokens:
- The statement of purpose and the "use this instead when" boundary.
- Format hints such as
YYYY-MM-DDand ID examples. - Defaults and limits the model cannot infer.
Cut these:
- Descriptions that repeat the name ("Gets the order" for
get_order). - Parameter descriptions that restate the parameter name.
- Implementation history, internal notes, and warnings aimed at developers.
- Long enums that the model rarely needs. If a field has 200 valid values, accept a string and validate on the server, with an error that lists close matches.
- Deeply nested objects when a flat set of parameters works.
Offering fewer tools per request
If trimming is not enough, send fewer tools. Three common approaches:
- Route by task. Choose a tool set before the model call. A support bot might send order tools for an order question and account tools for a login question. A cheap classifier or a keyword rule can do the routing.
- Stage by workflow. Expose only tools that make sense at the current step. A "refund" tool should not be visible until the order has been looked up.
- Use a tool-search mechanism. Some providers and frameworks let you mark tools as deferred. The model first sees only a small search tool, finds the tools it needs, and only those definitions are loaded. Support and syntax differ by provider, so check your provider's documentation.
The trade-off is that the model cannot call a tool it was not shown. Routing mistakes become missing-capability failures, which are harder to notice than wrong-argument failures. Log which tool set was sent with each request so you can diagnose them.
Prompt caching and tool stability
Many providers support prompt caching, which lets repeated prefixes of a request be billed at a reduced rate and processed faster. Tool definitions usually sit at the start of the request, so they are good cache candidates. This only works if they stay identical between requests.
- Keep the tool list and its order stable within a session.
- Do not put timestamps, user names, or per-request data in tool descriptions.
- Changing, adding, or removing a tool usually invalidates the cached prefix that follows it.
This pushes against per-request routing: routing changes the tool list, which breaks caching. Pick the approach that saves more for your traffic. A small, stable tool set that is cached is often cheaper than a routed one that is not.
Shaping results to save tokens
Results are the part you control most precisely, because your code produces them. Four techniques cover most cases.
- Return only useful fields. The model needs
id,status, andtotalto answer "where is my order". It rarely needs the full warehouse record. - Offer a detail switch. A
detailparameter with valuesconciseandfulllets the model ask for more only when needed. - Paginate with a signal. Return a page plus the total count and a
next_offset, so the model knows more exists and how to get it. - Cap size. Put a hard character limit on any text result and say what was cut.
def shape_orders(orders, detail="concise", limit=10, offset=0):
"""Return a bounded page of orders with enough metadata to continue."""
page = orders[offset:offset + limit]
if detail == "concise":
page = [
{"id": o["id"], "status": o["status"], "total": o["total"]}
for o in page
]
result = {
"orders": page,
"total_matches": len(orders),
"returned": len(page),
}
next_offset = offset + len(page)
if next_offset < len(orders):
result["next_offset"] = next_offset
result["note"] = (
f"Showing {len(page)} of {len(orders)}. "
f"Call again with offset={next_offset} for more."
)
return result
def cap_text(text: str, max_chars: int = 4000) -> str:
"""Truncate long text and tell the model that it was truncated."""
if len(text) <= max_chars:
return text
omitted = len(text) - max_chars
return text[:max_chars] + f"\n[truncated: {omitted} more characters omitted]"The truncation marker matters. Without it, the model may treat partial data as complete and give a confident wrong answer.
Pruning old results
Even well-shaped results accumulate. In long sessions, remove or replace results the model no longer needs:
- Replace a large result from several turns ago with a one-line summary such as
[search_orders returned 10 orders; ids ord_1001..ord_1010]. - Keep results the model is still reasoning over, and anything the user may ask about again.
- Some APIs offer built-in context editing for old tool results. If yours does, prefer it over writing your own.
Pruning also changes the conversation prefix, which can interrupt caching. Prune in batches rather than every turn.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Returning the full database row | Large repeated tokens and distracting fields | Select fields; add a `detail` option |
| Sending all 40 tools on every request | Cost, latency, wrong tool picks | Route or stage tool sets |
| Cutting boundary sentences from descriptions | Overlapping tools get confused | Keep "use X instead when" lines |
| Per-request data in descriptions | Cache never hits | Move dynamic data to the message |
| Truncating silently | Model treats partial data as complete | Add a truncation note |
Exercise
A tool returns 200 order records of about 150 tokens each on turn 1 of a 6-turn conversation. Roughly how many tokens does this single result cost across the conversation if the history is never pruned, and name two changes to the tool that would reduce it.
Show answer
The result is about 30,000 tokens (200 x 150). It is sent on turn 1's follow-up and every later request, so it is paid for on about 5 further turns, a total near 150,000 input tokens (exact figure depends on when the result is added). Reduce it by returning only needed fields (for example id, status, total) and by paginating with a limit and next_offset so only a small page is returned unless the model asks for more. A detail switch or a size cap with a truncation note would also work.