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

Count_tokens_approximately: Missing Handler For Tool_use Content Blocks Causes ~2.4X Overcounting

The count_tokens_approximately function in langchain-core fails to handle Anthropic tool_use and tool_result content blocks, falling back to repr() which inflates token counts by up to ~2.4x (measured 4.6x in production), causing premature summarization.

highConfidence 95%LangchainChainsMemorylangchain-coreAffected V>=0.1.0Affected V1.2.17

Origin Analysis

In langchain_core/messages/utils.py, the content block handler loop only checks for 'text' and 'image_url' types; 'tool_use' and 'tool_result' blocks hit the else branch and use repr(item), which produces a Python dict representation with single quotes and expanded booleans, significantly longer than compact JSON.
from langchain_core.messages import AIMessage from langchain_core.messages.utils import count_tokens_approximately msg = AIMessage(content=[ { 'type': 'tool_use', 'id': 'toolu_01AbCdEf', 'name': 'search_memories', 'input': {'query': 'recent events'}, } ]) approx = count_tokens_approximately(msg) print(f'Approximated tokens: {approx}') # Expected: ~23 tokens, Actual: significantly more due to repr()

Fixing Code Block

Edge Case Audit

This fix reduces but does not eliminate overcounting: json.dumps still counts structural keys and metadata (type, id, etc.), and nested image or non-serializable objects may cause serialization errors or undercount. If tool_result contains nested content arrays with text and images, the entire block is stringified, potentially including image data as base64 if present, which may still overcount or raise TypeError on non-serializable objects. Rollback suggestion: if unexpected behavior occurs, revert to the previous repr() fallback, but that will reintroduce overcounting; better to implement a custom normalizer that extracts only meaningful text and handles nested blocks recursively.

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