Sub topic 12
Shaping tool results the model can use
This chapter assumes you know the tool-calling loop (the model requests a tool, your code runs it, you send the result back) and have read the earlier chapters on tool definitions. You should be comfortable reading short Python examples and JSON.
The result is the model's only view of what happened
The model never sees your database, your logs, or your code. After it requests a tool call, the only evidence it gets is the result you return. It reads that result as text, decides what to tell the user, and decides whether to call another tool.
So a tool result is not a data dump for a program. It is input for a reader who has no other context. Three questions guide the design:
- Does the result contain what the model needs for the next step?
- Does it leave out what the model does not need?
- Can the model tell what kind of outcome it is looking at: success, empty, partial, or failure?
Return what the next step needs
Backends usually return far more than the model can use. Raw rows contain internal keys, audit timestamps, nested objects, and codes that only your team understands. Each extra field costs tokens and gives the model something to misread.
Follow these rules when you choose fields:
- Include identifiers the model may need later. If the user might say "cancel the second one", the model needs each order's
idto call a follow-up tool. A result that shows only customer-facing names makes that follow-up impossible. - Include the fields the user will ask about. For orders, that is status, total, and creation date.
- Drop internal fields. Database row versions, shard names, and tracing headers rarely help.
- Resolve codes to words. Return
"status": "shipped"instead of"status": 3. Return"total": "42.50 USD"or a separatecurrencyfield instead of a bare number in cents, unless the unit is stated. - Use the same names the tool definition uses. If the parameter is
order_id, do not return the same value asreforoid. Matching names let the model pass values from one call into the next without guessing.
Make the shape predictable
Pick one structure per tool and keep it. The model handles a consistent shape better than one that changes with the data.
JSON works well when results are lists of records or when values feed into other tools. Short plain text works well for single facts or confirmations, such as Order ord_1001 cancelled. Refund of 42.50 USD will arrive in 5 business days. Either is fine. Mixing them in one tool is the problem.
Whatever you choose, keep these habits:
- Always return the same top-level keys, even when a list is empty.
- Put dates in one format, such as ISO 8601 (
2026-11-28). - Spell out units in a field name or value, for example
weight_kg. - Avoid deeply nested structures. Flat records are easier to read and cheaper to send.
Say what is missing, empty, or cut off
A result can look complete when it is not. The model will treat what you give it as the whole truth, so add explicit signals for the cases below.
| Situation | Weak result | Better result |
|---|---|---|
| No matches | `[]` | `{"orders": [], "total_matches": 0, "note": "No orders match these filters."}` |
| More matches than returned | The first 10 rows, with no mention of more | `{"orders": [...], "total_matches": 37, "returned": 10, "truncated": true}` |
| A field is unknown | Field missing, or `null` with no context | `"tracking_number": null` plus a note such as `"not yet assigned"` |
| Write succeeded | `{}` or `"ok"` | A short confirmation naming what changed and the new state |
An empty list is ambiguous. It can mean "nothing exists", "your filter was too narrow", or "the backend failed quietly". A total_matches count and a one-line note remove that ambiguity.
Truncation needs the same care. If you cap a list at 10 and say nothing, the model may tell the user "you have 10 orders" when there are 37. When you cap, say so, and tell the model how to get more. That can be a next_cursor value the tool accepts, or a hint to narrow the filters.
A shaping function
The function below turns raw database rows into the result shape described above. It selects fields, converts cents to a labelled amount, caps the list, and reports totals and truncation. It runs as written.
import json
DEFAULT_LIMIT = 10
STATUS_NAMES = {0: "pending", 1: "shipped", 2: "delivered", 3: "cancelled"}
def shape_orders(rows, limit=DEFAULT_LIMIT):
"""Turn raw order rows into a compact result for the model."""
total = len(rows)
shown = rows[:limit]
orders = [
{
"id": row["id"],
"status": STATUS_NAMES.get(row["status_code"], "unknown"),
"total": f"{row['total_cents'] / 100:.2f} {row['currency']}",
"created_at": row["created_at"][:10],
}
for row in shown
]
result = {
"orders": orders,
"total_matches": total,
"returned": len(orders),
"truncated": total > len(orders),
}
if total == 0:
result["note"] = "No orders match these filters."
elif result["truncated"]:
result["note"] = (
f"Showing {len(orders)} of {total}. "
"Narrow the search with status or created_after to see others."
)
return result
raw_rows = [
{
"id": "ord_1001",
"status_code": 1,
"total_cents": 4250,
"currency": "USD",
"created_at": "2026-11-02T14:03:55Z",
"shard": "eu-3",
"row_version": 17,
},
{
"id": "ord_1002",
"status_code": 3,
"total_cents": 1999,
"currency": "USD",
"created_at": "2026-11-10T09:12:01Z",
"shard": "eu-3",
"row_version": 4,
},
]
print(json.dumps(shape_orders(raw_rows, limit=1), indent=2))
print(json.dumps(shape_orders([]), indent=2))The first call prints one order plus "truncated": true and a note about narrowing the search. The second prints an empty list with a note. Both have the same keys. The shard and row_version fields never reach the model.
Keep results small
Every result you return stays in the conversation and is paid for again on later turns. A tool that returns 20,000 tokens of raw JSON once can crowd out the instructions and history the model needs. A later chapter covers context cost in general. For results, these controls work well:
- Default limits. Cap list size by default, and let the model raise it through a bounded
limitparameter. - Summaries before details. Offer a search tool that returns short records and a separate get tool that returns the full record for one ID.
- Field selection. If records are large, accept an optional
fieldsparameter with an enum of allowed names. - Truncating long text. Cut long free-text fields at a fixed length and mark the cut, for example with
"...[truncated, 4210 more characters]".
A cap without a signal is worse than no cap, because the model cannot tell the data was cut.
Separate failures from results
If a tool fails, do not return an empty or normal-looking result. Mark failures explicitly, as in the is_error field in the earlier get_order example, so the model does not read a failure as "no data". Many APIs also let you set an error flag on the tool result block itself. The next chapter covers how to write the error text so the model can recover.
Check results the way the model reads them
Before shipping a tool, print its result for a typical call, an empty call, and an oversized call. Then read each as if you had never seen the code. If you cannot answer "what happened, and what can I do next?" from the text alone, the model cannot either.
Exercise
A list_invoices tool returns the first 25 of 140 matching invoices as a bare JSON array. A user asks "How many unpaid invoices do I have?" and the model answers "25". Name the two problems in the result design and give the fields you would add to fix them.
Show answer
The result hides that it was truncated, and it gives no total, so the model took the length of the array as the answer. Wrap the array in an object and add total_matches (140), returned (25), and truncated (true), plus a note saying how to see more, such as a next_cursor or a narrower status filter. Filtering by status (for example status="unpaid") in the tool call would also let the total be the number the user asked for.
Exercise
A cancel_order tool returns "ok" on success. Why is this a weak result, and what would you return instead?
Show answer
The model learns that the call finished but not what changed, so it cannot report the new state, and it cannot tell a repeated cancel from a first one. Return the new state, for example {"id": "ord_1001", "status": "cancelled", "refund": "42.50 USD", "note": "Refund arrives in 5 business days."}.