feat(tool-loop): add token-budget awareness and tool output pruning #61
Labels
No labels
auto/blocked-by-deps
auto/ci-timeout
auto/claimed-implementer
auto/claimed-merge
auto/claimed-reviewer
auto/driver-down
auto/invariant-violation
auto/last-attempt-tier-0
auto/last-attempt-tier-1
auto/last-attempt-tier-2
auto/last-attempt-tier-min
Automation Tracking
auto/needs-conflict-resolution
auto/needs-implementer
auto/postmortem
auto/ready-to-merge
auto/restart-throttled
auto/revert
auto/sentinel
auto/stale-inactivity
auto/unstable
Blocked
Bounty
$100
Bounty
$1000
Bounty
$10000
Bounty
$20
Bounty
$2000
Bounty
$250
Bounty
$50
Bounty
$500
Bounty
$5000
Bounty
$750
MoSCoW
Could have
MoSCoW
Must have
MoSCoW
Should have
Needs Feedback
Points
1
Points
13
Points
2
Points
21
Points
3
Points
34
Points
5
Points
55
Points
8
Points
88
Priority
Backlog
Priority
CI Blocker
Priority
Critical
Priority
High
Priority
Low
Priority
Medium
Signed-off: Owner
Signed-off: Scrum Master
Signed-off: Tech Lead
Spike
State
Completed
State
Duplicate
State
In Progress
State
In Review
State
Paused
State
Unverified
State
Verified
State
Wont Do
Type
Automation
Type
Bug
Type
Discussion
Type
Documentation
Type
Epic
Type
Feature
Type
Legendary
Type
Refactor
Type
Support
Type
Task
Type
Testing
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Blocks
Depends on
#77 Epic: LLM Agent Runtime Stabilization — reliability, resource enforcement & correctness hardening
cleveragents/cleveractors-core
#62 feat(tool-loop): add token-budget awareness and tool output pruning
cleveragents/cleveractors-core
Reference
cleveragents/cleveractors-core#61
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Metadata
feat(tool-loop): add token-budget awareness and tool output pruningfeature/m2-tool-budgetBackground and Context
The multi-turn tool-call loop (implemented in #59/#60) accumulates all AIMessages and ToolMessages into a single
messageslist across every round of the loop. Every subsequentainvoke()call sends the entire accumulated conversation. This accumulation is architecturally correct and essential for effective LLM reasoning: the model must see its prior reasoning (AIMessage content), prior tool decisions (tool_calls), and prior tool results (ToolMessages) to build coherent multi-step chains.However, the current implementation has zero context management. The loop blindly accumulates messages until it hits
_TOOL_MAX_ROUNDS(default 20) or the model stops making tool calls. Two distinct failure modes arise:Failure Mode 1: Context overflow from irrelevant tool output
The LLM reads a large file (e.g., 50KB log) via
file_readbut only needs 3 specific lines. The full 50KB enters context as a ToolMessage, crowding out room for the actual relevant data it still needs to gather from other files. The loop terminates prematurely not because the model made too many rounds, but because low-value tool output displaced space for high-value data. The final answer is degraded.Failure Mode 2: Silent context window exhaustion
When accumulated context exceeds the model's context window, the provider either rejects the request with a context-length error or silently truncates from the beginning, causing the model to forget its system prompt or early reasoning.
Why Not Automatic Compaction?
Automatic compaction is harmful because the compressor cannot know what the LLM still needs. The correct approach is LLM-directed extraction: let the LLM extract only the relevant content from each tool output before it enters the main conversation context.
Architecture Decision Record
ADR-2031 (
docs/adr/ADR-2031-tool-loop-token-budget-and-pruning.md, status: accepted) documents all specification extensions. Key decisions:token_budget_percent(number, default 0.85). Budget ceiling =token_budget_percent x model_context_window. At 75% consumption a warning is emitted; at 100% the budget-exhausted synthesis flow triggers.allow_tool_output_pruning(boolean, default false) andpruning_model(string, optional). Initial pruning scope isfile_readonly — the tool most likely to produce context-busting output. Mechanism extends to other tools in future.output_prune(boolean, default true) andoutput_prune_context(string, optional) meta-arguments injected into tool schemas. The main model can opt-out per call (output_prune: false) or provide a focused search directive (output_prune_context) that replaces the broader task context in the extraction prompt. Both meta-arguments are stripped before tool execution.[PRUNE_INFO_START] / [PRUNE_INFO_END]and[PRUNE_OUTPUT_START] / [PRUNE_OUTPUT_END]for the pruning model's response. Marker strings reserved under §15.Proposed Solution: Two Complementary Mechanisms
1. Token-Budget Awareness
Track estimated token consumption and detect when the context window is approaching its limit:
ainvoke()call, estimate current token count usingchat_model.get_num_tokens()when available, falling back tolen(content) // 4heuristic.2. Tool Output Pruning
An implicit extraction pass scoped to
file_readcalls, gated behindallow_tool_output_pruning: true(opt-in, backward compatible).Meta-arguments injected into tool schemas:
output_prune(boolean, default true): set tofalseto skip pruning and receive the full raw output.output_prune_context(string, optional): a focused description from the main model of what it is looking for in the tool output. When provided, it replaces the broader task context in the extraction prompt.Pruning response format:
Design principles:
pruning_modelconfig allows a lighter model).messageslist.Acceptance Criteria
token_budget_percentis configured and accumulated token estimate exceeds the budget ceiling, a warning is logged at 75% consumption and the budget-exhausted flow triggers.allow_tool_output_pruning: true, eachfile_readtool output is passed through the extraction LLM call before becoming a ToolMessage.file_readresult is pruned and the LLM needs only 3 lines, the resulting ToolMessage contains ~200 chars with pruning markers.output_prune: falsein the tool call arguments.output_prune_contextto focus the pruning model.Supporting Information
fbf62145301168bae04411c07f1ade875935609f(original multi-turn tool-call loop)docs/adr/ADR-2031-tool-loop-token-budget-and-pruning.md(this feature)src/cleveractors/agents/llm.py— new methods:_get_model_context_window,_estimate_token_count,_augment_tool_schemas_for_pruning,_parse_pruning_response,_run_pruning_passsrc/cleveractors/agents/llm.py— tool loop modified with budget check, pruning pass, schema augmentation, meta-argument strippingSubtasks
token_budget_percent,allow_tool_output_pruning, andpruning_modelconfig keys to LLMAgent with validation_estimate_token_count(messages)using LangChainchat_model.get_num_tokens()orlen(content) // 4fallback_get_model_context_window()for known models with 128K defaultainvoke()in the tool loop_augment_tool_schemas_for_pruning()to injectoutput_pruneandoutput_prune_contextmeta-arguments_run_pruning_pass()extraction pass withbuild_chat_model_parse_pruning_response()marker parsingoutput_pruneandoutput_prune_contextfrom args before tool executionfeatures/llm_agent_tool_calling.featurerobot/llm_token_budget.robotbenchmarks/token_budget_benchmark.pynox -s coverage_reportdocs/adr/ADR-2031-tool-loop-token-budget-and-pruning.mdDefinition of Done
This issue is complete when:
master, reviewed, and merged before this issue is marked done.feat(tool-loop): add token-budget-aware context management in multi-turn tool-call loopto feat(tool-loop): add token-budget awareness and LLM-directed context pruningfeat(tool-loop): add token-budget awareness and LLM-directed context pruningto feat(tool-loop): add token-budget awareness and tool output pruning