← Back to Pull requests

feat(agent): gate the final model request on a context window budget (issue #137) #352

Closed
unknown closed this pull request without merging on Nov 07, 2026 03:17 UTC
View on GitHub
unknown unknown commented on Nov 02, 2026 12:01 UTC
Author

Describe what this PR does / why we need it

Fixes #137: the neutral agent API had no notion of a context window budget. TokenCounter.countTokens(List<ChatMessage>) only measures the conversation, while the request which is finally dispatched carries more than the conversation - ReActAgent.invokeModel builds new ChatRequest(composeMessages(request), effective.definitions(), request.getOptions(), request.getAttributes()), so the system message, the tool schemas and the reserved output belong to the request but stay outside the measured scope. SummarizationHook and ContextEditingInterceptor each trigger on their own message threshold and both continue when they cannot compress anything, so nothing keeps an oversized request from reaching the provider, and LargeResultEvictionInterceptor claimed that a result was written to the filesystem even when the write failed.

Does this pull request fix one issue?

Fixes #137

Describe how you did it

  • Added the neutral budget contract io.github.agentic.ai.agent.budget in argi-agent-api: ContextWindowBudget for the context window and the reserved output, RequestTokenEstimate for the decomposition into system, conversation, tool schema and reserved output with an EstimationAccuracy that tells exact and conservative counts apart, RequestTokenEstimator with the default ApproximateRequestTokenEstimator, BudgetComponent and BudgetViolation for a stable classification, and ContextWindowBudgetExceededException for an explicit failure;

  • Added ContextBudgetInterceptor, a neutral ModelInterceptor which is opt-in through the existing interceptor chain: it estimates the request, asks the configured RequestCompactor to shrink an oversized request, measures the compacted request again, validates the tool call pairing and only then dispatches; a request which still does not fit fails with ContextWindowBudgetExceededException and never reaches the provider;

  • Reused the existing compression instead of rebuilding it: the framework adapter SummarizationRequestCompactor delegates to the existing SummarizationHook and rebuilds the request from the messages the hook returned; the hook keeps its own behaviour, so a failed summary returns the original history and the gate then fails explicitly instead of continuing with a broken context;

  • Fixed the write failure of the large result eviction: when the filesystem write fails, the interceptor no longer returns a pointer to a file which was never written, but an explicit failure which keeps the metadata of the original response;

  • Kept the existing behaviour intact: no existing signature, threshold or default changed, the new path is opt-in, and the neutral package depends on argi-api and argi-runtime-api only.
  • How was it tested / verified?

    New ContextBudgetInterceptorTest in argi-agent-api (offline, no model and no provider):

    1. the estimate covers the system message, the tool schemas and the reserved output;
    2. an oversized request fails and the dispatch counter stays at zero;
    3. a compacted request is measured again and then dispatched;
    4. a compaction which does not help still fails without a dispatch;
    5. a compaction which breaks the tool call pairing is rejected without a dispatch;
    6. the estimator is replaceable, an exact estimator changes the decision;
    7. the boundary is exact, a request which exactly fills the budget is dispatched and one token more is rejected.

    New SummarizationRequestCompactorTest and two additional cases in LargeResultEvictionInterceptorTest in argi-agent-framework: the compactor summarizes with the existing hook and returns the original request when the summary fails or is not needed, and a failed filesystem write produces a failure which contains no file pointer and no "saved in the filesystem" wording while keeping the metadata of the original response.

    Green after the change: argi-agent-api 41/41, argi-agent-framework 1341/1341, argi-agent-core 138/138, argi-workflow-graph-core 551/551; spring-javaformat:validate and checkstyle:check report no violation for the two touched modules, codespell and the newline check pass.

    Additional notes

  • Scope is the budget contract, the gate and the correctness of the write failure; the chain executor, the declarative plugin model and the engine wiring stay with their own issues, and the summarization and the context editing are not migrated into plugins here;

  • The change is additive: eleven new types in argi-agent-api, one new adapter and one behavioural fix in argi-agent-framework, and no change to an existing public signature, event, configuration or persistence format;

  • The builder of LargeResultEvictionInterceptor always supplies a default filesystem backend when eviction is enabled, so the branch for a missing backend is defensive only and the test covers the failed write path.
  • Diff: 614 lines (+460 / -154) across 7 files Reviewer: yuluo-yx Review duration: 6675m
    All Vouch review confidence checks passed
    Residual risk 0.20 = Change Risk (0.50) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.50 · 614 lines diff across 7 files
    0.50
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.384
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #352"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 50.2% (MEDIUM) · Higher = larger blast radius
    50.2%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 19.8% · Safe to merge
    19.8%