Fix template variable handling in ChatPromptTemplate BaseMessage objects #29034 #29057
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.
Title: core: Fix template variable handling in ChatPromptTemplate BaseMessage objects #29034
Description:
Fixes a bug in ChatPromptTemplate where template variables in BaseMessage objects (like SystemMessage) were not being processed. Previously, template variables in direct BaseMessage instances would be left unformatted, while variables in MessagePromptTemplate instances were processed correctly. This PR modifies the format_messages method to properly handle template variables in all message types.
Example of the bug:
template = ChatPromptTemplate.from_messages([
SystemMessage("Answer in {language}"), # Variable not processed
HumanMessagePromptTemplate.from_template("Hello") # Works fine
])
Before fix:
result = template.invoke({"language": "English"})
Output: SystemMessage(content='Answer in {language}') # Variable not replaced
After fix:
result = template.invoke({"language": "English"})
Output: SystemMessage(content='Answer in English') # Variable properly replaced
The fix adds template variable processing for BaseMessage objects while maintaining backward compatibility and existing functionality for other message types.
Key changes:
Modified format_messages method to detect and process template variables in BaseMessage content
Added template variable processing using PromptTemplate for BaseMessage instances
Implemented proper error handling for missing variables or formatting failures
Added comprehensive tests for template variable processing in all message types
Maintained backward compatibility with existing usage patterns
Implementation details:
Uses PromptTemplate for consistent variable formatting
Only attempts formatting when template variables are detected
Preserves original message if formatting fails
Maintains all existing functionality for MessagePromptTemplate instances
@baskaryan, @efriis, @eyurtsev, @ccurme