fix(agent): no token count guard — prompt exceeds model max context
Bug Report
Description
Agent sends prompts that exceed the model's maximum context length, causing 400 errors from the upstream provider. No pre-flight token count check or truncation exists before dispatch.
Sentry issues:
- OPENHUMAN-TAURI-HF — prompt is too long: 201756 tokens > 200000 maximum (112 events)
- OPENHUMAN-TAURI-QX — token count 203783 exceeds model max context 202752 (48 events)
Combined impact: 160 events. Users see agent errors mid-conversation when context grows large. The model tag shows github_copilot/claude-haiku-4.5 — GitHub Copilot proxy with 200K limit.
Error
litellm.BadRequestError: Github_copilotException - prompt is too long: 201756 tokens > 200000 maximum.
Received Model Group=github_copilot/claude-haiku-4.5
- Platform: Windows x86_64 (10.0.26220)
- Version: [email protected]
- Environment: production
Root Cause Analysis
The agent harness builds conversation context (system prompt + message history + tool results) without checking the total token count against the target model's context window limit before dispatching to the LLM provider. When conversations grow long or tool results are large, the prompt exceeds the model's maximum.
The provider routing layer (src/openhuman/inference/provider/) translates abstract tier names to concrete models but does not enforce a token budget. The custom_openai provider path forwards the full payload to the upstream endpoint, which rejects it.
Proposed Fix
- Before LLM dispatch, estimate token count and compare against the model's known context limit
- If over limit, truncate conversation history (oldest messages first) or summarize to fit
- Add per-model context limits to the provider config / routing table
- Log a warning when truncation is applied so users know context was trimmed
Labels
sentry-traced-bug, os:windows, bug, priority: high, area: core