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(other[key]).__name__!r}.

What it means

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

Source

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

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

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

    def __radd__(self, other: AddableDict) -> AddableDict:
        """Add this dictionary to another dictionary.

        Args:
            other: The other dictionary to be added to.

        Returns:
            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:

View on GitHub (pinned to e32fa9a52e)

Solutions

  1. Make values for any shared key consistently addable across chunks (same type, or types with `__add__` defined).
  2. Yield `None` values where appropriate — `AddableDict` skips addition when either side is `None`, which is the intended escape hatch.
  3. Wrap non-addable payloads under a single key that only appears in one chunk so no merge is attempted.

Example fix

// before
# chunk 1 from branch A
yield AddableDict({'result': 42})
# chunk 2 from branch B (same key, incompatible type)
yield AddableDict({'result': 'done'})
// after
yield AddableDict({'count': 42})
yield AddableDict({'status': 'done'})  # distinct keys, no cross-type add
Defensive patterns

Strategy: validation

Validate before calling

def mergeable(a: dict, b: dict) -> bool:
    for k in set(a) & set(b):
        if a[k] is None or b[k] is None:
            continue
        try:
            a[k] + b[k]
        except TypeError:
            return False
    return True

# check before aggregating streamed chunks
assert mergeable(acc, next_chunk)

Type guard

from typing import Any

def is_addable_pair(x: Any, y: Any) -> bool:
    if x is None or y is None:
        return True
    try:
        x + y
        return True
    except TypeError:
        return False

Try / catch

try:
    total = chunk_a + chunk_b
except TypeError as e:
    if 'Cannot add incompatible types' in str(e):
        total = {**chunk_a, **chunk_b}  # last-write-wins instead of addition
    else:
        raise

Prevention

When it happens

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

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

Related errors


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