Skip to content

Python: Preserve messages when replacing chat history from itself - #14465

Open
黄耀鑫(Huang Yaoxin) (YaoxinHuang) wants to merge 2 commits into
microsoft:mainfrom
YaoxinHuang:fix/chat-history-replace-iterables
Open

黄耀鑫(Huang Yaoxin) (YaoxinHuang) wants to merge 2 commits into
microsoft:mainfrom
YaoxinHuang:fix/chat-history-replace-iterables

Conversation

@YaoxinHuang

Copy link
Copy Markdown

Motivation and Context

ChatHistory.replace clears its messages before consuming the replacement iterable. Passing the history itself, its messages list, or a generator filtering the history therefore silently empties it. For example, removing assistant messages with history.replace(m for m in history if m.role != AuthorRole.ASSISTANT) also loses the system and user messages.

Description

Materialize the iterable before clearing the history, while preserving the existing messages list. Add regression coverage for the history, its backing list, an iterator, and a filtered generator.

Validated the contents unit suite, repository pre-commit hooks for both changed files, scoped mypy, and a wheel build. The full optional-provider test matrix was not run.

Contribution Checklist

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟢 Approval recommended

Reviewed changes address the reported replacement behavior with regression coverage.

Review effort: Lite
Findings: None

What changed in this PR

Updates ChatHistory.replace to preserve messages when replacing history from itself or related iterables.

Changes:

  • Materializes replacement messages before clearing history.
  • Adds regression tests for histories, lists, iterators, and filtered generators.
File Description
python/​tests/​unit/​contents/​test_chat_history.py Adds regression coverage for self-referential replacements.
python/​semantic_kernel/​contents/​chat_history.py Safely materializes replacement messages while preserving list identity.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@YaoxinHuang

Copy link
Copy Markdown
Author

@microsoft-github-policy-service agree

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants