The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
fix(core): issues in merging chunks (#39535)
Nishitha Ma648460cfd43
diff --git a/libs/core/langchain_core/runnables/utils.py b/libs/core/langchain_core/runnables/utils.pyindex 080c6d01cb..0bc6b0780a 100644--- a/libs/core/langchain_core/runnables/utils.py+++ b/libs/core/langchain_core/runnables/utils.py@@ -477,6 +477,9 @@ class AddableDict(dict[str, Any]):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(self)for key in other:@@ -485,8 +488,13 @@ class AddableDict(dict[str, Any]):elif other[key] is not None:try:added = chunk[key] + other[key]- except TypeError:- added = 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 excchunk[key] = addedreturn chunk@@ -498,6 +506,9 @@ class AddableDict(dict[str, Any]):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:@@ -506,8 +517,13 @@ class AddableDict(dict[str, Any]):elif self[key] is not None:try:added = chunk[key] + self[key]- except TypeError:- added = 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 excchunk[key] = addedreturn chunkdiff --git a/libs/core/langchain_core/utils/_merge.py b/libs/core/langchain_core/utils/_merge.pyindex 8ddc797f62..15f06cc4e4 100644--- a/libs/core/langchain_core/utils/_merge.py+++ b/libs/core/langchain_core/utils/_merge.py@@ -68,6 +68,15 @@ def merge_dicts(left: dict[str, Any], *others: dict[str, Any]) -> dict[str, Any]merged[right_k] = merge_lists(merged[right_k], right_v)elif merged[right_k] == right_v:continue+ elif isinstance(merged[right_k], bool):+ # `bool` is a subclass of `int`, so without this check differing+ # booleans would fall into the int branch below and get summed,+ # silently turning e.g. `True + False` into the int `1`.+ msg = (+ f"Additional kwargs key {right_k} already exists in left dict and "+ f"value has unsupported type {type(merged[right_k])}."+ )+ raise TypeError(msg)elif isinstance(merged[right_k], int):# Preserve identification and temporal fields using last-wins strategy# instead of summing:@@ -118,7 +127,8 @@ def merge_lists(left: list[Any] | None, *others: list[Any] | None) -> list[Any]ifor i, e_left in enumerate(merged)if (- "index" in e_left+ isinstance(e_left, dict)+ and "index" in e_leftand e_left["index"] == e["index"] # index matchesand ( # IDs not inconsistente_left.get("id") in {None, ""}diff --git a/libs/core/tests/unit_tests/runnables/test_utils.py b/libs/core/tests/unit_tests/runnables/test_utils.pyindex 031bb5aa23..2b77caf342 100644--- a/libs/core/tests/unit_tests/runnables/test_utils.py+++ b/libs/core/tests/unit_tests/runnables/test_utils.py@@ -5,6 +5,7 @@ import pytestfrom langchain_core.runnables.base import RunnableLambdafrom langchain_core.runnables.utils import (+ AddableDict,get_function_nonlocals,get_lambda_source,indent_lines_after_first,@@ -73,3 +74,29 @@ def test_nonlocals() -> None:assert RunnableLambda(my_func3).deps == [agent]assert RunnableLambda(my_func4).deps == [global_agent]assert RunnableLambda(func).deps == [nl]+++def test_addable_dict_add_incompatible_types_raises() -> None:+ left = AddableDict({"count": 1})+ right = AddableDict({"count": "some_string"})+ with pytest.raises(+ TypeError,+ match=r"Cannot add incompatible types for key 'count': 'int' and 'str'\.",+ ):+ left + right+++def test_addable_dict_radd_incompatible_types_raises() -> None:+ left = AddableDict({"count": 1})+ right = AddableDict({"count": "some_string"})+ with pytest.raises(+ TypeError,+ match=r"Cannot add incompatible types for key 'count': 'int' and 'str'\.",+ ):+ right.__radd__(left)+++def test_addable_dict_add_none_seeded_key_is_unaffected() -> None:+ left = AddableDict({"data": None})+ right = AddableDict({"data": {"a": 1}})+ assert (left + right) == AddableDict({"data": {"a": 1}})diff --git a/libs/core/tests/unit_tests/test_messages.py b/libs/core/tests/unit_tests/test_messages.pyindex c6e4f5b50b..cf92d4eeae 100644--- a/libs/core/tests/unit_tests/test_messages.py+++ b/libs/core/tests/unit_tests/test_messages.py@@ -225,6 +225,14 @@ def test_message_chunks() -> None:assert (default_id_chunk + provider_chunk).id == meaningful_id+def test_message_chunks_bool_additional_kwargs_raises() -> None:+ """Differing booleans (e.g. `refusal`) must not silently coerce to `int`."""+ a = AIMessageChunk(content="", additional_kwargs={"refusal": True})+ b = AIMessageChunk(content="", additional_kwargs={"refusal": False})+ with pytest.raises(TypeError, match="unsupported type"):+ a + b++def test_chat_message_chunks() -> None:assert ChatMessageChunk(role="User", content="I am", id="ai4") + ChatMessageChunk(role="User", content=" indeed."diff --git a/libs/core/tests/unit_tests/utils/test_utils.py b/libs/core/tests/unit_tests/utils/test_utils.pyindex 95c7cf50a0..fe123a7ed3 100644--- a/libs/core/tests/unit_tests/utils/test_utils.py+++ b/libs/core/tests/unit_tests/utils/test_utils.py@@ -129,6 +129,18 @@ def test_check_package_version(# Other integer fields should still be summed (e.g., token counts)({"tokens": 10}, {"tokens": 5}, {"tokens": 15}),({"count": 1}, {"count": 2}, {"count": 3}),+ # Differing booleans must not silently coerce to `int` (e.g. `True + False`).+ (+ {"a": True},+ {"a": False},+ pytest.raises(+ TypeError,+ match=(+ "Additional kwargs key a already exists in left dict and value "+ r"has unsupported type .+bool.+."+ ),+ ),+ ),],)def test_merge_dicts(@@ -437,6 +449,16 @@ def test_generation_chunk_addition_type_error() -> None:[{"no_index": "b"}],[{"no_index": "a"}, {"no_index": "b"}],),+ # A string element whose text happens to contain the literal substring+ # "index" must not be treated as index-keyed (it isn't a dict).+ (+ ["the index is here", {"index": 0, "reference_ids": ["a"]}],+ [{"index": 0, "reference_ids": ["b"]}],+ [+ "the index is here",+ {"index": 0, "reference_ids": ["a", "b"]},+ ],+ ),],)def test_merge_lists(