Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions chatlas/_merge.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,'
Expand Down
19 changes: 16 additions & 3 deletions tests/test_utils_merge.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}

Expand Down
Loading