secondbrain
secondbrain copied to clipboard
[Bug] Token Count Not Validated - Exceeds Model Limits
Description
Token count is not validated before sending requests to the LLM backend. Users can send prompts that exceed model context limits, causing request failures and error handling issues. No validation on input document size or context window utilization.
Steps to Reproduce
- User loads a 50,000-word document into the knowledge base
- User sends a prompt to generate summary
- System concatenates document + prompt without checking token count
- LLM API receives request exceeding token limit (e.g., GPT-3.5 4K limit)
- API returns 400 error "Tokens exceed context limit"
- Application crashes or shows generic error
Environment Information
- LLM: OpenAI API, Claude API, or similar
- Token counter: tiktoken library (or custom)
- Model context limits: GPT-3.5 (4K), GPT-4 (8K/32K), Claude (varies)
- Integration: Langchain/direct API calls
Expected Behavior
- System validates total token count before LLM call
- Exceeds limit: automatically truncate context or split request
- User notification: show token usage and limit
- Graceful degradation: provide partial results
Actual Behavior
- No token validation occurs
- Requests fail silently with API errors
- User sees cryptic error messages
- No indication of why request failed
Code Reference
- File:
src/llm/prompt_builder.py - Method:
build_context()- missing token validation - Method:
send_to_llm()- no pre-flight check - Missing: Token counter initialization
Additional Context
This is a Level 2 reliability issue. The fix requires:
- Integrating token counter library
- Adding validation in prompt building pipeline
- Calculating: document tokens + prompt tokens + buffer
- Truncating context or splitting into batches if over limit
- Returning token usage in response metadata
Suggested Labels
bug, reliability, validation, llm-integration, error-handling