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

TypeError In _Create_usage_metadata When Service_tier Is Priority/Flex And Cached_tokens Is Missing

langchain-openai's _create_usage_metadata and _create_usage_metadata_responses crash with TypeError when service_tier is 'priority' or 'flex' and the OpenAI API response omits cached_tokens in prompt_tokens_details. The subtraction of None from an int causes an unhandled exception, breaking chat completions using service tiers.

highConfidence 95%Langchain-Openailangchain-coreMemoryVector StoresAffected V1.1.12

Origin Analysis

The code retrieves cached_tokens from prompt_tokens_details using .get('cached_tokens') without a default value. When the key is absent, .get returns None, which is then used in arithmetic subtraction: prompt_tokens -= cached_tokens. Python cannot subtract None from int, raising TypeError. The bug exists in both _create_usage_metadata and _create_usage_metadata_responses. A previous fix (#36500) addressed similar patterns elsewhere but missed the service_tier arithmetic.
1. Install langchain-openai 1.1.12. 2. Run: `_create_usage_metadata({"prompt_tokens": 100, "completion_tokens": 50, "total_tokens": 150, "prompt_tokens_details": {}, "completion_tokens_details": {}}, service_tier="priority")`. 3. Observe TypeError: unsupported operand type(s) for -: 'int' and 'NoneType'.

Fixing Code Block

Edge Case Audit

The patch assumes cached_tokens, when present, is a non-negative integer. If OpenAI changes the API to return float or Decimal, type issues may persist. The `max(0, ...)` guards against negative counts but could mask data inconsistencies. Rollback advice: keep the original code under version control and downgrade to a previous langchain-openai version (e.g., 1.1.11) if unexpected behavior occurs. Ensure tests cover service_tier responses with missing, None, and zero cached_tokens.

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