mirror of
https://github.com/hwchase17/langchain.git
synced 2026-06-09 10:17:00 +00:00
fix(core): support (message class, template) tuples in ChatPromptTemplate.from_messages (#33989)
### Description
`ChatPromptTemplate.from_messages` supports multiple tuple formats for
defining message templates. One documented format is `(message class,
template)`, which allows users to specify the message type using the
class directly:
```python
ChatPromptTemplate.from_messages([
(SystemMessage, "You are a helpful assistant named {name}."),
(HumanMessage, "{input}"),
])
```
However, this syntax was broken. Passing a tuple like `(HumanMessage,
"{input}")` would raise a Pydantic validation error because the
conversion logic in `_convert_to_message_template` didn't handle
`BaseMessage` subclasses—it only recognized string-based role
identifiers like `"human"` or `"system"`.
This PR adds the missing branch to detect when the first element of a
tuple is a message class (by checking for the `type` class attribute)
and routes it through `_create_template_from_message_type`, which
already knows how to create the appropriate `MessagePromptTemplate` for
each message type.
### Changes
- Updated `_convert_to_message_template` to properly support `(message
class, template)` tuples
### Testing
Added 16 comprehensive unit tests covering:
- Basic usage with `HumanMessage`, `AIMessage`, and `SystemMessage`
classes
- Integration with `invoke()` method
- Mixed syntax (message class tuples alongside string tuples)
- Multiple template variables
- Edge cases: empty templates, static text (no variables)
- Correct extraction of `input_variables`
- Partial variables support
- Combination with `MessagesPlaceholder`
- Mustache template format
- Template operations: `append()`, `extend()`, concatenation, and
slicing
- Special characters and unicode in templates
### Issue
Fixes #33791
### Dependencies
None
---------
Co-authored-by: Mason Daugherty <mason@langchain.dev>
This commit is contained in:
@@ -1438,6 +1438,14 @@ def _convert_to_message_template(
|
||||
message_ = _create_template_from_message_type(
|
||||
message_type_str, template, template_format=template_format
|
||||
)
|
||||
elif (
|
||||
hasattr(message_type_str, "model_fields")
|
||||
and "type" in message_type_str.model_fields
|
||||
):
|
||||
message_type = message_type_str.model_fields["type"].default
|
||||
message_ = _create_template_from_message_type(
|
||||
message_type, template, template_format=template_format
|
||||
)
|
||||
else:
|
||||
message_ = message_type_str(
|
||||
prompt=PromptTemplate.from_template(
|
||||
|
||||
Reference in New Issue
Block a user