{"record":{"id":"d26915378c427053","repo":"langchain-ai/langchain","slug":"cannot-add-incompatible-types-for-key-key-r-ty","errorCode":null,"errorMessage":"Cannot add incompatible types for key {key!r}: {type(chunk[key]).__name__!r} and {type(other[key]).__name__!r}.","messagePattern":"Cannot add incompatible types for key (.+?): (.+?) and (.+?)\\.","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"libs/core/langchain_core/runnables/utils.py","lineNumber":497,"sourceCode":"            A dictionary that is the result of adding the two dictionaries.\n\n        Raises:\n            TypeError: If a shared key holds values of incompatible types.\n        \"\"\"\n        chunk = AddableDict(self)\n        for key in other:\n            if key not in chunk or chunk[key] is None:\n                chunk[key] = other[key]\n            elif other[key] is not None:\n                try:\n                    added = chunk[key] + other[key]\n                except TypeError as exc:\n                    msg = (\n                        f\"Cannot add incompatible types for key {key!r}: \"\n                        f\"{type(chunk[key]).__name__!r} and \"\n                        f\"{type(other[key]).__name__!r}.\"\n                    )\n                    raise TypeError(msg) from exc\n                chunk[key] = added\n        return chunk\n\n    def __radd__(self, other: AddableDict) -> AddableDict:\n        \"\"\"Add this dictionary to another dictionary.\n\n        Args:\n            other: The other dictionary to be added to.\n\n        Returns:\n            A dictionary that is the result of adding the two dictionaries.\n\n        Raises:\n            TypeError: If a shared key holds values of incompatible types.\n        \"\"\"\n        chunk = AddableDict(other)\n        for key in self:\n            if key not in chunk or chunk[key] is None:","sourceCodeStart":479,"sourceCodeEnd":515,"githubUrl":"https://github.com/langchain-ai/langchain/blob/e32fa9a52eab3b61ad7a45399bfde59b3e580fc4/libs/core/langchain_core/runnables/utils.py#L479-L515","documentation":"`AddableDict.__add__` merges two dict chunks key-by-key using `+` on the values; when two chunks share a key whose values do not support addition (e.g. `str` and `int`, or two arbitrary objects), the inner `TypeError` is re-raised with this detailed message. This is how langchain merges streamed chunks, so it surfaces during `.stream()`/`.batch()` aggregation.","triggerScenarios":"Streaming a `RunnablePassthrough.assign(...)` (or any dict-emitting runnable chain) where one chunk has `{'count': 3}` and the next has `{'count': 'many'}`; custom runnables yielding dicts whose value types differ across chunks for the same key.","commonSituations":"Custom LCEL components that yield dicts with values of inconsistent types across calls; mixing counters/ints with strings in assign branches; a mapper producing `None` then a non-addable type for the same key.","solutions":["Make values for any shared key consistently addable across chunks (same type, or types with `__add__` defined).","Yield `None` values where appropriate — `AddableDict` skips addition when either side is `None`, which is the intended escape hatch.","Wrap non-addable payloads under a single key that only appears in one chunk so no merge is attempted."],"exampleFix":"// before\n# chunk 1 from branch A\nyield AddableDict({'result': 42})\n# chunk 2 from branch B (same key, incompatible type)\nyield AddableDict({'result': 'done'})\n// after\nyield AddableDict({'count': 42})\nyield AddableDict({'status': 'done'})  # distinct keys, no cross-type add","handlingStrategy":"validation","validationCode":"def mergeable(a: dict, b: dict) -> bool:\n    for k in set(a) & set(b):\n        if a[k] is None or b[k] is None:\n            continue\n        try:\n            a[k] + b[k]\n        except TypeError:\n            return False\n    return True\n\n# check before aggregating streamed chunks\nassert mergeable(acc, next_chunk)","typeGuard":"from typing import Any\n\ndef is_addable_pair(x: Any, y: Any) -> bool:\n    if x is None or y is None:\n        return True\n    try:\n        x + y\n        return True\n    except TypeError:\n        return False","tryCatchPattern":"try:\n    total = chunk_a + chunk_b\nexcept TypeError as e:\n    if 'Cannot add incompatible types' in str(e):\n        total = {**chunk_a, **chunk_b}  # last-write-wins instead of addition\n    else:\n        raise","preventionTips":["Keep one value type per key across all chunks of a stream.","Use None for absent values — AddableDict skips adding None.","Give non-addable payloads their own unique keys."],"tags":["runnable","addabledict","streaming","type-mismatch"],"backgroundTag":null,"analyzedSha":"e32fa9a52eab3b61ad7a45399bfde59b3e580fc4","analyzedAt":"2026-08-14T18:42:09.092Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}