AI & Agent Dev Bug Sandbox logo
AI & Agent Dev Bug Sandbox
Back to Radar

Count_tokens_approximately Inflates Estimates 5-10X For Reasoning/Thinking Blocks

count_tokens_approximately has no dedicated case for reasoning or thinking content blocks, causing them to fall through to the catch-all len(repr(block)) branch. This stringifies the entire block dict, including provider metadata such as extras.encrypted_content, inflating token estimates by 5-10x and breaking context-window management.

highConfidence 93%Langchain-Corelangchain-coreChainsChat ModelsAffected V1.5.5

Origin Analysis

Missing explicit handling for content blocks with type 'reasoning' or 'thinking' in count_tokens_approximately. The fallback len(repr(block)) serializes the entire block dict, including long encrypted_content fields inside extras, rather than extracting only the readable reasoning/thinking text.
from langchain_core.messages import AIMessage from langchain_core.messages.utils import count_tokens_approximately reasoning_text = "I should inspect the staging model." ciphertext = "g" * 4000 block_with_extras = { "type": "reasoning", "id": "rs_abc", "reasoning": reasoning_text, "extras": {"content": [], "encrypted_content": ciphertext}, } block_without_extras = { "type": "reasoning", "id": "rs_abc", "reasoning": reasoning_text, } print(count_tokens_approximately([AIMessage(content=[block_with_extras], id="ai-1")])) # ~1070 print(count_tokens_approximately([AIMessage(content=[block_without_extras], id="ai-1")])) # ~15

Fixing Code Block

Edge Case Audit

This hotfix only covers top-level 'reasoning' and 'thinking' fields. If providers embed encrypted or long payloads inside other block types or under different keys (e.g., nested inside extras for 'text' blocks), the fallback len(repr(block)) will still inflate counts. Future-proof by routing content extraction through get_buffer_string or maintaining a central block-type registry. Rollback is straightforward: restore the original function body; no data migration is required. Test with both OpenAI reasoning blocks and Anthropic thinking blocks to ensure no regression.

Ecosystem Topology

Agent Frameworks

LangChain, LlamaIndex, and Pydantic

  1. highProperty graph relation keys collide when entity IDs or labels contain underscores
  2. highCodeActAgent drops assistant tool-call metadata during handoff, leaving an orphan tool response
  3. high[Bug]: HierarchicalNodeParser async methods return the documents unsplit
  4. highLLM.predict_and_call fails with ValidationError for non-function-calling models when react_chat_formatter is omitted
  5. highAnthropic streaming server-tool input_json_delta overwrites completed client tool_use arguments due to stale cur_tool_call state