Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

core[minor]: Init ChatPromptTemplate with message-like representations #16851

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 58 additions & 39 deletions libs/core/langchain_core/prompts/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -593,6 +593,24 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
validate_template: bool = False
"""Whether or not to try validating the template."""

def __init__(
self,
messages: Sequence[MessageLikeRepresentation],
Copy link
Collaborator

Choose a reason for hiding this comment

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

Could we put a * here so that only messages can be passed by position

input_variables: Optional[Sequence[str]] = None,
**kwargs: Any,
) -> None:
_messages = [_convert_to_message(msg) for msg in messages]
if input_variables is None:
prompts = [
msg
for msg in _messages
if isinstance(msg, (BaseChatPromptTemplate, BaseMessagePromptTemplate))
]
input_variables = list(
set(iv for prompt in prompts for iv in prompt.input_variables)
)
super().__init__(messages=_messages, input_variables=input_variables, **kwargs)

@classmethod
def get_lc_namespace(cls) -> List[str]:
"""Get the namespace of the langchain object."""
Expand Down Expand Up @@ -677,45 +695,9 @@ def from_template(cls, template: str, **kwargs: Any) -> ChatPromptTemplate:
message = HumanMessagePromptTemplate(prompt=prompt_template)
return cls.from_messages([message])

@classmethod
@deprecated("0.0.260", alternative="from_messages classmethod", pending=True)
def from_role_strings(
cls, string_messages: List[Tuple[str, str]]
) -> ChatPromptTemplate:
"""Create a chat prompt template from a list of (role, template) tuples.

Args:
string_messages: list of (role, template) tuples.

Returns:
a chat prompt template
"""
return cls(
messages=[
ChatMessagePromptTemplate.from_template(template, role=role)
for role, template in string_messages
]
)

@classmethod
@deprecated("0.0.260", alternative="from_messages classmethod", pending=True)
def from_strings(
cls, string_messages: List[Tuple[Type[BaseMessagePromptTemplate], str]]
) -> ChatPromptTemplate:
"""Create a chat prompt template from a list of (role class, template) tuples.

Args:
string_messages: list of (role class, template) tuples.

Returns:
a chat prompt template
"""
return cls.from_messages(string_messages)

@classmethod
def from_messages(
cls,
messages: Sequence[MessageLikeRepresentation],
cls, messages: Sequence[MessageLikeRepresentation], **kwargs: Any
) -> ChatPromptTemplate:
"""Create a chat prompt template from a variety of message formats.

Expand Down Expand Up @@ -747,21 +729,23 @@ def from_messages(
(message type, template); e.g., ("human", "{user_input}"),
(4) 2-tuple of (message class, template), (4) a string which is
shorthand for ("human", template); e.g., "{user_input}"
**kwargs: Additional keyword arguments to pass to ChatPromptTemplate
constructor.

Returns:
a chat prompt template
"""
_messages = [_convert_to_message(message) for message in messages]

# Automatically infer input variables from messages
input_vars: Set[str] = set()
input_vars: Set[str] = kwargs.pop("input_variables", set())
for _message in _messages:
if isinstance(
_message, (BaseChatPromptTemplate, BaseMessagePromptTemplate)
):
input_vars.update(_message.input_variables)

return cls(input_variables=sorted(input_vars), messages=_messages)
return cls(input_variables=sorted(input_vars), messages=_messages, **kwargs)

def format(self, **kwargs: Any) -> str:
"""Format the chat template into a string.
Expand Down Expand Up @@ -887,6 +871,41 @@ def pretty_repr(self, html: bool = False) -> str:
# TODO: handle partials
return "\n\n".join(msg.pretty_repr(html=html) for msg in self.messages)

@classmethod
@deprecated("0.0.260", alternative="from_messages classmethod", pending=True)
def from_role_strings(
cls, string_messages: List[Tuple[str, str]]
) -> ChatPromptTemplate:
"""Create a chat prompt template from a list of (role, template) tuples.

Args:
string_messages: list of (role, template) tuples.

Returns:
a chat prompt template
"""
return cls(
messages=[
ChatMessagePromptTemplate.from_template(template, role=role)
for role, template in string_messages
]
)

@classmethod
@deprecated("0.0.260", alternative="from_messages classmethod", pending=True)
def from_strings(
cls, string_messages: List[Tuple[Type[BaseMessagePromptTemplate], str]]
) -> ChatPromptTemplate:
"""Create a chat prompt template from a list of (role class, template) tuples.

Args:
string_messages: list of (role class, template) tuples.

Returns:
a chat prompt template
"""
return cls.from_messages(string_messages)


def _create_template_from_message_type(
message_type: str, template: Union[str, list]
Expand Down
Loading