diff --git a/chatlas/_merge.py b/chatlas/_merge.py index b5a4976a..25b50526 100644 --- a/chatlas/_merge.py +++ b/chatlas/_merge.py @@ -39,16 +39,16 @@ def merge_dicts(left: dict[str, Any], *others: dict[str, Any]) -> dict[str, Any] merged[right_k] = None elif left_v is None: merged[right_k] = right_v - elif left_v == right_v: - continue elif isinstance(left_v, str): merged[right_k] += right_v - elif isinstance(left_v, (int, float)): - merged[right_k] = right_v - elif isinstance(merged[right_k], dict): + elif isinstance(left_v, dict): merged[right_k] = merge_dicts(merged[right_k], right_v) - elif isinstance(merged[right_k], list): + elif isinstance(left_v, list): merged[right_k] = merge_lists(merged[right_k], right_v) + elif left_v == right_v: + continue + elif isinstance(left_v, (int, float)): + merged[right_k] = right_v elif type(merged[right_k]) is not type(right_v): raise TypeError( f'additional_kwargs["{right_k}"] already exists in this message,' diff --git a/tests/test_utils_merge.py b/tests/test_utils_merge.py index eabe262d..6d2de074 100644 --- a/tests/test_utils_merge.py +++ b/tests/test_utils_merge.py @@ -14,14 +14,27 @@ def test_equal_values(): assert merge_dicts({"a": True}, {"a": True}) == {"a": True} assert merge_dicts({"a": False}, {"a": False}) == {"a": False} - assert merge_dicts({"a": "x"}, {"a": "x"}) == {"a": "x"} - -def test_strings_are_concatenated(): +def test_strings_are_always_concatenated(): + # Strings always concatenate, even when equal. This is essential for + # streaming: a delta can legitimately equal everything accumulated so far + # (e.g. a leading "\n\n" arriving as two "\n" chunks). + # https://github.com/posit-dev/chatlas/issues/435 assert merge_dicts({"a": "a"}, {"a": "b"}) == {"a": "ab"} + assert merge_dicts({"a": "x"}, {"a": "x"}) == {"a": "xx"} + assert merge_dicts({"a": "\n"}, {"a": "\n"}) == {"a": "\n\n"} assert merge_dicts({"a": {"b": "a"}}, {"a": {"b": "b"}}) == {"a": {"b": "ab"}} +def test_equal_dicts_still_recurse(): + # Equal dicts must recurse — they can carry accumulating string leaves. + # https://github.com/posit-dev/chatlas/issues/435 + assert merge_dicts( + {"delta": {"content": "\n", "role": "assistant"}}, + {"delta": {"content": "\n", "role": "assistant"}}, + ) == {"delta": {"content": "\n\n", "role": "assistantassistant"}} + + def test_merge_dictionaries_with_different_keys(): assert merge_dicts({"a": 1, "b": 2}, {"a": 1}) == {"a": 1, "b": 2}