openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

fix(agent): guard agent prompts against model max-context limit (#2074)

Open CodeGhost21 opened this issue 6 months ago • 1 comments

Summary

  • Add inference::model_context to resolve known per-model context windows (OpenHuman tier aliases, Copilot Haiku 200K, common Claude/GPT patterns).
  • Add agent::harness::token_budget to estimate prompt tokens (~4 chars/token) and trim oldest non-system history before LLM dispatch.
  • Wire pre-dispatch trimming + warning logs into run_tool_call_loop and the main Agent session turn path.
  • Populate Route::context_window when building model routes from config.

Problem

The agent harness built conversation context (system prompt + history + tool results) without checking total token count against the target model's context window before dispatching to the LLM. Long conversations or large tool outputs exceeded limits (e.g. github_copilot/claude-haiku-4.5 with a 200K cap), causing upstream 400 BadRequest errors (~160 Sentry events on Windows).

Solution

Before each provider chat() call, look up the model's context window via context_window_for_model, estimate total prompt tokens, and drop the oldest non-system messages until the payload fits (reserving ~10% / 8K tokens for completion and tool-schema overhead). When trimming occurs, emit a log::warn! with model id, context window, original vs final token estimates, and messages removed. ContextGuard is seeded with the known window when available so post-response utilization checks remain meaningful.

Submission Checklist

  • [x] Tests added or updated (happy path + at least one failure / edge case) per Testing Strategy
  • [x] Diff coverage ≥ 80% — enforced server-side by .github/workflows/coverage.yml (Vitest + cargo-llvm-cov merged via diff-cover). Local full pnpm test:coverage / pnpm test:rust not run in this session; new Rust modules include dedicated unit tests for pass-through, over-limit truncation, and model lookup edge cases. CI is the authoritative gate.
  • [x] Coverage matrix updated — N/A: Rust-only agent/inference change; no user-facing feature row added/removed
  • [x] All affected feature IDs from the matrix are listed in the PR description under ## Related — N/A: no matrix feature IDs
  • [x] No new external network dependencies introduced (mock backend used per Testing Strategy)
  • [x] Manual smoke checklist updated if this touches release-cut surfaces (docs/RELEASE-MANUAL-SMOKE.md) — N/A
  • [x] Linked issue closed via Closes #NNN in the ## Related section

Impact

  • Desktop agent turns and channel/tool-loop paths now proactively trim oversized histories before upstream LLM calls when the model window is known.
  • Unknown models skip pre-dispatch trimming (no guessing); existing post-response ContextGuard / autocompaction behavior is unchanged.
  • No migration or config changes required.

Related

  • Closes #2074
  • Follow-up PR(s)/TODOs: none

AI Authored PR Metadata (required for Codex/Linear PRs)

Linear Issue

  • Key: N/A
  • URL: N/A

Commit & Branch

  • Branch: cursor/a01-2074-agent-token-budget
  • Commit SHA: 168f0cd5976111b3fb5d71b951918bc56bad98fe

Validation Run

  • [x] pnpm --filter openhuman-app format:check
  • [x] pnpm typecheck
  • [x] Focused tests: cargo test --lib token_budget:: (5 passed), cargo test --lib model_context:: (4 passed)
  • [x] Rust fmt/check (if changed): cargo fmt --manifest-path Cargo.toml --all --check; pre-push pnpm rust:check (Tauri shell) passed
  • [x] Tauri fmt/check (if changed): included in pre-push hook

Validation Blocked

  • command: pnpm test:coverage and pnpm test:rust (full diff-cover gate)
  • error: Not run locally in this session — CI will enforce ≥80% on changed lines
  • impact: Merge gate depends on GitHub Actions coverage workflow; new Rust modules include dedicated unit tests for pass-through, over-limit truncation, and model lookup edge cases

Behavior Changes

  • Intended behavior change: Pre-dispatch token budget enforcement for known models
  • User-visible effect: Long agent conversations should stop failing with upstream context-length 400 errors; users may see slightly shorter retained history after trimming (logged at warn level)

Parity Contract

  • Legacy behavior preserved: Unknown models and post-response compaction/summarization paths unchanged
  • Guard/fallback/dispatch parity checks: ContextGuard still updated from provider usage; trimming only runs when context_window_for_model returns Some

Duplicate / Superseded PR Handling

  • Duplicate PR(s): none
  • Canonical PR: this PR
  • Resolution (closed/superseded/updated): N/A

Made with Cursor

Summary by CodeRabbit

  • New Features
    • Automatic conversation-history trimming before each model request to respect model context limits.
    • Per-model context-window detection and application, including a mapping of known models to their token windows.
    • Preservation of important system messages when trimming; trimming events are logged with token/message statistics.
    • Enhanced routing metadata now carries model context-window information for more accurate dispatching.

Review Change Stack

CodeGhost21 avatar May 18 '26 12:05 CodeGhost21

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 829d6233-ec59-4f98-8d7e-07888a224d72

📥 Commits

Reviewing files that changed from the base of the PR and between 168f0cd5976111b3fb5d71b951918bc56bad98fe and 1c0cc95769c35a8e0f88c591733680386c5a96e2.

📒 Files selected for processing (3)
  • src/openhuman/agent/harness/mod.rs
  • src/openhuman/agent/harness/session/turn.rs
  • src/openhuman/agent/harness/token_budget.rs
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/openhuman/agent/harness/mod.rs
  • src/openhuman/agent/harness/token_budget.rs

📝 Walkthrough

Walkthrough

Adds model-context-window discovery, token estimation, and pre-dispatch budgeting: resolves per-model context windows, estimates tokens, trims oldest non-system messages (preserving system messages) in conversation history and provider-bound chat before each LLM request, and surfaces trimming outcomes via logs.

Changes

Token Budgeting and Context Window Integration

Layer / File(s) Summary
Model context window resolution
src/openhuman/inference/model_context.rs, src/openhuman/inference/mod.rs
Adds context_window_for_model(model: &str) -> Option<u64> with tier constants and substring mappings; includes unit tests and re-exports the function from inference.
Token estimation and message trimming
src/openhuman/agent/harness/token_budget.rs, src/openhuman/agent/harness/mod.rs
Implements ~4-char-per-token estimators for ChatMessage and ConversationMessage, DEFAULT_OUTPUT_RESERVE_TOKENS, and two public trim entrypoints (trim_chat_messages_to_budget, trim_conversation_history_to_budget) that remove oldest non-system messages until budget fits; includes TokenBudgetOutcome and unit tests.
Provider routing context window integration
src/openhuman/inference/provider/router.rs, src/openhuman/inference/provider/ops.rs, src/openhuman/inference/provider/router_test.rs
Adds context_window: Option<u64> to Route and populates it during provider creation via context_window_for_model for each configured model route.
Agent harness pre-dispatch trimming
src/openhuman/agent/harness/session/turn.rs, src/openhuman/agent/harness/tool_loop.rs, src/openhuman/agent/harness/mod.rs
Imports context lookup and trimming helpers, computes per-iteration context_window, trims self.history and provider-bound messages to budget before dispatch, and derives ContextGuard using the model context window when available.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • graycyrus

Tokens tallied, old lines gently pruned, 🐇
Context windows set so requests stay tuned,
System lines kept, oldest go to sleep,
Trimmed with a hop so responses fit deep.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: adding token-budget guards to prevent agent prompts from exceeding model context limits, directly addressing the issue reference #2074.
Linked Issues check ✅ Passed All objectives from #2074 are met: per-model context limits added to routing, pre-dispatch token estimation and truncation implemented, oldest messages trimmed first, and warning logs added for truncation events.
Out of Scope Changes check ✅ Passed All changes are directly scoped to implementing token-budget guards: model context resolution, token estimation/trimming logic, integration into dispatch paths, and routing configuration updates.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar May 18 '26 12:05 coderabbitai[bot]