secondbrain icon indicating copy to clipboard operation
secondbrain copied to clipboard

[Bug] Token Count Not Validated - Exceeds Model Limits

Open anshul23102 opened this issue 5 months ago • 0 comments

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

  1. User loads a 50,000-word document into the knowledge base
  2. User sends a prompt to generate summary
  3. System concatenates document + prompt without checking token count
  4. LLM API receives request exceeding token limit (e.g., GPT-3.5 4K limit)
  5. API returns 400 error "Tokens exceed context limit"
  6. 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

anshul23102 avatar Jun 03 '26 18:06 anshul23102