Agent Tool Result Reducer: Fit Large JSON Tool Results into an LLM Agent's Context Window
Shrink large JSON tool results for LLM agents without silently losing data.
Package: agent-tool-result-reducer · Import: tool_result_reducer
A zero-dependency Python library that fits an API/tool response into a
character budget by selecting fields, dropping the widest fields, and cutting
only on whole-item boundaries — and that always tells the model, in a
_meta block, exactly what it did and did not receive.
Before: [{"id":1,"name":"Acme","description":"…"},{"id":2,"name":"content delivery networ ← cut mid-object
After: {"items":[…25 whole items…],"_meta":{"items_included":25,"items_available":25,
"total_reported_by_source":443,"fields_dropped":{"description":3617},…}}
Install
pip install agent-tool-result-reducer
Requires Python 3.10+. No runtime dependencies.
Quick start
from tool_result_reducer import reduce_tool_result
rows = [{"id": i, "name": f"Company {i}", "description": "long text " * 400} for i in range(25)]
response = {"results": rows, "total": 443} # a page of 25 companies, about 100,000 characters
result = reduce_tool_result(response, "crm.search", budget=4_000)
result.text # 1,506 characters of valid JSON: this is what goes to the model
result.complete # True: all 25 items are there; the wide `description` field was dropped
result.summary("crm.search")
# crm.search: complete, agent received 25 of 25 items (source reports 443 in total), dropped fields: description
The model is told what happened, in the result itself:
"_meta": {"items_included": 25, "items_available": 25, "complete": true,
"total_reported_by_source": 443,
"total_note": "`complete` covers this response only. The source reports 443 in total; ...",
"fields_dropped": {"description": 4017}, ...}
Objective
Give agent builders a drop-in function that sits between "tool returned something" and "append it to the model's context", so that:
- A result fits the budget you set, short of cutting a single item in half (cost and context-window control).
- What the model receives is always valid JSON made of whole items.
- When anything is left out, the model is told explicitly, with counts and a concrete way to get the rest — so it cannot report a partial result as complete.
The problem
Every tool result is re-sent to the model on every later turn of an agent loop, so large results are expensive and frameworks cap them. The usual cap is "keep the first N characters". That causes a quiet, serious failure:
In production, a search API returned 11 companies in 77,539 characters. A 12,000-character cap kept the start and cut mid-object (
…"name": "content delivery networ). The model parsed the 2 whole records it could see, wrote 2 rows to a spreadsheet, and reported success. Nothing indicated that 9 records had been dropped.
The cap bounded bytes. What matters is what the agent consumes: with only the 14 fields the task needed, all 11 records fit the same budget several times over.
How it works
For each tool result, in order:
| Step | What happens | Why |
|---|---|---|
| 1. Pass-through | Under budget and no select → returned unchanged. |
Zero overhead for the common case. |
| 2. Locate the collection | Finds the main list of objects in the envelope (data, items, results, content, … up to 3 levels deep; longest list wins; JSON:API data beats included). Reads server totals (total, totalElements, count, page.totalElements, …). A page size is not read as a total. |
Works with real-world API shapes without configuration, and lets the note say "25 of 443". |
3. Project (select) |
Keeps only the dot-paths requested (id,summary.name). Applied whenever given, not just when oversized. |
Pay only for the fields you use, on every turn. |
| 4. Guard the select | A select that matches no field on any item is discarded (full items shown, plus the list of valid paths). A select written against the envelope (items.id) is repaired automatically. A field that exists but is null still counts as a match. |
A wrong select must never produce an empty result labelled "complete". |
| 5. Auto-fit fields | Still too big → drop the widest fields across all items (measured, deterministic) until every item fits, down to a floor of 2 fields. | The model can't see the budget; dropping a known-expensive field beats making it guess through extra LLM turns. |
| 6. Cut on item boundaries | Still too big → keep as many whole items as fit. | Never broken JSON, never half a record. |
| 7. Annotate | Wrap in {"items": [...], "_meta": {...}} with counts, source totals, dropped fields with per-item cost, the top 3 most expensive fields, and an explicit warning when incomplete. |
The model, your logs and your UI all see the same truth. |
| Fallbacks | A large single object → structure outline (every key visible, long strings cut, nested containers summarised; still valid JSON). Non-JSON text → character cut with a clear marker. | Even non-collections degrade honestly. |
Usage
from tool_result_reducer import reduce_tool_result
raw = call_my_tool(**args) # dict, list or JSON string
result = reduce_tool_result(raw, "crm.search", select=args.get("select"), budget=12_000)
messages.append({"role": "tool", "content": result.text}) # goes to the model
store_full_payload(result.raw) # keep the original elsewhere
logger.info("tool_result_reduced", extra=result.log_fields())
if not result.complete:
ui.warn(result.summary("crm.search"))
# "crm.search: INCOMPLETE, agent received 7 of 25 items (source reports 443 in total)"
Let the model choose fields by adding an optional select parameter to your
tool schema, for example:
"select": {
"type": "string",
"description": "Comma-separated dot-paths to keep from each item, e.g. id,summary.name. Omit to get all fields."
}
Customising what the model is told
The text written into _meta is part of the agent's prompt. Defaults only
assume the model can call the tool again with select. If your runtime can
do better — e.g. answer a re-select from the cached response, or expose a
tool that queries the stored full payload — say so:
from tool_result_reducer import Messages, reduce_tool_result
msgs = Messages(
incomplete=(
"You did NOT receive all items. Call this tool again with the same "
"arguments plus `select=`; that is served from cache at no cost. "
"Or call query_payload(ref) to read any part of the full response."
),
)
result = reduce_tool_result(raw, "crm.search", messages=msgs)
API
| Name | Purpose |
|---|---|
reduce_tool_result(payload, tool_name="tool", *, select=None, budget=12000, max_overshoot=0, messages=Messages()) |
Main entry point. Returns ReducedResult. |
ReducedResult |
.text (for the model), .raw (original), .complete, .items_included, .items_available, .total_reported, .fields_dropped, .select_error, .outlined, .fallback_char_cut, .summary(), .log_fields() |
Messages |
Model-facing text templates (incomplete, fields_dropped, more_at_source, outline, char_cut). |
parse_select, project, available_paths_for, projection_matched_nothing, repair_envelope_prefix |
The building blocks, exposed for callers that project data outside an agent loop (e.g. ETL steps). |
locate_collection(parsed) |
Finds the main list in an API response. Returns (items, path, total_reported). |
resolve(item, path), MISSING |
Reads a dot-path from one item. Returns MISSING when the path is absent, and None when it exists and is null. |
available_paths(item, depth=2) |
The dot-paths that can be selected on one item. |
Examples
Each agent-loop example runs the same task against a stand-in search tool
(examples/demo_tool.py) whose result is about
108,000 characters. The reducer is a one-line change in each: the model gets
all 30 companies in about 5,600 characters, told which fields were dropped.
| File | Where the reducer goes | Install |
|---|---|---|
basic.py |
No model: what the reducer does to a payload | nothing else |
openai_tool_loop.py |
Before the function_call_output item, in a Responses API loop |
openai |
anthropic_tool_loop.py |
Before the tool_result block, in a Messages API loop |
anthropic |
langchain_tool.py |
Inside the @tool function, so any LangChain agent gets the reduced text |
langchain langchain-openai |
pip install agent-tool-result-reducer openai
export OPENAI_API_KEY=...
python examples/openai_tool_loop.py
Scope
In scope
- JSON (or JSON-serialisable) tool/API results: lists, paginated envelopes, JSON:API, large single objects.
- Character budgets (a proxy for tokens that needs no tokenizer).
- Deterministic, explainable reduction with model-facing and human-facing accounting.
Out of scope (non-goals)
- Summarising with an LLM. This is deterministic and free; run an LLM summariser afterwards if you want one.
- Storing payloads or serving follow-up queries. The library returns
.raw; caching and a "query the full payload" tool belong to your runtime. - Token-exact budgets. Characters are used deliberately; convert with your tokenizer's ratio if needed.
- Framework adapters in the core package. The OpenAI, Anthropic and LangChain examples show the one line each needs; the package stays free of dependencies.
- Non-JSON formats (XML, CSV, HTML) beyond the plain character fallback.
Design decisions
- Fields before items. Twenty-five items with fewer fields lets the model make one informed follow-up; twenty items with all fields forces it to guess what it's missing.
- Existence, not value.
nullis an answer; a missing path is a mistake. - The budget is strict by default. At least one item is always kept, so the budget is exceeded only when the first item alone does not fit. A bounded cut of one record would be worse than a slightly larger whole one.
- You can allow a small overshoot. The size of the
_metablock is estimated while filling, so a result sometimes lands a few dozen characters over, and strict mode then drops a whole item to get back under.max_overshoot=200keeps that item and accepts a result up to 200 characters over the budget. Use it when the budget is a cost target; keep the default when it is a hard limit. - Budgets under about 1,000 characters are too small. The
_metablock itself needs several hundred characters, so the result will exceed them. - Text is kept as written. Non-ASCII text (Hindi, Japanese, emoji) is
measured and returned as real characters, not as
\uescapes. - No dependencies. Standard library only, so it fits any stack.
Compared with
| Approach | Valid JSON | Keeps whole items | Tells the model what's missing |
|---|---|---|---|
| Truncate to N chars (most frameworks' default) | ✗ | ✗ | Rarely |
| LLM summarisation of the result | n/a | ✗ (lossy) | ✗ |
| agent-tool-result-reducer | ✓ | ✓ | ✓ counts, totals, dropped fields |
Status and roadmap
v0.1 — extracted from a production agent runtime, where it handles every tool result.
- Core reducer, select projection, auto-fit, outline fallback
- Configurable model-facing messages
- Unit tests, including randomised checks of the invariants (valid JSON, whole items, budget) and non-ASCII text
- CI (tests on 3.10–3.15)
- More tests: deep nesting, very wide objects
- Published on PyPI
- Examples for the OpenAI, Anthropic and LangChain tool loops
- Optional token-based budget via a pluggable length function
Development
pip install -e ".[dev]"
pytest
Feedback and contributing
- Bugs and requests: open an issue.
- Design questions (for example, whether the budget should be in tokens): join the feedback thread, or start your own in Design reviews.
- Pull requests are welcome; see CONTRIBUTING.
License
MIT © Ajeet Singh Kushwaha. Built at Aryabhatta Labs.
Metadata
Release files for agent-tool-result-reducer 0.2.3
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| agent_tool_result_reducer-0.2.3.tar.gz | 22.2 kB | With provenance | Details for agent_tool_result_reducer-0.2.3.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| agent_tool_result_reducer-0.2.3-py3-none-any.whl | Python 3 | none | any | Details for agent_tool_result_reducer-0.2.3-py3-none-any.whl |
Total release size: 41.5 kB
Release files / agent_tool_result_reducer-0.2.3.tar.gz
| Download URL | agent_tool_result_reducer-0.2.3.tar.gz |
|---|---|
| Size | 22.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
aad7882692686732db59ee1c2222370146ef3794f8e39798fae7ba9224fa8448
|
|
BLAKE2b-256 checksum How to use checksums |
6a74873dc9f3be87be998e11a341b893a0caea6fc8d1f4d4701010f3b21f8f10
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.
Transparency logRelease files / agent_tool_result_reducer-0.2.3-py3-none-any.whl
| Download URL | agent_tool_result_reducer-0.2.3-py3-none-any.whl |
|---|---|
| Size | 19.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
763b6d95f7a93a5acf08c2b72b1f6ad7e5a20f44f6a50184d76fdf98281477c7
|
|
BLAKE2b-256 checksum How to use checksums |
f6e1b4ff33028601906d5ead16f91bdc0fbf17605d4bc8fb83a59d56db4f5786
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.
Transparency logSecurity for agent-tool-result-reducer 0.2.3
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for agent_tool_result_reducer-0.2.3.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.