返回资讯中心
外部精选
软件工程
#开发者实时流

agent-tool-result-reducer:按字符预算裁剪大 JSON 工具结果并告知模型取舍

来源标题:Show HN: Fit large JSON tool results into an LLM's context without losing data

Python 零依赖库 agent-tool-result-reducer 可按字符预算裁剪 API 或工具返回的大 JSON,只按完整条目边界截断,并在 _meta 块中说明实际传入与缺失的内容。示例中约 10 万字符的 25 条公司数据被压缩到 1506 字符有效 JSON。要求 Python 3.10+,无运行时依赖。

Hacker News 最新ajeetsk2026/11/24 · 今天18 分钟阅读

以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。

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.

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}, ...}

More in Usage and Examples.

Give agent builders a drop-in function that sits between "tool returned something" and "append it to the model's context", so that:

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.

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.

pip install agent-tool-result-reducer openai export OPENAI_API_KEY=... python examples/openai_tool_loop.py

Scope

In scope

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. null is 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 _meta block 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=200 keeps 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 _meta block 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 \u escapes.

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.

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.

正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。

打开原文
去社区讨论 →