Practical technical guides / AI engineering: tool interfaces and context budgets

Cap Large Tool Results With a Truncation Record the Agent Can See

Bound tool output at structural boundaries and return an explicit truncation record with counts and a continuation offset the model can act on.

By Sandeep Belgavi · Published 2026-11-26 · Prepared 2026-11-25

Bound tool output at structural boundaries and return an explicit truncation record with counts and a continuation offset the model can act on.

A silent cut looks exactly like a complete answer

Tools return whatever their backing system returns. An order-history lookup for a long-standing customer of Belgavi's Book Store can return hundreds of rows; a log search can return megabytes; a document fetch can return a whole PDF's text. The agent runtime has to fit that into a context window and a cost budget, so somewhere a limit is applied. The dangerous version of that limit is the one nobody sees: the result is sliced at some byte count and handed to the model as if it were whole.

A model cannot tell that a list stopped at row 11 because of a byte budget rather than because there were 11 rows. It will answer "this customer has returned one book" when the twelfth row is a second return. Worse, a byte slice of serialized JSON is usually not valid JSON, and different runtimes react differently: some pass the broken text to the model, some drop the result, some raise an error that the agent loop retries until it gives up.

The pattern that fixes this is the same one paginated APIs have used for decades, moved to the tool adapter: cut at structural boundaries, and attach an explicit record saying what was cut and how to get the rest. This guide implements that for JSON arrays and plain text, measures it on a synthetic fixture, and covers the design decisions that make the record useful to a model.

Where the limit belongs

Put the budget in the adapter that sits between the tool implementation and the model-facing result, not in the tool and not in the generic runtime.

The tool should keep returning complete data to any caller that needs it, such as a batch job. Teaching every tool about model budgets couples business logic to one consumer.

The generic runtime knows the budget but not the shape. It sees a string or a blob and can only slice bytes. That is where silent truncation comes from.

The adapter knows both: the budget configured for this tool and the structure of its result. It can cut at a whole item, a whole line or a character boundary, and it can describe the cut in terms the model understands, such as "returned 11 of 40 orders, continue from offset 11".

A truncation envelope for arrays

# Author: Sandeep Belgavi. Cap a list result at whole items within a byte budget.
def size(obj):  # encoded length of the compact JSON the model will receive
    return len(json.dumps(obj, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))

def cap_items(items, budget_bytes, offset=0):
    envelope = {"items": [], "truncation": {"truncated": False, "returned": 0,
                "total": len(items), "offset": offset, "next_offset": None}}
    if size(envelope) > budget_bytes:
        raise ValueError("budget smaller than an empty envelope")
    for i in range(offset, len(items)):
        envelope["items"].append(items[i])
        envelope["truncation"]["returned"] = len(envelope["items"])
        probe = dict(envelope, truncation=dict(envelope["truncation"],
                     truncated=True, next_offset=i + 1))
        if size(probe) > budget_bytes:
            envelope["items"].pop()
            envelope["truncation"].update(returned=len(envelope["items"]),
                                          truncated=True, next_offset=i)
            return envelope
    return envelope

The size check measures the whole envelope, including the truncation record, because the record itself costs bytes. Checking only the items would let the final result exceed the budget by the size of the record. The probe measures the envelope in its worst case, marked truncated with a next offset, so the decision to stop is made against the size that will actually be sent.

On the companion fixture of 40 synthetic orders with a 900-byte budget, the first page returns 11 items with total 40 and next_offset 11, the second returns items 11 to 21, and four pages reassemble the full list exactly. The test suite checks that every page fits the budget, every page is valid JSON, and the concatenation of pages equals the original list with no gaps or duplicates. A naive byte slice of the same serialized list at 900 bytes does not parse as JSON, which the tests also assert.

Text needs a different boundary

For text the natural unit is the line. The adapter cuts at the last newline that fits. If a single line exceeds the budget, it falls back to a character boundary, and in UTF-8 that requires care: a byte slice can end in the middle of a multi-byte character. The companion implementation drops trailing continuation bytes and any dangling lead byte before decoding. With a five-byte budget and a string of two-byte characters, it returns two whole characters rather than two and a half.

The text record reports returned_bytes, total_bytes and next_byte_offset. Bytes are the honest unit here, since that is what the budget measures and what a follow-up read would use as an offset. If the backing tool supports reading by line number, report lines as well.

Make the record readable to a model

A truncation record only helps if the model notices it and knows what to do. Three practices make that more likely.

Put the record in a fixed place with fixed field names, and describe it once in the tool's description: "Results may be truncated. When truncation.truncated is true, call this tool again with offset set to truncation.next_offset to read more." Consistency across tools means the model learns one convention.

Give the total whenever it is cheap to know. "Returned 11 of 40" lets the model decide whether to read on or to narrow the query. "Returned 11, more available" is better than nothing but forces a read to find out how much remains.

Offer narrowing as well as paging. For many questions the right response to truncation is not to read 40 rows but to filter, for example asking only for returned orders. If the tool accepts filters, say so in the same description.

Some protocols already carry paging for their own list operations; the Model Context Protocol, for example, uses opaque cursors for listing tools and resources. Tool call results are a separate surface, so the truncation record described here is an application convention you define for your own tools rather than a protocol field.

Failure modes

An item larger than the budget. A single order with an enormous note field cannot fit. The adapter must not return an empty page marked "not truncated". The companion implementation returns zero items with truncated true, next_offset pointing at the oversized item, and a reason field. The caller can then fetch that one item with a larger budget or request a projection without the large field.

Offsets over changing data. If orders are added between page reads, offset-based paging can skip or repeat items. For data that changes during a conversation, use a cursor bound to a snapshot or to a stable sort key such as order id, and include that key in the record.

Budgets measured in the wrong unit. A byte budget and a token budget are not the same. Tokens per byte vary by content and by tokenizer. If the binding constraint is the context window, convert using a measured ratio for this tool's typical output and keep a safety margin, or count tokens directly with the provider's tokenizer where one is available.

Truncation hidden by a later layer. If the runtime applies its own limit after the adapter, the adapter's record may itself be cut off. Make the runtime limit larger than the largest adapter budget, and alert when the runtime limit is ever hit, because that indicates a tool without an adapter.

Verification

Test that every page fits its budget including the record. Test that pages reassemble to the original. Test the oversized-item path, the empty-result path and the exact-fit path where the last item fits with no room to spare. For text, test multi-byte characters at the cut. Then run an evaluation case where the answer depends on an item beyond the first page and check that the agent reads on or narrows the query rather than answering from page one. That last check is the only one that involves a model, and it is the one that tells you whether the record is actually being read.

When you do not need this

If a tool's result is bounded by construction, such as a lookup by primary key that returns one record of fixed shape, a budget adds nothing. Apply the pattern to tools whose output size depends on data the agent does not control: searches, histories, logs and documents.

Primary references and authorship

Sources checked 2026-11-25. Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/tool_result_truncation. Views are my own and do not represent any employer, past or present.