mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-08-21 07:02:25 +02:00
fix(langgraph): Dedupe input (right-side) messages in add_messages (#3338)
Port: https://github.com/langchain-ai/langgraphjs/pull/846
This commit is contained in:
@@ -180,14 +180,15 @@ def add_messages(
|
||||
if m.id is None:
|
||||
m.id = str(uuid.uuid4())
|
||||
# merge
|
||||
left_idx_by_id = {m.id: i for i, m in enumerate(left)}
|
||||
merged = left.copy()
|
||||
merged_by_id = {m.id: i for i, m in enumerate(merged)}
|
||||
ids_to_remove = set()
|
||||
for m in right:
|
||||
if (existing_idx := left_idx_by_id.get(m.id)) is not None:
|
||||
if (existing_idx := merged_by_id.get(m.id)) is not None:
|
||||
if isinstance(m, RemoveMessage):
|
||||
ids_to_remove.add(m.id)
|
||||
else:
|
||||
ids_to_remove.discard(m.id)
|
||||
merged[existing_idx] = m
|
||||
else:
|
||||
if isinstance(m, RemoveMessage):
|
||||
@@ -195,6 +196,7 @@ def add_messages(
|
||||
f"Attempting to delete a message with an ID that doesn't exist ('{m.id}')"
|
||||
)
|
||||
|
||||
merged_by_id[m.id] = len(merged)
|
||||
merged.append(m)
|
||||
merged = [m for m in merged if m.id not in ids_to_remove]
|
||||
|
||||
|
||||
@@ -66,6 +66,31 @@ def test_missing_ids():
|
||||
assert all(isinstance(m.id, str) and UUID(m.id, version=4) for m in result)
|
||||
|
||||
|
||||
def test_duplicates_in_input():
|
||||
left = []
|
||||
right = [
|
||||
AIMessage(id="1", content="Hi there!"),
|
||||
AIMessage(id="1", content="Hi there again!"),
|
||||
]
|
||||
result = add_messages(left, right)
|
||||
assert len(result) == 1
|
||||
assert result[0].id == "1"
|
||||
assert result[0].content == "Hi there again!"
|
||||
|
||||
|
||||
def test_duplicates_in_input_with_remove():
|
||||
left = [AIMessage(id="1", content="Hello!")]
|
||||
right = [
|
||||
RemoveMessage(id="1"),
|
||||
AIMessage(id="1", content="Hi there!"),
|
||||
AIMessage(id="1", content="Hi there again!"),
|
||||
]
|
||||
result = add_messages(left, right)
|
||||
assert len(result) == 1
|
||||
assert result[0].id == "1"
|
||||
assert result[0].content == "Hi there again!"
|
||||
|
||||
|
||||
def test_remove_message():
|
||||
left = [
|
||||
HumanMessage(content="Hello", id="1"),
|
||||
|
||||
Reference in New Issue
Block a user