agent-tool-result-reducer 0.2.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agent_tool_result_reducer-0.2.1/LICENSE +21 -0
- agent_tool_result_reducer-0.2.1/PKG-INFO +264 -0
- agent_tool_result_reducer-0.2.1/README.md +239 -0
- agent_tool_result_reducer-0.2.1/pyproject.toml +43 -0
- agent_tool_result_reducer-0.2.1/setup.cfg +4 -0
- agent_tool_result_reducer-0.2.1/src/agent_tool_result_reducer.egg-info/PKG-INFO +264 -0
- agent_tool_result_reducer-0.2.1/src/agent_tool_result_reducer.egg-info/SOURCES.txt +12 -0
- agent_tool_result_reducer-0.2.1/src/agent_tool_result_reducer.egg-info/dependency_links.txt +1 -0
- agent_tool_result_reducer-0.2.1/src/agent_tool_result_reducer.egg-info/requires.txt +3 -0
- agent_tool_result_reducer-0.2.1/src/agent_tool_result_reducer.egg-info/top_level.txt +1 -0
- agent_tool_result_reducer-0.2.1/src/tool_result_reducer/__init__.py +34 -0
- agent_tool_result_reducer-0.2.1/src/tool_result_reducer/core.py +826 -0
- agent_tool_result_reducer-0.2.1/src/tool_result_reducer/py.typed +0 -0
- agent_tool_result_reducer-0.2.1/tests/test_reducer.py +303 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ajeet Singh Kushwaha
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agent-tool-result-reducer
|
|
3
|
+
Version: 0.2.1
|
|
4
|
+
Summary: Shrink large JSON tool results for LLM agents without silently losing data.
|
|
5
|
+
Author: Ajeet Singh Kushwaha
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/AryabhattaLabs/agent-tool-result-reducer
|
|
8
|
+
Project-URL: Issues, https://github.com/AryabhattaLabs/agent-tool-result-reducer/issues
|
|
9
|
+
Keywords: llm,agents,tool-calling,context-window,json
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Provides-Extra: dev
|
|
23
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# Agent Tool Result Reducer: Fit Large JSON Tool Results into an LLM Agent's Context Window
|
|
27
|
+
|
|
28
|
+
[](https://github.com/AryabhattaLabs/agent-tool-result-reducer/actions/workflows/ci.yml)
|
|
29
|
+

|
|
30
|
+

|
|
31
|
+
|
|
32
|
+
Shrink large JSON tool results for LLM agents **without silently losing data**.
|
|
33
|
+
|
|
34
|
+
**Package:** `agent-tool-result-reducer` · **Import:** `tool_result_reducer`
|
|
35
|
+
|
|
36
|
+
A zero-dependency Python library that fits an API/tool response into a
|
|
37
|
+
character budget by **selecting fields, dropping the widest fields, and cutting
|
|
38
|
+
only on whole-item boundaries** — and that always tells the model, in a
|
|
39
|
+
`_meta` block, exactly what it did and did not receive.
|
|
40
|
+
|
|
41
|
+
```text
|
|
42
|
+
Before: [{"id":1,"name":"Acme","description":"…"},{"id":2,"name":"content delivery networ ← cut mid-object
|
|
43
|
+
After: {"items":[…25 whole items…],"_meta":{"items_included":25,"items_available":25,
|
|
44
|
+
"total_reported_by_source":443,"fields_dropped":{"description":3617},…}}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## Install
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
pip install git+https://github.com/AryabhattaLabs/agent-tool-result-reducer
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Requires Python 3.10+. No runtime dependencies. Not yet on PyPI.
|
|
56
|
+
|
|
57
|
+
## Quick start
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
from tool_result_reducer import reduce_tool_result
|
|
61
|
+
|
|
62
|
+
rows = [{"id": i, "name": f"Company {i}", "description": "long text " * 400} for i in range(25)]
|
|
63
|
+
response = {"results": rows, "total": 443} # a page of 25 companies, about 100,000 characters
|
|
64
|
+
|
|
65
|
+
result = reduce_tool_result(response, "crm.search", budget=4_000)
|
|
66
|
+
|
|
67
|
+
result.text # 1,259 characters of valid JSON: this is what goes to the model
|
|
68
|
+
result.complete # True: all 25 items are there; the wide `description` field was dropped
|
|
69
|
+
result.summary("crm.search")
|
|
70
|
+
# crm.search: complete, agent received 25 of 25 items (source reports 443 in total), dropped fields: description
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
The model is told what happened, in the result itself:
|
|
74
|
+
|
|
75
|
+
```json
|
|
76
|
+
"_meta": {"items_included": 25, "items_available": 25, "complete": true,
|
|
77
|
+
"total_reported_by_source": 443, "fields_dropped": {"description": 4017}, ...}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
More in [Usage](#usage) and [`examples/basic.py`](examples/basic.py).
|
|
81
|
+
|
|
82
|
+
## Objective
|
|
83
|
+
|
|
84
|
+
Give agent builders a drop-in function that sits between **"tool returned
|
|
85
|
+
something"** and **"append it to the model's context"**, so that:
|
|
86
|
+
|
|
87
|
+
1. A result fits the budget you set, short of cutting a single item in half
|
|
88
|
+
(cost and context-window control).
|
|
89
|
+
2. What the model receives is **always valid JSON** made of **whole items**.
|
|
90
|
+
3. When anything is left out, the model is **told explicitly**, with counts and
|
|
91
|
+
a concrete way to get the rest — so it cannot report a partial result as
|
|
92
|
+
complete.
|
|
93
|
+
|
|
94
|
+
## The problem
|
|
95
|
+
|
|
96
|
+
Every tool result is re-sent to the model on every later turn of an agent
|
|
97
|
+
loop, so large results are expensive and frameworks cap them. The usual cap
|
|
98
|
+
is "keep the first N characters". That causes a quiet, serious failure:
|
|
99
|
+
|
|
100
|
+
> In production, a search API returned **11 companies in 77,539 characters**.
|
|
101
|
+
> A 12,000-character cap kept the start and cut mid-object
|
|
102
|
+
> (`…"name": "content delivery networ`). The model parsed the **2** whole
|
|
103
|
+
> records it could see, wrote 2 rows to a spreadsheet, and **reported
|
|
104
|
+
> success**. Nothing indicated that 9 records had been dropped.
|
|
105
|
+
|
|
106
|
+
The cap bounded *bytes*. What matters is *what the agent consumes*: with only
|
|
107
|
+
the 14 fields the task needed, all 11 records fit the same budget several
|
|
108
|
+
times over.
|
|
109
|
+
|
|
110
|
+
## How it works
|
|
111
|
+
|
|
112
|
+
For each tool result, in order:
|
|
113
|
+
|
|
114
|
+
| Step | What happens | Why |
|
|
115
|
+
|---|---|---|
|
|
116
|
+
| 1. Pass-through | Under budget and no `select` → returned unchanged. | Zero overhead for the common case. |
|
|
117
|
+
| 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". |
|
|
118
|
+
| 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. |
|
|
119
|
+
| 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". |
|
|
120
|
+
| 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. |
|
|
121
|
+
| 6. Cut on item boundaries | Still too big → keep as many **whole** items as fit. | Never broken JSON, never half a record. |
|
|
122
|
+
| 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. |
|
|
123
|
+
| 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. |
|
|
124
|
+
|
|
125
|
+
## Usage
|
|
126
|
+
|
|
127
|
+
```python
|
|
128
|
+
from tool_result_reducer import reduce_tool_result
|
|
129
|
+
|
|
130
|
+
raw = call_my_tool(**args) # dict, list or JSON string
|
|
131
|
+
result = reduce_tool_result(raw, "crm.search", select=args.get("select"), budget=12_000)
|
|
132
|
+
|
|
133
|
+
messages.append({"role": "tool", "content": result.text}) # goes to the model
|
|
134
|
+
store_full_payload(result.raw) # keep the original elsewhere
|
|
135
|
+
logger.info("tool_result_reduced", extra=result.log_fields())
|
|
136
|
+
if not result.complete:
|
|
137
|
+
ui.warn(result.summary("crm.search"))
|
|
138
|
+
# "crm.search: INCOMPLETE, agent received 7 of 25 items (source reports 443 in total)"
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
Let the model choose fields by adding an optional `select` parameter to your
|
|
142
|
+
tool schema, for example:
|
|
143
|
+
|
|
144
|
+
```json
|
|
145
|
+
"select": {
|
|
146
|
+
"type": "string",
|
|
147
|
+
"description": "Comma-separated dot-paths to keep from each item, e.g. id,summary.name. Omit to get all fields."
|
|
148
|
+
}
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
### Customising what the model is told
|
|
152
|
+
|
|
153
|
+
The text written into `_meta` is part of the agent's prompt. Defaults only
|
|
154
|
+
assume the model can call the tool again with `select`. If your runtime can
|
|
155
|
+
do better — e.g. answer a re-select from the cached response, or expose a
|
|
156
|
+
tool that queries the stored full payload — say so:
|
|
157
|
+
|
|
158
|
+
```python
|
|
159
|
+
from tool_result_reducer import Messages, reduce_tool_result
|
|
160
|
+
|
|
161
|
+
msgs = Messages(
|
|
162
|
+
incomplete=(
|
|
163
|
+
"You did NOT receive all items. Call this tool again with the same "
|
|
164
|
+
"arguments plus `select=`; that is served from cache at no cost. "
|
|
165
|
+
"Or call query_payload(ref) to read any part of the full response."
|
|
166
|
+
),
|
|
167
|
+
)
|
|
168
|
+
result = reduce_tool_result(raw, "crm.search", messages=msgs)
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
### API
|
|
172
|
+
|
|
173
|
+
| Name | Purpose |
|
|
174
|
+
|---|---|
|
|
175
|
+
| `reduce_tool_result(payload, tool_name="tool", *, select=None, budget=12000, max_overshoot=0, messages=Messages())` | Main entry point. Returns `ReducedResult`. |
|
|
176
|
+
| `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()` |
|
|
177
|
+
| `Messages` | Model-facing text templates (`incomplete`, `fields_dropped`, `outline`, `char_cut`). |
|
|
178
|
+
| `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). |
|
|
179
|
+
| `locate_collection(parsed)` | Finds the main list in an API response. Returns `(items, path, total_reported)`. |
|
|
180
|
+
| `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. |
|
|
181
|
+
| `available_paths(item, depth=2)` | The dot-paths that can be selected on one item. |
|
|
182
|
+
|
|
183
|
+
See [`examples/basic.py`](examples/basic.py).
|
|
184
|
+
|
|
185
|
+
## Scope
|
|
186
|
+
|
|
187
|
+
**In scope**
|
|
188
|
+
- JSON (or JSON-serialisable) tool/API results: lists, paginated envelopes,
|
|
189
|
+
JSON:API, large single objects.
|
|
190
|
+
- Character budgets (a proxy for tokens that needs no tokenizer).
|
|
191
|
+
- Deterministic, explainable reduction with model-facing and human-facing
|
|
192
|
+
accounting.
|
|
193
|
+
|
|
194
|
+
**Out of scope (non-goals)**
|
|
195
|
+
- **Summarising with an LLM.** This is deterministic and free; run an LLM
|
|
196
|
+
summariser afterwards if you want one.
|
|
197
|
+
- **Storing payloads or serving follow-up queries.** The library returns
|
|
198
|
+
`.raw`; caching and a "query the full payload" tool belong to your runtime.
|
|
199
|
+
- **Token-exact budgets.** Characters are used deliberately; convert
|
|
200
|
+
with your tokenizer's ratio if needed.
|
|
201
|
+
- **Framework adapters** (LangChain, OpenAI Agents SDK, Claude Agent SDK) in
|
|
202
|
+
the core package — planned as thin examples, not dependencies.
|
|
203
|
+
- Non-JSON formats (XML, CSV, HTML) beyond the plain character fallback.
|
|
204
|
+
|
|
205
|
+
## Design decisions
|
|
206
|
+
|
|
207
|
+
- **Fields before items.** Twenty-five items with fewer fields lets the model
|
|
208
|
+
make one informed follow-up; twenty items with all fields forces it to guess
|
|
209
|
+
what it's missing.
|
|
210
|
+
- **Existence, not value.** `null` is an answer; a missing path is a mistake.
|
|
211
|
+
- **The budget is strict by default.** At least one item is always kept, so
|
|
212
|
+
the budget is exceeded only when the first item alone does not fit. A
|
|
213
|
+
bounded cut of one record would be worse than a slightly larger whole one.
|
|
214
|
+
- **You can allow a small overshoot.** The size of the `_meta` block is
|
|
215
|
+
estimated while filling, so a result sometimes lands a few dozen characters
|
|
216
|
+
over, and strict mode then drops a whole item to get back under.
|
|
217
|
+
`max_overshoot=200` keeps that item and accepts a result up to 200
|
|
218
|
+
characters over the budget. Use it when the budget is a cost target; keep
|
|
219
|
+
the default when it is a hard limit.
|
|
220
|
+
- **Budgets under about 1,000 characters are too small.** The `_meta` block
|
|
221
|
+
itself needs several hundred characters, so the result will exceed them.
|
|
222
|
+
- **Text is kept as written.** Non-ASCII text (Hindi, Japanese, emoji) is
|
|
223
|
+
measured and returned as real characters, not as `\u` escapes.
|
|
224
|
+
- **No dependencies.** Standard library only, so it fits any stack.
|
|
225
|
+
|
|
226
|
+
## Compared with
|
|
227
|
+
|
|
228
|
+
| Approach | Valid JSON | Keeps whole items | Tells the model what's missing |
|
|
229
|
+
|---|---|---|---|
|
|
230
|
+
| Truncate to N chars (most frameworks' default) | ✗ | ✗ | Rarely |
|
|
231
|
+
| LLM summarisation of the result | n/a | ✗ (lossy) | ✗ |
|
|
232
|
+
| **agent-tool-result-reducer** | ✓ | ✓ | ✓ counts, totals, dropped fields |
|
|
233
|
+
|
|
234
|
+
## Status and roadmap
|
|
235
|
+
|
|
236
|
+
**v0.1 — extracted from a production agent runtime, where it handles every tool result.**
|
|
237
|
+
|
|
238
|
+
- [x] Core reducer, select projection, auto-fit, outline fallback
|
|
239
|
+
- [x] Configurable model-facing messages
|
|
240
|
+
- [x] Unit tests, including randomised checks of the invariants (valid JSON,
|
|
241
|
+
whole items, budget) and non-ASCII text
|
|
242
|
+
- [x] CI (tests on 3.10–3.15)
|
|
243
|
+
- [ ] More tests: deep nesting, very wide objects
|
|
244
|
+
- [ ] Publish to PyPI
|
|
245
|
+
- [ ] Examples for the OpenAI, Anthropic and LangChain tool loops
|
|
246
|
+
- [ ] Optional token-based budget via a pluggable length function
|
|
247
|
+
|
|
248
|
+
## Development
|
|
249
|
+
|
|
250
|
+
```bash
|
|
251
|
+
pip install -e ".[dev]"
|
|
252
|
+
pytest
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
## Feedback and contributing
|
|
256
|
+
|
|
257
|
+
- **Bugs and requests:** [open an issue](https://github.com/AryabhattaLabs/agent-tool-result-reducer/issues).
|
|
258
|
+
- **Design questions** (for example, whether the budget should be in tokens): start or join a thread in
|
|
259
|
+
[Design reviews](https://github.com/AryabhattaLabs/community/discussions/categories/design-reviews).
|
|
260
|
+
- **Pull requests** are welcome; see [CONTRIBUTING](https://github.com/AryabhattaLabs/.github/blob/main/CONTRIBUTING.md).
|
|
261
|
+
|
|
262
|
+
## License
|
|
263
|
+
|
|
264
|
+
MIT © Ajeet Singh Kushwaha. Built at [Aryabhatta Labs](https://aryabhattalabs.com/#developers).
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
# Agent Tool Result Reducer: Fit Large JSON Tool Results into an LLM Agent's Context Window
|
|
2
|
+
|
|
3
|
+
[](https://github.com/AryabhattaLabs/agent-tool-result-reducer/actions/workflows/ci.yml)
|
|
4
|
+

|
|
5
|
+

|
|
6
|
+
|
|
7
|
+
Shrink large JSON tool results for LLM agents **without silently losing data**.
|
|
8
|
+
|
|
9
|
+
**Package:** `agent-tool-result-reducer` · **Import:** `tool_result_reducer`
|
|
10
|
+
|
|
11
|
+
A zero-dependency Python library that fits an API/tool response into a
|
|
12
|
+
character budget by **selecting fields, dropping the widest fields, and cutting
|
|
13
|
+
only on whole-item boundaries** — and that always tells the model, in a
|
|
14
|
+
`_meta` block, exactly what it did and did not receive.
|
|
15
|
+
|
|
16
|
+
```text
|
|
17
|
+
Before: [{"id":1,"name":"Acme","description":"…"},{"id":2,"name":"content delivery networ ← cut mid-object
|
|
18
|
+
After: {"items":[…25 whole items…],"_meta":{"items_included":25,"items_available":25,
|
|
19
|
+
"total_reported_by_source":443,"fields_dropped":{"description":3617},…}}
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
---
|
|
23
|
+
|
|
24
|
+
## Install
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pip install git+https://github.com/AryabhattaLabs/agent-tool-result-reducer
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Requires Python 3.10+. No runtime dependencies. Not yet on PyPI.
|
|
31
|
+
|
|
32
|
+
## Quick start
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
from tool_result_reducer import reduce_tool_result
|
|
36
|
+
|
|
37
|
+
rows = [{"id": i, "name": f"Company {i}", "description": "long text " * 400} for i in range(25)]
|
|
38
|
+
response = {"results": rows, "total": 443} # a page of 25 companies, about 100,000 characters
|
|
39
|
+
|
|
40
|
+
result = reduce_tool_result(response, "crm.search", budget=4_000)
|
|
41
|
+
|
|
42
|
+
result.text # 1,259 characters of valid JSON: this is what goes to the model
|
|
43
|
+
result.complete # True: all 25 items are there; the wide `description` field was dropped
|
|
44
|
+
result.summary("crm.search")
|
|
45
|
+
# crm.search: complete, agent received 25 of 25 items (source reports 443 in total), dropped fields: description
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
The model is told what happened, in the result itself:
|
|
49
|
+
|
|
50
|
+
```json
|
|
51
|
+
"_meta": {"items_included": 25, "items_available": 25, "complete": true,
|
|
52
|
+
"total_reported_by_source": 443, "fields_dropped": {"description": 4017}, ...}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
More in [Usage](#usage) and [`examples/basic.py`](examples/basic.py).
|
|
56
|
+
|
|
57
|
+
## Objective
|
|
58
|
+
|
|
59
|
+
Give agent builders a drop-in function that sits between **"tool returned
|
|
60
|
+
something"** and **"append it to the model's context"**, so that:
|
|
61
|
+
|
|
62
|
+
1. A result fits the budget you set, short of cutting a single item in half
|
|
63
|
+
(cost and context-window control).
|
|
64
|
+
2. What the model receives is **always valid JSON** made of **whole items**.
|
|
65
|
+
3. When anything is left out, the model is **told explicitly**, with counts and
|
|
66
|
+
a concrete way to get the rest — so it cannot report a partial result as
|
|
67
|
+
complete.
|
|
68
|
+
|
|
69
|
+
## The problem
|
|
70
|
+
|
|
71
|
+
Every tool result is re-sent to the model on every later turn of an agent
|
|
72
|
+
loop, so large results are expensive and frameworks cap them. The usual cap
|
|
73
|
+
is "keep the first N characters". That causes a quiet, serious failure:
|
|
74
|
+
|
|
75
|
+
> In production, a search API returned **11 companies in 77,539 characters**.
|
|
76
|
+
> A 12,000-character cap kept the start and cut mid-object
|
|
77
|
+
> (`…"name": "content delivery networ`). The model parsed the **2** whole
|
|
78
|
+
> records it could see, wrote 2 rows to a spreadsheet, and **reported
|
|
79
|
+
> success**. Nothing indicated that 9 records had been dropped.
|
|
80
|
+
|
|
81
|
+
The cap bounded *bytes*. What matters is *what the agent consumes*: with only
|
|
82
|
+
the 14 fields the task needed, all 11 records fit the same budget several
|
|
83
|
+
times over.
|
|
84
|
+
|
|
85
|
+
## How it works
|
|
86
|
+
|
|
87
|
+
For each tool result, in order:
|
|
88
|
+
|
|
89
|
+
| Step | What happens | Why |
|
|
90
|
+
|---|---|---|
|
|
91
|
+
| 1. Pass-through | Under budget and no `select` → returned unchanged. | Zero overhead for the common case. |
|
|
92
|
+
| 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". |
|
|
93
|
+
| 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. |
|
|
94
|
+
| 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". |
|
|
95
|
+
| 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. |
|
|
96
|
+
| 6. Cut on item boundaries | Still too big → keep as many **whole** items as fit. | Never broken JSON, never half a record. |
|
|
97
|
+
| 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. |
|
|
98
|
+
| 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. |
|
|
99
|
+
|
|
100
|
+
## Usage
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
from tool_result_reducer import reduce_tool_result
|
|
104
|
+
|
|
105
|
+
raw = call_my_tool(**args) # dict, list or JSON string
|
|
106
|
+
result = reduce_tool_result(raw, "crm.search", select=args.get("select"), budget=12_000)
|
|
107
|
+
|
|
108
|
+
messages.append({"role": "tool", "content": result.text}) # goes to the model
|
|
109
|
+
store_full_payload(result.raw) # keep the original elsewhere
|
|
110
|
+
logger.info("tool_result_reduced", extra=result.log_fields())
|
|
111
|
+
if not result.complete:
|
|
112
|
+
ui.warn(result.summary("crm.search"))
|
|
113
|
+
# "crm.search: INCOMPLETE, agent received 7 of 25 items (source reports 443 in total)"
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Let the model choose fields by adding an optional `select` parameter to your
|
|
117
|
+
tool schema, for example:
|
|
118
|
+
|
|
119
|
+
```json
|
|
120
|
+
"select": {
|
|
121
|
+
"type": "string",
|
|
122
|
+
"description": "Comma-separated dot-paths to keep from each item, e.g. id,summary.name. Omit to get all fields."
|
|
123
|
+
}
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
### Customising what the model is told
|
|
127
|
+
|
|
128
|
+
The text written into `_meta` is part of the agent's prompt. Defaults only
|
|
129
|
+
assume the model can call the tool again with `select`. If your runtime can
|
|
130
|
+
do better — e.g. answer a re-select from the cached response, or expose a
|
|
131
|
+
tool that queries the stored full payload — say so:
|
|
132
|
+
|
|
133
|
+
```python
|
|
134
|
+
from tool_result_reducer import Messages, reduce_tool_result
|
|
135
|
+
|
|
136
|
+
msgs = Messages(
|
|
137
|
+
incomplete=(
|
|
138
|
+
"You did NOT receive all items. Call this tool again with the same "
|
|
139
|
+
"arguments plus `select=`; that is served from cache at no cost. "
|
|
140
|
+
"Or call query_payload(ref) to read any part of the full response."
|
|
141
|
+
),
|
|
142
|
+
)
|
|
143
|
+
result = reduce_tool_result(raw, "crm.search", messages=msgs)
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
### API
|
|
147
|
+
|
|
148
|
+
| Name | Purpose |
|
|
149
|
+
|---|---|
|
|
150
|
+
| `reduce_tool_result(payload, tool_name="tool", *, select=None, budget=12000, max_overshoot=0, messages=Messages())` | Main entry point. Returns `ReducedResult`. |
|
|
151
|
+
| `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()` |
|
|
152
|
+
| `Messages` | Model-facing text templates (`incomplete`, `fields_dropped`, `outline`, `char_cut`). |
|
|
153
|
+
| `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). |
|
|
154
|
+
| `locate_collection(parsed)` | Finds the main list in an API response. Returns `(items, path, total_reported)`. |
|
|
155
|
+
| `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. |
|
|
156
|
+
| `available_paths(item, depth=2)` | The dot-paths that can be selected on one item. |
|
|
157
|
+
|
|
158
|
+
See [`examples/basic.py`](examples/basic.py).
|
|
159
|
+
|
|
160
|
+
## Scope
|
|
161
|
+
|
|
162
|
+
**In scope**
|
|
163
|
+
- JSON (or JSON-serialisable) tool/API results: lists, paginated envelopes,
|
|
164
|
+
JSON:API, large single objects.
|
|
165
|
+
- Character budgets (a proxy for tokens that needs no tokenizer).
|
|
166
|
+
- Deterministic, explainable reduction with model-facing and human-facing
|
|
167
|
+
accounting.
|
|
168
|
+
|
|
169
|
+
**Out of scope (non-goals)**
|
|
170
|
+
- **Summarising with an LLM.** This is deterministic and free; run an LLM
|
|
171
|
+
summariser afterwards if you want one.
|
|
172
|
+
- **Storing payloads or serving follow-up queries.** The library returns
|
|
173
|
+
`.raw`; caching and a "query the full payload" tool belong to your runtime.
|
|
174
|
+
- **Token-exact budgets.** Characters are used deliberately; convert
|
|
175
|
+
with your tokenizer's ratio if needed.
|
|
176
|
+
- **Framework adapters** (LangChain, OpenAI Agents SDK, Claude Agent SDK) in
|
|
177
|
+
the core package — planned as thin examples, not dependencies.
|
|
178
|
+
- Non-JSON formats (XML, CSV, HTML) beyond the plain character fallback.
|
|
179
|
+
|
|
180
|
+
## Design decisions
|
|
181
|
+
|
|
182
|
+
- **Fields before items.** Twenty-five items with fewer fields lets the model
|
|
183
|
+
make one informed follow-up; twenty items with all fields forces it to guess
|
|
184
|
+
what it's missing.
|
|
185
|
+
- **Existence, not value.** `null` is an answer; a missing path is a mistake.
|
|
186
|
+
- **The budget is strict by default.** At least one item is always kept, so
|
|
187
|
+
the budget is exceeded only when the first item alone does not fit. A
|
|
188
|
+
bounded cut of one record would be worse than a slightly larger whole one.
|
|
189
|
+
- **You can allow a small overshoot.** The size of the `_meta` block is
|
|
190
|
+
estimated while filling, so a result sometimes lands a few dozen characters
|
|
191
|
+
over, and strict mode then drops a whole item to get back under.
|
|
192
|
+
`max_overshoot=200` keeps that item and accepts a result up to 200
|
|
193
|
+
characters over the budget. Use it when the budget is a cost target; keep
|
|
194
|
+
the default when it is a hard limit.
|
|
195
|
+
- **Budgets under about 1,000 characters are too small.** The `_meta` block
|
|
196
|
+
itself needs several hundred characters, so the result will exceed them.
|
|
197
|
+
- **Text is kept as written.** Non-ASCII text (Hindi, Japanese, emoji) is
|
|
198
|
+
measured and returned as real characters, not as `\u` escapes.
|
|
199
|
+
- **No dependencies.** Standard library only, so it fits any stack.
|
|
200
|
+
|
|
201
|
+
## Compared with
|
|
202
|
+
|
|
203
|
+
| Approach | Valid JSON | Keeps whole items | Tells the model what's missing |
|
|
204
|
+
|---|---|---|---|
|
|
205
|
+
| Truncate to N chars (most frameworks' default) | ✗ | ✗ | Rarely |
|
|
206
|
+
| LLM summarisation of the result | n/a | ✗ (lossy) | ✗ |
|
|
207
|
+
| **agent-tool-result-reducer** | ✓ | ✓ | ✓ counts, totals, dropped fields |
|
|
208
|
+
|
|
209
|
+
## Status and roadmap
|
|
210
|
+
|
|
211
|
+
**v0.1 — extracted from a production agent runtime, where it handles every tool result.**
|
|
212
|
+
|
|
213
|
+
- [x] Core reducer, select projection, auto-fit, outline fallback
|
|
214
|
+
- [x] Configurable model-facing messages
|
|
215
|
+
- [x] Unit tests, including randomised checks of the invariants (valid JSON,
|
|
216
|
+
whole items, budget) and non-ASCII text
|
|
217
|
+
- [x] CI (tests on 3.10–3.15)
|
|
218
|
+
- [ ] More tests: deep nesting, very wide objects
|
|
219
|
+
- [ ] Publish to PyPI
|
|
220
|
+
- [ ] Examples for the OpenAI, Anthropic and LangChain tool loops
|
|
221
|
+
- [ ] Optional token-based budget via a pluggable length function
|
|
222
|
+
|
|
223
|
+
## Development
|
|
224
|
+
|
|
225
|
+
```bash
|
|
226
|
+
pip install -e ".[dev]"
|
|
227
|
+
pytest
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
## Feedback and contributing
|
|
231
|
+
|
|
232
|
+
- **Bugs and requests:** [open an issue](https://github.com/AryabhattaLabs/agent-tool-result-reducer/issues).
|
|
233
|
+
- **Design questions** (for example, whether the budget should be in tokens): start or join a thread in
|
|
234
|
+
[Design reviews](https://github.com/AryabhattaLabs/community/discussions/categories/design-reviews).
|
|
235
|
+
- **Pull requests** are welcome; see [CONTRIBUTING](https://github.com/AryabhattaLabs/.github/blob/main/CONTRIBUTING.md).
|
|
236
|
+
|
|
237
|
+
## License
|
|
238
|
+
|
|
239
|
+
MIT © Ajeet Singh Kushwaha. Built at [Aryabhatta Labs](https://aryabhattalabs.com/#developers).
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "agent-tool-result-reducer"
|
|
7
|
+
version = "0.2.1"
|
|
8
|
+
description = "Shrink large JSON tool results for LLM agents without silently losing data."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{ name = "Ajeet Singh Kushwaha" }]
|
|
14
|
+
keywords = ["llm", "agents", "tool-calling", "context-window", "json"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Programming Language :: Python :: 3.10",
|
|
19
|
+
"Programming Language :: Python :: 3.11",
|
|
20
|
+
"Programming Language :: Python :: 3.12",
|
|
21
|
+
"Programming Language :: Python :: 3.13",
|
|
22
|
+
"Programming Language :: Python :: 3.14",
|
|
23
|
+
"Programming Language :: Python :: 3.15",
|
|
24
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
25
|
+
]
|
|
26
|
+
dependencies = []
|
|
27
|
+
|
|
28
|
+
[project.optional-dependencies]
|
|
29
|
+
dev = ["pytest>=7"]
|
|
30
|
+
|
|
31
|
+
[project.urls]
|
|
32
|
+
Homepage = "https://github.com/AryabhattaLabs/agent-tool-result-reducer"
|
|
33
|
+
Issues = "https://github.com/AryabhattaLabs/agent-tool-result-reducer/issues"
|
|
34
|
+
|
|
35
|
+
[tool.setuptools.packages.find]
|
|
36
|
+
where = ["src"]
|
|
37
|
+
|
|
38
|
+
[tool.setuptools.package-data]
|
|
39
|
+
tool_result_reducer = ["py.typed"]
|
|
40
|
+
|
|
41
|
+
[tool.pytest.ini_options]
|
|
42
|
+
testpaths = ["tests"]
|
|
43
|
+
pythonpath = ["src"]
|