agent-tool-result-reducer 0.2.1__py3-none-any.whl
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.dist-info/METADATA +264 -0
- agent_tool_result_reducer-0.2.1.dist-info/RECORD +8 -0
- agent_tool_result_reducer-0.2.1.dist-info/WHEEL +5 -0
- agent_tool_result_reducer-0.2.1.dist-info/licenses/LICENSE +21 -0
- agent_tool_result_reducer-0.2.1.dist-info/top_level.txt +1 -0
- tool_result_reducer/__init__.py +34 -0
- tool_result_reducer/core.py +826 -0
- tool_result_reducer/py.typed +0 -0
|
@@ -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,8 @@
|
|
|
1
|
+
agent_tool_result_reducer-0.2.1.dist-info/licenses/LICENSE,sha256=uC-vj7JhWtnE26P1hr1IdIHRTEe14Iq6OLJ6yHLEYWc,1077
|
|
2
|
+
tool_result_reducer/__init__.py,sha256=IZGn1r2RPLsksRxC4QQmbNt8LPp89Vwb2-k3Q8lAo2A,708
|
|
3
|
+
tool_result_reducer/core.py,sha256=70YahU86nl05S3hRFw_IkQINeY8XbiyTTa98fdGO5aI,32158
|
|
4
|
+
tool_result_reducer/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
agent_tool_result_reducer-0.2.1.dist-info/METADATA,sha256=0Z-SDUblWGr2cXKZy3nk0WGvbVqo2rTKsQHpuUispz4,13218
|
|
6
|
+
agent_tool_result_reducer-0.2.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
7
|
+
agent_tool_result_reducer-0.2.1.dist-info/top_level.txt,sha256=B4-7BT0TCa0j5qWa6_KlbVTYfYU5TOAKW9CTm3kdt-8,20
|
|
8
|
+
agent_tool_result_reducer-0.2.1.dist-info/RECORD,,
|
|
@@ -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 @@
|
|
|
1
|
+
tool_result_reducer
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Shrink large JSON tool results for LLM agents without silently losing data."""
|
|
2
|
+
|
|
3
|
+
from .core import (
|
|
4
|
+
DEFAULT_RESULT_BUDGET,
|
|
5
|
+
MISSING,
|
|
6
|
+
Messages,
|
|
7
|
+
ReducedResult,
|
|
8
|
+
available_paths,
|
|
9
|
+
available_paths_for,
|
|
10
|
+
locate_collection,
|
|
11
|
+
parse_select,
|
|
12
|
+
project,
|
|
13
|
+
projection_matched_nothing,
|
|
14
|
+
reduce_tool_result,
|
|
15
|
+
repair_envelope_prefix,
|
|
16
|
+
resolve,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"DEFAULT_RESULT_BUDGET",
|
|
21
|
+
"MISSING",
|
|
22
|
+
"Messages",
|
|
23
|
+
"ReducedResult",
|
|
24
|
+
"available_paths",
|
|
25
|
+
"available_paths_for",
|
|
26
|
+
"locate_collection",
|
|
27
|
+
"parse_select",
|
|
28
|
+
"project",
|
|
29
|
+
"projection_matched_nothing",
|
|
30
|
+
"reduce_tool_result",
|
|
31
|
+
"repair_envelope_prefix",
|
|
32
|
+
"resolve",
|
|
33
|
+
]
|
|
34
|
+
__version__ = "0.2.1"
|
|
@@ -0,0 +1,826 @@
|
|
|
1
|
+
"""Bound a tool result by what the agent consumes, not by raw byte count.
|
|
2
|
+
|
|
3
|
+
A tool result is re-sent to the model on every later turn of an agent loop,
|
|
4
|
+
so an unbounded one is billed many times over. The common fix is a flat
|
|
5
|
+
character cap: keep the first N characters, drop the rest.
|
|
6
|
+
|
|
7
|
+
That bounds the wrong thing. In production, an API returned 11 companies in
|
|
8
|
+
77,539 characters; a 12,000-character cap cut mid-object
|
|
9
|
+
(``..."name": "content delivery networ``). The model parsed the two whole
|
|
10
|
+
records it could see, acted on those, and reported success. Nothing said
|
|
11
|
+
that 65,539 characters had been dropped.
|
|
12
|
+
|
|
13
|
+
This module fixes that class of failure:
|
|
14
|
+
|
|
15
|
+
1. **Project before bounding.** If the caller names the fields it needs
|
|
16
|
+
(``select``), keep only those. Eleven records x 14 fields fit the same
|
|
17
|
+
budget several times over.
|
|
18
|
+
2. **Drop fields before items.** When everything still does not fit, drop the
|
|
19
|
+
widest fields across all items (measured, not guessed) so every item
|
|
20
|
+
survives, and say which fields went.
|
|
21
|
+
3. **Cut on item boundaries and say so.** What survives is always valid JSON,
|
|
22
|
+
wrapped in a ``_meta`` block stating how many items were included out of
|
|
23
|
+
how many exist. A partial result can no longer pass for a complete one.
|
|
24
|
+
4. **Outline, don't truncate, large single objects.** Every top-level key
|
|
25
|
+
stays visible and the text stays parseable.
|
|
26
|
+
|
|
27
|
+
Keep ``ReducedResult.raw`` wherever you store full payloads; only
|
|
28
|
+
``ReducedResult.text`` should enter the model's context.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
import json
|
|
34
|
+
from dataclasses import dataclass, field
|
|
35
|
+
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
|
|
36
|
+
|
|
37
|
+
__all__ = [
|
|
38
|
+
"DEFAULT_RESULT_BUDGET",
|
|
39
|
+
"MISSING",
|
|
40
|
+
"Messages",
|
|
41
|
+
"ReducedResult",
|
|
42
|
+
"available_paths",
|
|
43
|
+
"available_paths_for",
|
|
44
|
+
"locate_collection",
|
|
45
|
+
"parse_select",
|
|
46
|
+
"project",
|
|
47
|
+
"projection_matched_nothing",
|
|
48
|
+
"reduce_tool_result",
|
|
49
|
+
"repair_envelope_prefix",
|
|
50
|
+
"resolve",
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
# Default per-result budget in characters.
|
|
54
|
+
DEFAULT_RESULT_BUDGET = 12_000
|
|
55
|
+
|
|
56
|
+
# Room reserved inside the budget for the `_meta` envelope. It is an
|
|
57
|
+
# estimate; the main loop re-fits when the finished text overshoots.
|
|
58
|
+
_ENVELOPE_RESERVE = 700
|
|
59
|
+
|
|
60
|
+
# Keys that conventionally hold the collection in an API envelope. The
|
|
61
|
+
# longest list wins regardless; this set lets the search descend one level
|
|
62
|
+
# deeper through these names.
|
|
63
|
+
_COLLECTION_KEYS = (
|
|
64
|
+
"content",
|
|
65
|
+
"data",
|
|
66
|
+
"items",
|
|
67
|
+
"results",
|
|
68
|
+
"records",
|
|
69
|
+
"rows",
|
|
70
|
+
"elements",
|
|
71
|
+
"entries",
|
|
72
|
+
"values",
|
|
73
|
+
"list",
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
# Keys that conventionally report how many items exist server-side. This is
|
|
77
|
+
# what lets the note say "25 of 443" rather than just "25". "size" is left
|
|
78
|
+
# out on purpose: in paginated responses it is the page size, and reading it
|
|
79
|
+
# as a total tells the model "20 exist" when 11 were returned and more may.
|
|
80
|
+
_TOTAL_KEYS = (
|
|
81
|
+
"total",
|
|
82
|
+
"totalElements",
|
|
83
|
+
"totalCount",
|
|
84
|
+
"total_count",
|
|
85
|
+
"totalResults",
|
|
86
|
+
"total_results",
|
|
87
|
+
"count",
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
# How deep to look for the collection. Three levels covers
|
|
91
|
+
# {"data": {"result": {"items": [...]}}} without wandering into item bodies.
|
|
92
|
+
_MAX_SEARCH_DEPTH = 3
|
|
93
|
+
|
|
94
|
+
# Auto-fit never trims below this many fields per item. Past that point the
|
|
95
|
+
# problem is item count, not field width, and the item-boundary cut with its
|
|
96
|
+
# explicit "incomplete" accounting is the better failure.
|
|
97
|
+
_AUTO_FIT_MIN_FIELDS = 2
|
|
98
|
+
|
|
99
|
+
# How much of a long string survives in a structure outline.
|
|
100
|
+
_OUTLINE_VALUE_CHARS = 200
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@dataclass(frozen=True)
|
|
104
|
+
class Messages:
|
|
105
|
+
"""Text the reducer writes into results for the model to read.
|
|
106
|
+
|
|
107
|
+
The defaults assume only that the model can call the same tool again with
|
|
108
|
+
a ``select`` argument. If your runtime can answer a re-select from a
|
|
109
|
+
cached response, or offers a tool to query the stored full payload, say
|
|
110
|
+
so here: models follow these instructions closely, and a vague hint like
|
|
111
|
+
"narrow the request" can send them back to a metered API repeatedly.
|
|
112
|
+
|
|
113
|
+
``fields_dropped`` and ``outline`` are format strings; see their
|
|
114
|
+
placeholders below.
|
|
115
|
+
"""
|
|
116
|
+
|
|
117
|
+
incomplete: str = (
|
|
118
|
+
"You did NOT receive all items. Do not describe this result as "
|
|
119
|
+
"complete, and do not report the items you can see as if they were "
|
|
120
|
+
"the whole set. To get every item, call this tool again with the SAME "
|
|
121
|
+
"arguments plus `select=` naming only the fields you need (dot-paths "
|
|
122
|
+
"relative to one item, e.g. id,summary.name)."
|
|
123
|
+
)
|
|
124
|
+
# Placeholders: {count} items kept, {fields} comma-separated names.
|
|
125
|
+
fields_dropped: str = (
|
|
126
|
+
"All {count} items are included, but these fields were dropped to "
|
|
127
|
+
"fit: {fields}. If a dropped field is needed, call this tool again "
|
|
128
|
+
"with the SAME arguments but set `select=` to ONLY an id field plus "
|
|
129
|
+
"the dropped field(s)."
|
|
130
|
+
)
|
|
131
|
+
# Placeholder: {chars} original size, formatted with thousands separators.
|
|
132
|
+
outline: str = (
|
|
133
|
+
"This response is a single large object ({chars} chars), shown as a "
|
|
134
|
+
"structural outline: long strings are cut, nested objects/lists are "
|
|
135
|
+
"summarised as {{_type, _keys/_len, _first}}. Every key that exists "
|
|
136
|
+
"is listed."
|
|
137
|
+
)
|
|
138
|
+
# Placeholders: {dropped} characters cut, {tool} tool name.
|
|
139
|
+
char_cut: str = (
|
|
140
|
+
"\n\n... [truncated {dropped:,} characters of this {tool} result. "
|
|
141
|
+
"Narrow the request (filters, a smaller page size, fewer fields) if "
|
|
142
|
+
"you need the part that was cut.]"
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
DEFAULT_MESSAGES = Messages()
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
@dataclass
|
|
150
|
+
class ReducedResult:
|
|
151
|
+
"""What the model gets, plus everything needed to explain it."""
|
|
152
|
+
|
|
153
|
+
text: str
|
|
154
|
+
raw: str
|
|
155
|
+
complete: bool = True
|
|
156
|
+
chars_raw: int = 0
|
|
157
|
+
chars_kept: int = 0
|
|
158
|
+
items_included: Optional[int] = None
|
|
159
|
+
items_available: Optional[int] = None
|
|
160
|
+
total_reported: Optional[int] = None
|
|
161
|
+
fields_kept: List[str] = field(default_factory=list)
|
|
162
|
+
source_path: Optional[str] = None
|
|
163
|
+
# Set when a supplied `select` matched no field on any item, so the
|
|
164
|
+
# projection was discarded rather than served as an empty result.
|
|
165
|
+
select_error: Optional[str] = None
|
|
166
|
+
# Set when the payload was not JSON and we fell back to cutting
|
|
167
|
+
# characters: the one path that can hand the model broken syntax.
|
|
168
|
+
fallback_char_cut: bool = False
|
|
169
|
+
# Set when a large single object was replaced by a structure outline.
|
|
170
|
+
outlined: bool = False
|
|
171
|
+
# field -> approx chars/item removed by auto-fit. Non-empty means every
|
|
172
|
+
# item IS included (complete=True) but these fields were dropped.
|
|
173
|
+
fields_dropped: Dict[str, int] = field(default_factory=dict)
|
|
174
|
+
|
|
175
|
+
@property
|
|
176
|
+
def items_dropped(self) -> int:
|
|
177
|
+
if self.items_available is None or self.items_included is None:
|
|
178
|
+
return 0
|
|
179
|
+
return max(0, self.items_available - self.items_included)
|
|
180
|
+
|
|
181
|
+
@property
|
|
182
|
+
def chars_dropped(self) -> int:
|
|
183
|
+
return max(0, self.chars_raw - self.chars_kept)
|
|
184
|
+
|
|
185
|
+
def log_fields(self) -> Dict[str, Any]:
|
|
186
|
+
"""Structured fields for a log/metrics event."""
|
|
187
|
+
return {
|
|
188
|
+
"chars_raw": self.chars_raw,
|
|
189
|
+
"chars_kept": self.chars_kept,
|
|
190
|
+
"items_included": self.items_included,
|
|
191
|
+
"items_available": self.items_available,
|
|
192
|
+
"total_reported": self.total_reported,
|
|
193
|
+
"complete": self.complete,
|
|
194
|
+
"fallback_char_cut": self.fallback_char_cut or None,
|
|
195
|
+
"outlined": self.outlined or None,
|
|
196
|
+
"fields_dropped": len(self.fields_dropped) or None,
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
def summary(self, tool_name: str = "tool") -> str:
|
|
200
|
+
"""One line for humans (logs, run UIs) describing what was lost."""
|
|
201
|
+
if self.complete and not self.fields_dropped:
|
|
202
|
+
return f"{tool_name}: complete ({self.chars_kept:,} chars)"
|
|
203
|
+
if self.items_available is not None and self.items_included is not None:
|
|
204
|
+
scope = f"{self.items_included} of {self.items_available} items"
|
|
205
|
+
if self.total_reported and self.total_reported > self.items_available:
|
|
206
|
+
scope += f" (source reports {self.total_reported:,} in total)"
|
|
207
|
+
if self.fields_dropped:
|
|
208
|
+
scope += f", dropped fields: {', '.join(sorted(self.fields_dropped))}"
|
|
209
|
+
else:
|
|
210
|
+
scope = f"{self.chars_kept:,} of {self.chars_raw:,} characters"
|
|
211
|
+
state = "complete" if self.complete else "INCOMPLETE"
|
|
212
|
+
return f"{tool_name}: {state}, agent received {scope}"
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
# ── select / projection ────────────────────────────────────────────────
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def parse_select(select: Any) -> List[str]:
|
|
219
|
+
"""Normalise a `select` argument into a list of dot-paths.
|
|
220
|
+
|
|
221
|
+
Accepts a comma-separated string (what a model passes) or a list (what a
|
|
222
|
+
config holds). Empty/absent means "no projection".
|
|
223
|
+
"""
|
|
224
|
+
if not select:
|
|
225
|
+
return []
|
|
226
|
+
if isinstance(select, str):
|
|
227
|
+
parts: Iterable[str] = select.split(",")
|
|
228
|
+
elif isinstance(select, (list, tuple)):
|
|
229
|
+
parts = [str(p) for p in select]
|
|
230
|
+
else:
|
|
231
|
+
return []
|
|
232
|
+
return [p.strip() for p in parts if str(p).strip()]
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
# "No such path", as distinct from "the path exists and holds null". The
|
|
236
|
+
# projection renders both as None, but deciding whether a select matched
|
|
237
|
+
# anything has to tell them apart.
|
|
238
|
+
_MISSING = object()
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _resolve(item: Any, path: str) -> Any:
|
|
242
|
+
"""Read a dot-path, returning ``_MISSING`` when the path does not exist."""
|
|
243
|
+
cur = item
|
|
244
|
+
for segment in path.split("."):
|
|
245
|
+
if isinstance(cur, dict):
|
|
246
|
+
if segment not in cur:
|
|
247
|
+
return _MISSING
|
|
248
|
+
cur = cur[segment]
|
|
249
|
+
elif isinstance(cur, list) and segment.isdigit():
|
|
250
|
+
idx = int(segment)
|
|
251
|
+
if idx >= len(cur):
|
|
252
|
+
return _MISSING
|
|
253
|
+
cur = cur[idx]
|
|
254
|
+
else:
|
|
255
|
+
return _MISSING
|
|
256
|
+
return cur
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _dig(item: Any, path: str) -> Any:
|
|
260
|
+
value = _resolve(item, path)
|
|
261
|
+
return None if value is _MISSING else value
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
#: Returned by :func:`resolve` when a path does not exist on an item.
|
|
265
|
+
MISSING = _MISSING
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def resolve(item: Any, path: str) -> Any:
|
|
269
|
+
"""Read a dot-path from one item, telling "absent" from "present and null".
|
|
270
|
+
|
|
271
|
+
Returns the value at ``path`` (``summary.name``, ``tags.0``), or
|
|
272
|
+
:data:`MISSING` when the path does not exist. A path that exists and holds
|
|
273
|
+
``None`` returns ``None``::
|
|
274
|
+
|
|
275
|
+
resolve({"a": {"b": None}}, "a.b") is None
|
|
276
|
+
resolve({"a": {}}, "a.b") is MISSING
|
|
277
|
+
"""
|
|
278
|
+
return _resolve(item, path)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def project(item: Any, select: Sequence[str], *, full_path_keys: bool = False) -> Any:
|
|
282
|
+
"""Keep only the selected dot-paths of one item.
|
|
283
|
+
|
|
284
|
+
``full_path_keys=False`` (default) flattens each path to its last
|
|
285
|
+
segment: ``summary.name`` becomes ``name``, the shape an LLM reads most
|
|
286
|
+
easily. On a collision the later path keeps its full name so no selected
|
|
287
|
+
field is lost.
|
|
288
|
+
|
|
289
|
+
``full_path_keys=True`` keys by the path verbatim, for callers that must
|
|
290
|
+
reference fields later by exactly the path they selected.
|
|
291
|
+
"""
|
|
292
|
+
if not isinstance(item, dict):
|
|
293
|
+
return item
|
|
294
|
+
out: Dict[str, Any] = {}
|
|
295
|
+
for path in select:
|
|
296
|
+
value = _dig(item, path)
|
|
297
|
+
if full_path_keys:
|
|
298
|
+
out[path] = value
|
|
299
|
+
continue
|
|
300
|
+
key = path.rsplit(".", 1)[-1]
|
|
301
|
+
if key in out:
|
|
302
|
+
key = path
|
|
303
|
+
out[key] = value
|
|
304
|
+
return out
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _available_paths(item: Any, prefix: str = "", depth: int = 2) -> List[str]:
|
|
308
|
+
if not isinstance(item, dict) or depth <= 0:
|
|
309
|
+
return []
|
|
310
|
+
out: List[str] = []
|
|
311
|
+
for key, value in item.items():
|
|
312
|
+
path = f"{prefix}.{key}" if prefix else key
|
|
313
|
+
if isinstance(value, dict) and depth > 1:
|
|
314
|
+
nested = _available_paths(value, path, depth - 1)
|
|
315
|
+
out.extend(nested or [path])
|
|
316
|
+
else:
|
|
317
|
+
out.append(path)
|
|
318
|
+
return out
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def available_paths(item: Any, depth: int = 2) -> List[str]:
|
|
322
|
+
"""Dot-paths that can be selected on one item, ``depth`` levels deep.
|
|
323
|
+
|
|
324
|
+
``{"id": 1, "summary": {"name": "x"}}`` gives ``["id", "summary.name"]``.
|
|
325
|
+
Anything that is not a dict gives ``[]``.
|
|
326
|
+
"""
|
|
327
|
+
return _available_paths(item, "", depth)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def available_paths_for(items: Sequence[Any]) -> List[str]:
|
|
331
|
+
"""Dot-paths a caller could select, read from the first dict item."""
|
|
332
|
+
for item in items:
|
|
333
|
+
if isinstance(item, dict):
|
|
334
|
+
return _available_paths(item)
|
|
335
|
+
return []
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def projection_matched_nothing(items: Sequence[Any], fields: Sequence[str]) -> bool:
|
|
339
|
+
"""True when no selected path exists on any item.
|
|
340
|
+
|
|
341
|
+
Asks about *existence*, not value: a provider that answers
|
|
342
|
+
``"funding_stage": null`` for every item has answered the question, and
|
|
343
|
+
the selection must be kept. Only a path found nowhere is a mistake.
|
|
344
|
+
"""
|
|
345
|
+
if not fields or not items:
|
|
346
|
+
return False
|
|
347
|
+
saw_dict = False
|
|
348
|
+
for item in items:
|
|
349
|
+
if not isinstance(item, dict):
|
|
350
|
+
continue
|
|
351
|
+
saw_dict = True
|
|
352
|
+
if any(_resolve(item, path) is not _MISSING for path in fields):
|
|
353
|
+
return False
|
|
354
|
+
return saw_dict
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def repair_envelope_prefix(
|
|
358
|
+
items: Sequence[Any], fields: Sequence[str]
|
|
359
|
+
) -> Optional[List[str]]:
|
|
360
|
+
"""Selected paths minus a shared leading segment, when that rescues them.
|
|
361
|
+
|
|
362
|
+
Models write selects against the shape they see, and the reducer's own
|
|
363
|
+
envelope names its collection ``items``, so ``items.id,items.name`` is a
|
|
364
|
+
reasonable guess. Returns the stripped paths when every path is dotted,
|
|
365
|
+
all share one first segment, and stripping makes the select match;
|
|
366
|
+
otherwise None.
|
|
367
|
+
"""
|
|
368
|
+
if not fields or not all("." in f for f in fields):
|
|
369
|
+
return None
|
|
370
|
+
prefixes = {f.split(".", 1)[0] for f in fields}
|
|
371
|
+
if len(prefixes) != 1:
|
|
372
|
+
return None
|
|
373
|
+
stripped = [f.split(".", 1)[1] for f in fields]
|
|
374
|
+
if projection_matched_nothing(items, stripped):
|
|
375
|
+
return None
|
|
376
|
+
return stripped
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
# ── sizing ─────────────────────────────────────────────────────────────
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def _dumps(value: Any, *, ensure_ascii: bool = False) -> str:
|
|
383
|
+
# Non-ASCII text is kept as written. Escaping it ("\u0906...") makes each
|
|
384
|
+
# character cost six, so Hindi or Japanese text would be measured several
|
|
385
|
+
# times larger than it is and trimmed for no reason.
|
|
386
|
+
return json.dumps(value, default=str, separators=(",", ":"), ensure_ascii=ensure_ascii)
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def _encodable(text: str) -> bool:
|
|
390
|
+
"""False when ``text`` holds a lone surrogate and cannot be sent as UTF-8."""
|
|
391
|
+
try:
|
|
392
|
+
text.encode("utf-8")
|
|
393
|
+
except UnicodeEncodeError:
|
|
394
|
+
return False
|
|
395
|
+
return True
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def _field_costs(items: Sequence[Any]) -> Dict[str, int]:
|
|
399
|
+
"""Total serialized chars each top-level field costs across all items.
|
|
400
|
+
|
|
401
|
+
Empty when the items are not uniformly dicts.
|
|
402
|
+
"""
|
|
403
|
+
costs: Dict[str, int] = {}
|
|
404
|
+
for item in items:
|
|
405
|
+
if not isinstance(item, dict):
|
|
406
|
+
return {}
|
|
407
|
+
for key, value in item.items():
|
|
408
|
+
# + key, quotes, colon, separator
|
|
409
|
+
costs[key] = costs.get(key, 0) + len(_dumps(value)) + len(key) + 4
|
|
410
|
+
return costs
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def _auto_fit(
|
|
414
|
+
items: Sequence[Any], room: int
|
|
415
|
+
) -> Tuple[Optional[List[Any]], Dict[str, int]]:
|
|
416
|
+
"""Make ALL items fit by dropping the widest fields, not the last items.
|
|
417
|
+
|
|
418
|
+
The model cannot see the budget, so letting it discover one by trial and
|
|
419
|
+
error costs whole LLM turns. The reducer holds every field's measured
|
|
420
|
+
size; dropping the most expensive fields until everything fits is one
|
|
421
|
+
deterministic pass (widest first, ties by name).
|
|
422
|
+
|
|
423
|
+
Returns ``(fitted_items, {field: ~chars_per_item_dropped})``, or
|
|
424
|
+
``(None, {})`` when trimming fields cannot help.
|
|
425
|
+
"""
|
|
426
|
+
costs = _field_costs(items)
|
|
427
|
+
if len(costs) <= _AUTO_FIT_MIN_FIELDS:
|
|
428
|
+
return None, {}
|
|
429
|
+
|
|
430
|
+
keep = set(costs)
|
|
431
|
+
dropped: Dict[str, int] = {}
|
|
432
|
+
order = sorted(costs, key=lambda k: (-costs[k], k))
|
|
433
|
+
|
|
434
|
+
def measure(keys: set) -> int:
|
|
435
|
+
return (
|
|
436
|
+
sum(
|
|
437
|
+
len(_dumps({k: v for k, v in item.items() if k in keys})) + 1
|
|
438
|
+
for item in items
|
|
439
|
+
)
|
|
440
|
+
+ 2
|
|
441
|
+
)
|
|
442
|
+
|
|
443
|
+
size = measure(keep)
|
|
444
|
+
for key in order:
|
|
445
|
+
if size <= room or len(keep) <= _AUTO_FIT_MIN_FIELDS:
|
|
446
|
+
break
|
|
447
|
+
keep.discard(key)
|
|
448
|
+
dropped[key] = max(1, costs[key] // max(1, len(items)))
|
|
449
|
+
size = measure(keep)
|
|
450
|
+
|
|
451
|
+
if size > room or not dropped:
|
|
452
|
+
return None, {}
|
|
453
|
+
# Comprehension over item.items() preserves the provider's key order.
|
|
454
|
+
fitted = [{k: v for k, v in item.items() if k in keep} for item in items]
|
|
455
|
+
return fitted, dropped
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
# ── locating the collection ────────────────────────────────────────────
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def _first_total(container: Any) -> Optional[int]:
|
|
462
|
+
"""Pull a server-reported total off an envelope dict."""
|
|
463
|
+
if not isinstance(container, dict):
|
|
464
|
+
return None
|
|
465
|
+
for key in _TOTAL_KEYS:
|
|
466
|
+
value = container.get(key)
|
|
467
|
+
if isinstance(value, bool):
|
|
468
|
+
continue
|
|
469
|
+
if isinstance(value, int):
|
|
470
|
+
return value
|
|
471
|
+
if isinstance(value, str) and value.isdigit():
|
|
472
|
+
return int(value)
|
|
473
|
+
if isinstance(value, dict): # e.g. {"page": {"totalElements": N}}
|
|
474
|
+
nested = _first_total(value)
|
|
475
|
+
if nested is not None:
|
|
476
|
+
return nested
|
|
477
|
+
for key in ("page", "pagination", "meta", "paging"):
|
|
478
|
+
nested_container = container.get(key)
|
|
479
|
+
if isinstance(nested_container, dict):
|
|
480
|
+
nested = _first_total(nested_container)
|
|
481
|
+
if nested is not None:
|
|
482
|
+
return nested
|
|
483
|
+
return None
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def _locate_collection(
|
|
487
|
+
parsed: Any,
|
|
488
|
+
) -> Tuple[Optional[List[Any]], Optional[str], Optional[int]]:
|
|
489
|
+
"""Find the payload's main collection: ``(items, path, total_reported)``.
|
|
490
|
+
|
|
491
|
+
The longest list of objects wins, so a short sibling ("errors",
|
|
492
|
+
"warnings") never displaces the real payload.
|
|
493
|
+
"""
|
|
494
|
+
if isinstance(parsed, list):
|
|
495
|
+
return parsed, None, None
|
|
496
|
+
if not isinstance(parsed, dict):
|
|
497
|
+
return None, None, None
|
|
498
|
+
|
|
499
|
+
# JSON:API: `data` is the payload and `included` is a sidecar of related
|
|
500
|
+
# resources that is often the LONGER list. Longest-wins would project
|
|
501
|
+
# the sidecar and hand the model relationship stubs.
|
|
502
|
+
data = parsed.get("data")
|
|
503
|
+
if (
|
|
504
|
+
isinstance(data, list)
|
|
505
|
+
and data
|
|
506
|
+
and isinstance(data[0], dict)
|
|
507
|
+
and isinstance(parsed.get("included"), list)
|
|
508
|
+
):
|
|
509
|
+
return data, "data", _first_total(parsed)
|
|
510
|
+
|
|
511
|
+
best: Optional[List[Any]] = None
|
|
512
|
+
best_path: Optional[str] = None
|
|
513
|
+
best_owner: Any = None
|
|
514
|
+
|
|
515
|
+
def walk(node: Any, path: str, depth: int) -> None:
|
|
516
|
+
nonlocal best, best_path, best_owner
|
|
517
|
+
if depth > _MAX_SEARCH_DEPTH or not isinstance(node, dict):
|
|
518
|
+
return
|
|
519
|
+
for key, value in node.items():
|
|
520
|
+
child_path = f"{path}.{key}" if path else key
|
|
521
|
+
if isinstance(value, list):
|
|
522
|
+
# Only a list of objects is worth projecting; a list of
|
|
523
|
+
# scalars is cheap and better left alone.
|
|
524
|
+
if value and isinstance(value[0], dict):
|
|
525
|
+
if best is None or len(value) > len(best):
|
|
526
|
+
best, best_path, best_owner = value, child_path, node
|
|
527
|
+
continue
|
|
528
|
+
if isinstance(value, dict) and (
|
|
529
|
+
depth < _MAX_SEARCH_DEPTH or key in _COLLECTION_KEYS
|
|
530
|
+
):
|
|
531
|
+
walk(value, child_path, depth + 1)
|
|
532
|
+
|
|
533
|
+
walk(parsed, "", 1)
|
|
534
|
+
|
|
535
|
+
total = _first_total(best_owner) or _first_total(parsed)
|
|
536
|
+
return best, best_path, total
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def locate_collection(parsed: Any) -> Tuple[Optional[List[Any]], Optional[str], Optional[int]]:
|
|
540
|
+
"""Find the main list of items in a parsed API response.
|
|
541
|
+
|
|
542
|
+
Returns ``(items, path, total_reported)``:
|
|
543
|
+
|
|
544
|
+
* ``items``: the list, or ``None`` when the response holds no list of
|
|
545
|
+
objects (a single object, a scalar).
|
|
546
|
+
* ``path``: where it was found (``"data.results"``), or ``None`` when the
|
|
547
|
+
response itself is the list.
|
|
548
|
+
* ``total_reported``: the total the server reports (``total``,
|
|
549
|
+
``totalElements``, ``page.totalElements``, ...), or ``None``.
|
|
550
|
+
|
|
551
|
+
This is the same search :func:`reduce_tool_result` uses: up to three
|
|
552
|
+
levels deep, the longest list of objects wins, and JSON:API ``data`` beats
|
|
553
|
+
a longer ``included``.
|
|
554
|
+
"""
|
|
555
|
+
return _locate_collection(parsed)
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
# ── non-collection fallbacks ───────────────────────────────────────────
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def _outline_value(value: Any, depth: int) -> Any:
|
|
562
|
+
"""One node of a structure outline: keep scalars, summarise containers."""
|
|
563
|
+
if isinstance(value, str):
|
|
564
|
+
if len(value) > _OUTLINE_VALUE_CHARS:
|
|
565
|
+
return value[:_OUTLINE_VALUE_CHARS] + f"… [{len(value):,} chars]"
|
|
566
|
+
return value
|
|
567
|
+
if isinstance(value, dict):
|
|
568
|
+
if depth <= 0:
|
|
569
|
+
return {"_type": "object", "_keys": list(value)[:24]}
|
|
570
|
+
return {k: _outline_value(v, depth - 1) for k, v in value.items()}
|
|
571
|
+
if isinstance(value, list):
|
|
572
|
+
summary: Dict[str, Any] = {"_type": "list", "_len": len(value)}
|
|
573
|
+
if value and depth > 0:
|
|
574
|
+
summary["_first"] = _outline_value(value[0], depth - 1)
|
|
575
|
+
return summary
|
|
576
|
+
return value
|
|
577
|
+
|
|
578
|
+
|
|
579
|
+
def _structure_outline(parsed: Dict[str, Any], budget: int) -> Optional[str]:
|
|
580
|
+
"""A valid-JSON structural view of a large non-collection object.
|
|
581
|
+
|
|
582
|
+
Tries progressively shallower depths; None when even the shallowest view
|
|
583
|
+
cannot fit, which only a pathologically wide object hits.
|
|
584
|
+
"""
|
|
585
|
+
for depth in (2, 1, 0):
|
|
586
|
+
outlined = {k: _outline_value(v, depth) for k, v in parsed.items()}
|
|
587
|
+
text = _dumps(outlined)
|
|
588
|
+
if len(text) <= budget:
|
|
589
|
+
return text
|
|
590
|
+
return None
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
# ── entry point ────────────────────────────────────────────────────────
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def reduce_tool_result(
|
|
597
|
+
payload: Any,
|
|
598
|
+
tool_name: str = "tool",
|
|
599
|
+
*,
|
|
600
|
+
select: Any = None,
|
|
601
|
+
budget: int = DEFAULT_RESULT_BUDGET,
|
|
602
|
+
max_overshoot: int = 0,
|
|
603
|
+
messages: Messages = DEFAULT_MESSAGES,
|
|
604
|
+
) -> ReducedResult:
|
|
605
|
+
"""Bound a tool result to what the agent can use, and say what was left out.
|
|
606
|
+
|
|
607
|
+
Args:
|
|
608
|
+
payload: The tool's output: a JSON string, or any JSON-serialisable
|
|
609
|
+
value (dict, list, ...). Non-JSON strings are accepted.
|
|
610
|
+
tool_name: Used in fallback text and summaries.
|
|
611
|
+
select: Fields to keep per item, as a comma-separated string or a
|
|
612
|
+
list of dot-paths relative to one item (``"id,summary.name"``).
|
|
613
|
+
Applied whenever supplied, not only when the payload is oversized:
|
|
614
|
+
a caller that knows which fields it consumes should not pay for
|
|
615
|
+
the rest on every later turn.
|
|
616
|
+
budget: Maximum characters for ``ReducedResult.text``. One item is
|
|
617
|
+
always kept, so the budget is exceeded only when the first item
|
|
618
|
+
alone does not fit. A budget under about 1,000 characters has no
|
|
619
|
+
room for the ``_meta`` block.
|
|
620
|
+
max_overshoot: Characters the result may run over ``budget`` before
|
|
621
|
+
an item is dropped to bring it back. The default, 0, holds the
|
|
622
|
+
budget exactly. The size of the ``_meta`` block is estimated
|
|
623
|
+
while filling, so a result can land a few dozen characters over;
|
|
624
|
+
a small allowance (say 200) keeps the item that strict mode would
|
|
625
|
+
drop for the sake of those characters.
|
|
626
|
+
messages: Instructions written into the result for the model.
|
|
627
|
+
"""
|
|
628
|
+
raw_text = payload if isinstance(payload, str) else _dumps(payload)
|
|
629
|
+
# A lone surrogate (a broken "\ud83d" from upstream) cannot be encoded as
|
|
630
|
+
# UTF-8, so in that rare case the output falls back to ASCII escapes.
|
|
631
|
+
ascii_only = not _encodable(raw_text)
|
|
632
|
+
if ascii_only and not isinstance(payload, str):
|
|
633
|
+
raw_text = _dumps(payload, ensure_ascii=True)
|
|
634
|
+
chars_raw = len(raw_text)
|
|
635
|
+
fields = parse_select(select)
|
|
636
|
+
budget = max(1, int(budget or DEFAULT_RESULT_BUDGET))
|
|
637
|
+
limit = budget + max(0, int(max_overshoot or 0))
|
|
638
|
+
|
|
639
|
+
if chars_raw <= budget and not fields:
|
|
640
|
+
return ReducedResult(
|
|
641
|
+
text=raw_text, raw=raw_text, chars_raw=chars_raw, chars_kept=chars_raw
|
|
642
|
+
)
|
|
643
|
+
|
|
644
|
+
try:
|
|
645
|
+
parsed = json.loads(raw_text) if isinstance(payload, str) else payload
|
|
646
|
+
except (json.JSONDecodeError, TypeError, ValueError):
|
|
647
|
+
parsed = None
|
|
648
|
+
|
|
649
|
+
items, source_path, total_reported = _locate_collection(parsed)
|
|
650
|
+
|
|
651
|
+
if items is None:
|
|
652
|
+
# Not a collection: a single large object, or not JSON at all.
|
|
653
|
+
if chars_raw <= budget:
|
|
654
|
+
return ReducedResult(
|
|
655
|
+
text=raw_text, raw=raw_text, chars_raw=chars_raw, chars_kept=chars_raw
|
|
656
|
+
)
|
|
657
|
+
if isinstance(parsed, dict):
|
|
658
|
+
outline = _structure_outline(parsed, max(1, budget - _ENVELOPE_RESERVE))
|
|
659
|
+
if outline is not None:
|
|
660
|
+
envelope = {
|
|
661
|
+
"outline": json.loads(outline),
|
|
662
|
+
"_meta": {
|
|
663
|
+
"complete": False,
|
|
664
|
+
"chars_raw": chars_raw,
|
|
665
|
+
"note": messages.outline.format(chars=f"{chars_raw:,}"),
|
|
666
|
+
},
|
|
667
|
+
}
|
|
668
|
+
text = _dumps(envelope, ensure_ascii=ascii_only)
|
|
669
|
+
return ReducedResult(
|
|
670
|
+
text=text,
|
|
671
|
+
raw=raw_text,
|
|
672
|
+
complete=False,
|
|
673
|
+
chars_raw=chars_raw,
|
|
674
|
+
chars_kept=len(text),
|
|
675
|
+
outlined=True,
|
|
676
|
+
)
|
|
677
|
+
dropped = chars_raw - budget
|
|
678
|
+
text = raw_text[:budget] + messages.char_cut.format(dropped=dropped, tool=tool_name)
|
|
679
|
+
return ReducedResult(
|
|
680
|
+
text=text,
|
|
681
|
+
raw=raw_text,
|
|
682
|
+
complete=False,
|
|
683
|
+
chars_raw=chars_raw,
|
|
684
|
+
chars_kept=len(text),
|
|
685
|
+
fallback_char_cut=True,
|
|
686
|
+
)
|
|
687
|
+
|
|
688
|
+
# A select written against the envelope (`items.id`) instead of one item:
|
|
689
|
+
# strip the shared prefix, but only when the select as given matches
|
|
690
|
+
# nothing, so a genuine `items` field on an item is never touched.
|
|
691
|
+
prefix_stripped: Optional[str] = None
|
|
692
|
+
if fields and projection_matched_nothing(items, fields):
|
|
693
|
+
repaired = repair_envelope_prefix(items, fields)
|
|
694
|
+
if repaired is not None:
|
|
695
|
+
prefix_stripped = fields[0].split(".", 1)[0]
|
|
696
|
+
fields = repaired
|
|
697
|
+
|
|
698
|
+
projected = [project(item, fields) for item in items] if fields else list(items)
|
|
699
|
+
|
|
700
|
+
# A select that matched nothing must never be served as a complete
|
|
701
|
+
# result: that is a silent empty answer wearing a success badge. Drop the
|
|
702
|
+
# projection and say which paths actually exist.
|
|
703
|
+
select_error: Optional[str] = None
|
|
704
|
+
if projection_matched_nothing(items, fields):
|
|
705
|
+
available = available_paths_for(items)
|
|
706
|
+
select_error = (
|
|
707
|
+
f"The select {list(fields)} matched no field on any of the "
|
|
708
|
+
f"{len(items)} items, so it was ignored and the full records are "
|
|
709
|
+
f"shown instead (trimmed to fit). Select from these paths: "
|
|
710
|
+
f"{', '.join(available[:40])}"
|
|
711
|
+
)
|
|
712
|
+
projected = list(items)
|
|
713
|
+
fields = []
|
|
714
|
+
|
|
715
|
+
def render(kept: List[Any], fields_dropped: Dict[str, int]) -> Tuple[str, bool]:
|
|
716
|
+
"""The finished text for these items, and whether it is complete."""
|
|
717
|
+
complete = len(kept) == len(items)
|
|
718
|
+
meta: Dict[str, Any] = {
|
|
719
|
+
"items_included": len(kept),
|
|
720
|
+
"items_available": len(items),
|
|
721
|
+
"complete": complete,
|
|
722
|
+
}
|
|
723
|
+
if total_reported is not None and total_reported != len(items):
|
|
724
|
+
meta["total_reported_by_source"] = total_reported
|
|
725
|
+
if source_path:
|
|
726
|
+
meta["source_path"] = source_path
|
|
727
|
+
if fields:
|
|
728
|
+
# Only what actually survived auto-fit.
|
|
729
|
+
meta["fields_selected"] = [
|
|
730
|
+
f
|
|
731
|
+
for f in fields
|
|
732
|
+
if f.rsplit(".", 1)[-1] not in fields_dropped and f not in fields_dropped
|
|
733
|
+
]
|
|
734
|
+
if prefix_stripped:
|
|
735
|
+
meta["select_prefix_stripped"] = (
|
|
736
|
+
f"Your select paths were prefixed with '{prefix_stripped}.'; "
|
|
737
|
+
f"that prefix names the collection, not a field, so it was "
|
|
738
|
+
f"stripped. Select paths are relative to a single item "
|
|
739
|
+
f"(e.g. summary.name)."
|
|
740
|
+
)
|
|
741
|
+
if select_error:
|
|
742
|
+
meta["select_error"] = select_error
|
|
743
|
+
if fields_dropped:
|
|
744
|
+
names = sorted(fields_dropped)
|
|
745
|
+
listed = ", ".join(names[:8]) + (" …" if len(names) > 8 else "")
|
|
746
|
+
meta["fields_dropped"] = fields_dropped
|
|
747
|
+
meta["fields_dropped_note"] = messages.fields_dropped.format(
|
|
748
|
+
count=len(kept), fields=listed
|
|
749
|
+
)
|
|
750
|
+
if not complete:
|
|
751
|
+
meta["items_omitted"] = len(items) - len(kept)
|
|
752
|
+
meta["warning"] = messages.incomplete
|
|
753
|
+
# Which fields are eating the budget, so a follow-up select is
|
|
754
|
+
# informed rather than guessed. Measured on the original items.
|
|
755
|
+
costs = _field_costs(items)
|
|
756
|
+
if costs:
|
|
757
|
+
top = sorted(costs.items(), key=lambda kv: (-kv[1], kv[0]))[:3]
|
|
758
|
+
meta["field_costs"] = dict(top)
|
|
759
|
+
text = json.dumps({"items": kept, "_meta": meta}, default=str, ensure_ascii=ascii_only)
|
|
760
|
+
return text, complete
|
|
761
|
+
|
|
762
|
+
# Build the whole result; if the finished text still overflows (the
|
|
763
|
+
# envelope reserve is an estimate), shrink the room by the overshoot and
|
|
764
|
+
# rebuild. The fill always keeps at least one item.
|
|
765
|
+
projected_full = projected
|
|
766
|
+
room = max(1, budget - _ENVELOPE_RESERVE)
|
|
767
|
+
for _ in range(3):
|
|
768
|
+
projected = projected_full
|
|
769
|
+
|
|
770
|
+
fields_dropped: Dict[str, int] = {}
|
|
771
|
+
projected_size = sum(len(_dumps(item)) + 1 for item in projected) + 2
|
|
772
|
+
if projected_size > room:
|
|
773
|
+
fitted, fields_dropped = _auto_fit(projected, room)
|
|
774
|
+
if fitted is not None:
|
|
775
|
+
projected = fitted
|
|
776
|
+
|
|
777
|
+
# Fill on item boundaries; serialise each item once (O(n)).
|
|
778
|
+
kept: List[Any] = []
|
|
779
|
+
used = 2 # the enclosing "[]"
|
|
780
|
+
for item in projected:
|
|
781
|
+
size = len(_dumps(item)) + 1
|
|
782
|
+
if kept and used + size > room:
|
|
783
|
+
break
|
|
784
|
+
kept.append(item)
|
|
785
|
+
used += size
|
|
786
|
+
|
|
787
|
+
text, complete = render(kept, fields_dropped)
|
|
788
|
+
if len(text) <= budget:
|
|
789
|
+
break
|
|
790
|
+
room = max(1, room - (len(text) - budget))
|
|
791
|
+
|
|
792
|
+
# The passes above usually land inside the budget. When they do not (by
|
|
793
|
+
# more than the caller allows), keep the largest number of whole items
|
|
794
|
+
# that does: the text grows with every item kept, so a binary search finds
|
|
795
|
+
# it in a few renders. If even one item cannot fit, the budget is out of
|
|
796
|
+
# reach and dropping the others would lose data for nothing, so the result
|
|
797
|
+
# is left as it is.
|
|
798
|
+
if (
|
|
799
|
+
len(text) > limit
|
|
800
|
+
and len(kept) > 1
|
|
801
|
+
and len(render(projected[:1], fields_dropped)[0]) <= limit
|
|
802
|
+
):
|
|
803
|
+
low, high, fits = 2, len(kept) - 1, 1
|
|
804
|
+
while low <= high:
|
|
805
|
+
middle = (low + high) // 2
|
|
806
|
+
if len(render(projected[:middle], fields_dropped)[0]) <= limit:
|
|
807
|
+
fits, low = middle, middle + 1
|
|
808
|
+
else:
|
|
809
|
+
high = middle - 1
|
|
810
|
+
kept = projected[:fits]
|
|
811
|
+
text, complete = render(kept, fields_dropped)
|
|
812
|
+
|
|
813
|
+
return ReducedResult(
|
|
814
|
+
text=text,
|
|
815
|
+
raw=raw_text,
|
|
816
|
+
complete=complete,
|
|
817
|
+
chars_raw=chars_raw,
|
|
818
|
+
chars_kept=len(text),
|
|
819
|
+
items_included=len(kept),
|
|
820
|
+
items_available=len(items),
|
|
821
|
+
total_reported=total_reported,
|
|
822
|
+
fields_kept=list(fields),
|
|
823
|
+
source_path=source_path,
|
|
824
|
+
select_error=select_error,
|
|
825
|
+
fields_dropped=fields_dropped,
|
|
826
|
+
)
|
|
File without changes
|