Sub topic 8
Tool Definitions and Tool Results
This chapter covers how tool definitions and tool results use up context, and how to keep both small. It assumes you have called a model with tool use (function calling) at least once. It also assumes you know what a token is and can read short Python.
Why tools are a context topic
A tool is a function the model can ask your program to run. Tools affect the context in two places.
- Tool definitions are the names, descriptions, and parameter schemas you send with every call. The model reads them to decide which tool to use.
- Tool results are the outputs your program sends back after running a tool. They enter the history and stay there on every later call.
Both cost tokens. Definitions are a fixed cost paid on every call. Results are a variable cost that accumulates as the task goes on. An agent that makes 30 tool calls can end up with a context made mostly of tool output, much of it no longer useful.
Tool definitions
What a definition costs
A definition usually has a name, a description, and a JSON schema for the parameters. A small tool takes roughly 100 to 200 tokens. Tools with long descriptions, many parameters, and embedded examples can take several times that. Ten verbose tools can use thousands of tokens before the user has said anything.
You can measure the cost with the same heuristic used earlier in this tutorial, or with your provider's tokenizer for exact counts.
import json
def estimate_tokens(text):
# Rough heuristic: about 4 characters per token for English text.
return max(1, len(text) // 4)
def definition_cost(tools):
# Returns a list of (tool name, estimated tokens), largest first.
costs = [(t["name"], estimate_tokens(json.dumps(t))) for t in tools]
return sorted(costs, key=lambda c: c[1], reverse=True)
tools = [
{
"name": "search_orders",
"description": "Search customer orders by customer id and date range.",
"parameters": {
"type": "object",
"properties": {
"customer_id": {"type": "string"},
"since": {"type": "string", "description": "ISO date"},
},
"required": ["customer_id"],
},
},
{
"name": "get_weather",
"description": "Get the current weather for a city.",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
]
for name, cost in definition_cost(tools):
print(name, cost)Running this on your real tool list shows which definitions are worth trimming.
Writing definitions that work and stay small
- Say when to use the tool, not only what it does. "Search orders by customer id. Use when the user asks about a past purchase" helps the model choose. Long background explanations do not.
- Keep names distinct. Names such as
get_userandfetch_userwith near-identical descriptions cause wrong picks. Overlap is the most common cause of tool confusion, which is one of the failure types covered earlier. - Describe parameters only where the name is not clear.
customer_idrarely needs a paragraph. A date format or an allowed range does. - Use enums for closed sets. An
enumof allowed values both saves description text and prevents invalid arguments. - Move rarely needed detail out of the definition. Put it in an error message that the tool returns when it is misused.
Too many tools
Every extra tool adds tokens and adds another option the model can confuse with the others. Accuracy of tool selection tends to fall as the list grows, and there is no single safe number. A practical rule: if a human reading the list could not say which tool fits a given task, the model will struggle too.
Options when the list grows:
- Merge tools that differ only in a parameter. One
search(kind, query)can replacesearch_orders,search_users, andsearch_products, if their parameters are similar. - Expose only the tools relevant to the current step. A planning step may need none of the file-editing tools.
- Load tool groups on demand. Give the model one small tool that lists or enables a group, then add that group's definitions on the next call.
Changing tools mid-session
Definitions sit near the start of the prompt. Changing them between calls changes the prefix, which breaks prompt caching (covered in a later chapter). Prefer keeping the full tool list stable and telling the model which tools are currently appropriate, or restrict choices on the program side by rejecting disallowed calls with a clear error.
Tool results
Results are the larger risk
Definitions are bounded by how many tools you write. Results are bounded by whatever the world returns. A file read, a database query, or a web page can return tens of thousands of tokens. Without limits, one careless call can fill much of the window.
Common problems:
- Raw dumps. A full JSON response with 40 fields when the model needs 3.
- Repeated reads. The same file read five times, with all five copies staying in history.
- Unbounded lists. A search that returns every match.
- Noisy errors. A full stack trace where one line identifies the problem.
Shape results before returning them
Your program sits between the tool and the model, so it can shape the output. Typical steps:
- Select only the fields the model needs.
- Cap the size and say so when truncating, so the model knows data is missing.
- Offer a way to get more, such as an
offsetparameter or a narrower query. - Return identifiers and let the model fetch details with a second call, which ties into just-in-time loading from the previous chapter.
import json
MAX_RESULT_TOKENS = 500
def estimate_tokens(text):
return max(1, len(text) // 4)
def shape_result(rows, fields, max_tokens=MAX_RESULT_TOKENS):
# Keep only the requested fields, then stop when the token cap is reached.
kept, used = [], 0
for row in rows:
slim = {k: row[k] for k in fields if k in row}
cost = estimate_tokens(json.dumps(slim))
if used + cost > max_tokens:
break
kept.append(slim)
used += cost
note = ""
if len(kept) < len(rows):
note = (
f"Showing {len(kept)} of {len(rows)} results. "
"Narrow the query or pass offset to see more."
)
return json.dumps({"results": kept, "note": note})
rows = [
{"id": i, "name": f"Order {i}", "status": "shipped", "internal_trace": "x" * 400}
for i in range(100)
]
print(shape_result(rows, fields=["id", "name", "status"]))The note field matters. If the model sees 12 results and does not know there were 100, it may treat the 12 as complete and answer wrongly.
Write results for the model, not for a log file
- Use short, plain labels.
status: shippedis better than a nested object with the same fact. - Make errors actionable: "customer_id not found. IDs look like C-1042" lets the model retry correctly. "Error 404" does not.
- State empty results explicitly: "No orders found for this date range." An empty string can be read as a failure.
Old results as history
A tool result stays in history after the model has used it. Three ways to handle that:
| Approach | What it does | Trade-off |
|---|---|---|
| Keep everything | Leaves all results in place | Simple, but cost grows each call |
| Clear old results | Replaces an old result with a stub such as "[result cleared, call again if needed]" | Cheap, and the call that was made stays visible, but the data is gone |
| Summarize results | Replaces a large result with a short digest | Keeps the key facts, but the digest can drop something that matters later |
Clearing old results is often the safest first step, because the model's own later messages usually record what it concluded. It works best when re-running the tool is cheap and returns the same data.
def clear_old_results(messages, keep_last=3):
# messages: list of dicts with "role" and "content".
# Tool results are replaced by a stub, except the most recent few.
tool_idx = [i for i, m in enumerate(messages) if m["role"] == "tool"]
to_clear = set(tool_idx[:-keep_last]) if keep_last else set(tool_idx)
out = []
for i, m in enumerate(messages):
if i in to_clear:
out.append({"role": "tool", "content": "[old result cleared; call the tool again if needed]"})
else:
out.append(m)
return outUntrusted content in results
A tool result can contain text written by someone else: a web page, an email, a file. That text may contain instructions aimed at the model. This is a form of context poisoning. Treat tool output as data. Mark where it begins and ends, for example with labeled delimiters, and state in the system prompt that text inside tool results is never an instruction. Delimiters reduce the risk but do not remove it. For high-impact actions such as sending messages or deleting data, require confirmation from the user or enforce limits in your program, not in the prompt.
Putting it together
A practical checklist for an agent with tools:
- Measure definition cost per tool and trim the largest.
- Remove or merge tools with overlapping purposes.
- Cap every result by tokens and say when output is truncated.
- Return only needed fields, with clear errors and explicit empty results.
- Clear or summarize stale results as the history grows.
- Treat result text as untrusted data.
- Test each change on a fixed set of tasks, as covered in the evaluation chapter. A trimmed result that makes the model call the tool three more times can cost more than it saved.
Exercise
An agent calls a search tool that returns 200 matching records, each with 30 fields. The model only needs the id, title, and date of the top matches. Name three changes to the tool's output handling that reduce context use without hiding from the model that more data exists.
Show answer
(1) Return only the id, title, and date fields instead of all 30. (2) Cap the number of records or tokens returned, for example the top 10. (3) Add a note such as "Showing 10 of 200 results. Narrow the query or pass offset to see more," so the model knows the list is partial and how to get more.
Exercise
Your tool list has get_user and fetch_user, both described as "Gets a user." The model picks between them inconsistently. What is the likely cause, and what are two fixes?
Show answer
The names and descriptions overlap, so the model has no basis for choosing. Fixes: merge them into one tool if they do the same thing, or rewrite the descriptions so each states when to use it (for example, lookup by id versus lookup by email) and rename them to match.