feat(core): add to_message_state and as_message_state helpers for LCEL message normalization #34094
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.
Description
This PR introduces two new utilities to the
langchain_core.messagesmodule:to_message_stateas_message_stateThese helpers provide a consistent and centralized way to normalize various message-like inputs into the canonical LCEL message state:
They allow LCEL pipelines to seamlessly handle strings,
BaseMessageinstances, mixed lists, and pre-existing{"messages": [...]}dicts without needing to duplicate normalization logic across runnables.This change follows the discussion in Issue #34061 and places the implementation in the appropriate module (
messages.utils), preserving clear domain boundaries and avoiding unnecessary coupling withrunnables.Fixes #34061
Issue
The absence of a standardized message-normalization helper required LCEL chains to implement small variations of the same logic.
This PR resolves that by providing a unified, well-tested implementation.
Dependencies
No new dependencies were added.
No modifications to
pyproject.tomloruv.lock.Changes are limited to:
Tests
This PR includes a dedicated test file:
Test coverage includes:
HumanMessageBaseMessagepassthroughBaseMessage)Nonenormalizationas_message_stateAll tests pass locally:
Linting and formatting also pass (
ruff check .is clean).Notes
An earlier community PR attempted to introduce message normalization inside
runnables, but message transformation belongs to themessagesdomain.This PR follows the expected architecture of LangChain Core, keeps responsibilities separated, and avoids circular dependencies.
Happy to adjust naming or behavior based on reviewer feedback.