Skip to content
Open
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
3 changes: 2 additions & 1 deletion python/semantic_kernel/contents/chat_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,12 +300,13 @@ def extend(self, messages: Iterable[ChatMessageContent]) -> None:
def replace(self, messages: Iterable[ChatMessageContent]) -> None:
"""Replace the chat history with a list of messages.

This calls clear() and then extend(messages=messages).
The iterable is consumed before clearing the history so it can refer to the current messages.

Args:
messages: The messages to add to the history.
Can be a list of ChatMessageContent instances or a ChatHistory itself.
"""
messages = list(messages)
self.clear()
self.extend(messages=messages)

Expand Down
28 changes: 28 additions & 0 deletions python/tests/unit/contents/test_chat_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,34 @@ def test_iter(chat_history: ChatHistory):
assert message.content == messages[i]


@pytest.mark.parametrize(
"get_messages",
[lambda history: history, lambda history: history.messages, lambda history: iter(history)],
ids=["history", "messages", "iterator"],
)
def test_replace_from_same_history(chat_history: ChatHistory, get_messages):
chat_history.add_user_message("Question")
chat_history.add_assistant_message("Answer")
expected_messages = list(chat_history)
messages = chat_history.messages

chat_history.replace(get_messages(chat_history))

assert chat_history.messages == expected_messages
assert chat_history.messages is messages


def test_replace_from_filtered_history(chat_history: ChatHistory):
chat_history.add_system_message("Instructions")
chat_history.add_user_message("Question")
chat_history.add_assistant_message("Answer")
expected_messages = chat_history.messages[:2]

chat_history.replace(message for message in chat_history if message.role != AuthorRole.ASSISTANT)

assert chat_history.messages == expected_messages


def test_eq():
# Create two instances of ChatHistory
chat_history1 = ChatHistory()
Expand Down
Loading