{"record":{"id":"0b59cf9b539c6357","repo":"langchain-ai/langchain","slug":"cannot-add-incompatible-types-for-key-key-r-ty-0b59cf","errorCode":null,"errorMessage":"Cannot add incompatible types for key {key!r}: {type(chunk[key]).__name__!r} and {type(self[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":526,"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(other)\n        for key in self:\n            if key not in chunk or chunk[key] is None:\n                chunk[key] = self[key]\n            elif self[key] is not None:\n                try:\n                    added = chunk[key] + self[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(self[key]).__name__!r}.\"\n                    )\n                    raise TypeError(msg) from exc\n                chunk[key] = added\n        return chunk\n\n\n_T_co = TypeVar(\"_T_co\", covariant=True)\n_T_contra = TypeVar(\"_T_contra\", contravariant=True)\n\n\nclass SupportsAdd(Protocol[_T_contra, _T_co]):\n    \"\"\"Protocol for objects that support addition.\"\"\"\n\n    def __add__(self, x: _T_contra, /) -> _T_co:\n        \"\"\"Add the object to another object.\"\"\"\n\n\nAddable = TypeVar(\"Addable\", bound=SupportsAdd[Any, Any])\n\n","sourceCodeStart":508,"sourceCodeEnd":544,"githubUrl":"https://github.com/langchain-ai/langchain/blob/e32fa9a52eab3b61ad7a45399bfde59b3e580fc4/libs/core/langchain_core/runnables/utils.py#L508-L544","documentation":"Mirror of `AddableDict.__add__` on the `__radd__` path: when an `AddableDict` appears on the right side of `+` and the accumulated chunk already holds a value for a key whose type cannot be added to the incoming one, this TypeError is raised. It bites during streaming aggregation when summed chunk values for a key have incompatible types.","triggerScenarios":"`chunk_total + AddableDict({'k': v})` where `chunk_total['k']` is, say, an `int` and `v` a `str` (or two objects with no cross `__add__`); merging partial dict outputs from parallel branches of a streamed chain where the same key carries different value types.","commonSituations":"Parallel LCEL branches (`.assign()` mappers, `RunnableParallel`) emitting the same key with different value types; custom tool/parser outputs that sometimes emit numbers and sometimes strings for one field; upgrading a custom runnable that used to emit `None` (skipped) to emit typed values that collide.","solutions":["Ensure every producer of a given key emits the same addable type (or `None`, which is skipped during merge).","Rename keys so colliding payloads live under distinct keys and are never added together.","Add `__add__` to custom value classes that must merge."],"exampleFix":"// before\n# branch A yields AddableDict({'out': [1]}); branch B yields AddableDict({'out': 'x'})\n// -> TypeError: Cannot add incompatible types for key 'out'\n// after\n# branch B yields under its own key\nAddableDict({'out_text': 'x'})","handlingStrategy":"validation","validationCode":"def keys_type_consistent(producers: list[dict]) -> bool:\n    seen: dict[str, type] = {}\n    for d in producers:\n        for k, v in d.items():\n            if v is None:\n                continue\n            if k in seen and type(v) is not seen[k]:\n                return False\n            seen.setdefault(k, type(v))\n    return True","typeGuard":"def can_radd(chunk: dict, addable: 'AddableDict') -> bool:\n    for k in addable:\n        if k in chunk and chunk[k] is not None and addable[k] is not None:\n            try:\n                chunk[k] + addable[k]\n            except TypeError:\n                return False\n    return True","tryCatchPattern":"try:\n    merged = base + AddableDict(incoming)\nexcept TypeError as e:\n    if 'Cannot add incompatible types' in str(e):\n        merged = {**base, **incoming}\n    else:\n        raise","preventionTips":["Parallel branches must not reuse a key with different value types.","Define __add__ on custom value classes that must merge.","Prefer distinct keys per branch over overloaded ones."],"tags":["addabledict","streaming","type-mismatch","runnable"],"backgroundTag":null,"analyzedSha":"e32fa9a52eab3b61ad7a45399bfde59b3e580fc4","analyzedAt":"2026-08-14T18:42:09.092Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}