fix(core): remove orphaned ToolMessages in trim_messages #33268
+117
−6
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary: Ensure trimmed chat histories drop ToolMessages whose originating tool calls were trimmed away, preventing invalid assistant-tool exchanges. Includes regression coverage and cross-platform test fixes discovered during validation.
Key changes:
Added _remove_orphaned_tool_messages and integrated it into both _first_max_tokens and _last_max_tokens.
Extended tests/unit_tests/messages/test_utils.py with scenarios covering orphan removal and preservation.
Hardened tests/unit_tests/prompts/test_prompt.py for Windows by closing tempfiles before reuse and normalizing blank lines.
Updated tests/unit_tests/test_imports.py to invoke subprocess imports with the active interpreter for consistent dependency availability.
Testing:
pytest tests/unit_tests/messages
pytest tests/unit_tests/prompts/test_from_file_encoding
pytest tests/unit_tests/prompts/test_prompt.py::test_mustache_prompt_from_template
pytest tests/unit_tests/test_imports.py
Full sweep: pytest tests/unit_tests (1,341 passed, 24 skipped, 10 xfailed, 2 xpassed, 1 warning about LangSmith key)
quality gates
Build: PASS (not rerun; no build artifacts changed)
Lint / Typecheck: PASS (ruff & mypy previously green; no new code edits)
Unit tests: PASS (runs listed above)
Smoke test: Not applicable (library-only change)
notes
External research depended on GitHub issue content due to blocked Google access (consent/CAPTCHA); no additional upstream changes detected.
All four modified files (langchain_core/messages/utils.py, tests/unit_tests/messages/test_utils.py, tests/unit_tests/prompts/test_prompt.py, tests/unit_tests/test_imports.py) are required for the fix.
Fixes #33245