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

TypeError In _Combine_llm_outputs When Token Usage Contains Nested Dicts

Calling ChatMistralAI.generate() with multiple message lists fails due to unsupported operand type(s) for += on dict in _combine_llm_outputs. The method blindly uses += to aggregate token usage fields, but Mistral API returns nested dictionaries for some fields (e.g., 'tokens_details'), causing a TypeError. A recursive merge is needed.

highConfidence 95%LangchainAffected V1.1.5

Origin Analysis

The _combine_llm_outputs method in langchain_mistralai assumes all token_usage values are scalar numbers and uses += to aggregate them. However, the Mistral API's token usage includes nested dictionary fields, making dict += dict invalid.
1. Install langchain_mistralai version 1.1.5 (or earlier affected versions). 2. Set MISTRAL_API_KEY environment variable. 3. Run the following Python code: ```python import os from langchain_mistralai import ChatMistralAI from langchain_core.messages import HumanMessage llm = ChatMistralAI( model="mistral-small-latest", api_key=os.environ["MISTRAL_API_KEY"], ) result = llm.generate([ [HumanMessage(content="What is 1+1?")], [HumanMessage(content="What is 2+2?")], ]) print(result) ``` 4. Observe TypeError: unsupported operand type(s) for +=: 'dict' and 'dict'.

Fixing Code Block

Edge Case Audit

The fix assumes that nested dictionaries contain only numeric values or further nested dictionaries. If the Mistral API later returns non-numeric leaf values (e.g., strings or lists), the current merge logic will overwrite instead of summing, potentially losing information. Additionally, this fix only addresses token_usage; other llm_output fields with similar nested structures may still cause errors. Rollback suggestion: if unexpected behavior occurs after applying this patch, revert to using ChatOpenAI with Mistral's OpenAI-compatible endpoint as a workaround, or pin langchain-mistralai to a version known to work.

Ecosystem Topology