langchain-ai/langchain · error · TypeError

Cannot add incompatible types for key {key!r}: {type(chunk[k

Error message

Cannot add incompatible types for key {key!r}: {type(chunk[key]).__name__!r} and {type(self[key]).__name__!r}.

What it means

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.

Source

Thrown at libs/core/langchain_core/runnables/utils.py:526

            A dictionary that is the result of adding the two dictionaries.

        Raises:
            TypeError: If a shared key holds values of incompatible types.
        """
        chunk = AddableDict(other)
        for key in self:
            if key not in chunk or chunk[key] is None:
                chunk[key] = self[key]
            elif self[key] is not None:
                try:
                    added = chunk[key] + self[key]
                except TypeError as exc:
                    msg = (
                        f"Cannot add incompatible types for key {key!r}: "
                        f"{type(chunk[key]).__name__!r} and "
                        f"{type(self[key]).__name__!r}."
                    )
                    raise TypeError(msg) from exc
                chunk[key] = added
        return chunk


_T_co = TypeVar("_T_co", covariant=True)
_T_contra = TypeVar("_T_contra", contravariant=True)


class SupportsAdd(Protocol[_T_contra, _T_co]):
    """Protocol for objects that support addition."""

    def __add__(self, x: _T_contra, /) -> _T_co:
        """Add the object to another object."""


Addable = TypeVar("Addable", bound=SupportsAdd[Any, Any])

View on GitHub (pinned to e32fa9a52e)

Solutions

  1. Ensure every producer of a given key emits the same addable type (or `None`, which is skipped during merge).
  2. Rename keys so colliding payloads live under distinct keys and are never added together.
  3. Add `__add__` to custom value classes that must merge.

Example fix

// before
# branch A yields AddableDict({'out': [1]}); branch B yields AddableDict({'out': 'x'})
// -> TypeError: Cannot add incompatible types for key 'out'
// after
# branch B yields under its own key
AddableDict({'out_text': 'x'})
Defensive patterns

Strategy: validation

Validate before calling

def keys_type_consistent(producers: list[dict]) -> bool:
    seen: dict[str, type] = {}
    for d in producers:
        for k, v in d.items():
            if v is None:
                continue
            if k in seen and type(v) is not seen[k]:
                return False
            seen.setdefault(k, type(v))
    return True

Type guard

def can_radd(chunk: dict, addable: 'AddableDict') -> bool:
    for k in addable:
        if k in chunk and chunk[k] is not None and addable[k] is not None:
            try:
                chunk[k] + addable[k]
            except TypeError:
                return False
    return True

Try / catch

try:
    merged = base + AddableDict(incoming)
except TypeError as e:
    if 'Cannot add incompatible types' in str(e):
        merged = {**base, **incoming}
    else:
        raise

Prevention

When it happens

Trigger: `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.

Common situations: 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.

Related errors


AI-assisted analysis of langchain-ai/langchain@e32fa9a52e (2026-08-14). Data as JSON: /api/errors/0b59cf9b539c6357. Report an issue: GitHub.