-
Notifications
You must be signed in to change notification settings - Fork 15.9k
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]: dict chat prompt template support #25674
Draft
baskaryan
wants to merge
8
commits into
master
Choose a base branch
from
bagatur/dict_msg_tmpl2
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+350
−86
Draft
Changes from 3 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
76858e3
wip
baskaryan fe1d02c
Merge branch 'master' into bagatur/dict_msg_tmpl2
baskaryan 27c8ba6
core[minor]: dict chat prompt template support
baskaryan 10ef356
fmt
baskaryan 5c761bd
merge
baskaryan 100dc2e
fmt
baskaryan d7dd172
fmt
baskaryan 76b2520
fmt
baskaryan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,167 @@ | ||
"""Message prompt templates.""" | ||
|
||
from __future__ import annotations | ||
|
||
from abc import ABC, abstractmethod | ||
from typing import TYPE_CHECKING, Any, Dict, List, Literal | ||
|
||
from langchain_core.load import Serializable | ||
from langchain_core.messages import BaseMessage, convert_to_messages | ||
from langchain_core.prompts.string import ( | ||
DEFAULT_FORMATTER_MAPPING, | ||
get_template_variables, | ||
) | ||
from langchain_core.utils.image import image_to_data_url | ||
from langchain_core.utils.interactive_env import is_interactive_env | ||
|
||
if TYPE_CHECKING: | ||
from langchain_core.prompts.chat import ChatPromptTemplate | ||
|
||
|
||
class BaseMessagePromptTemplate(Serializable, ABC): | ||
"""Base class for message prompt templates.""" | ||
|
||
@classmethod | ||
def is_lc_serializable(cls) -> bool: | ||
"""Return True if the class is serializable, else False. | ||
|
||
Returns: | ||
True | ||
""" | ||
return True | ||
|
||
@classmethod | ||
def get_lc_namespace(cls) -> List[str]: | ||
"""Get the namespace of the langchain object.""" | ||
return ["langchain", "prompts", "chat"] | ||
|
||
@abstractmethod | ||
def format_messages(self, **kwargs: Any) -> List[BaseMessage]: | ||
"""Format messages from kwargs. Should return a list of BaseMessages. | ||
|
||
Args: | ||
**kwargs: Keyword arguments to use for formatting. | ||
|
||
Returns: | ||
List of BaseMessages. | ||
""" | ||
|
||
async def aformat_messages(self, **kwargs: Any) -> List[BaseMessage]: | ||
"""Async format messages from kwargs. | ||
Should return a list of BaseMessages. | ||
|
||
Args: | ||
**kwargs: Keyword arguments to use for formatting. | ||
|
||
Returns: | ||
List of BaseMessages. | ||
""" | ||
return self.format_messages(**kwargs) | ||
|
||
@property | ||
@abstractmethod | ||
def input_variables(self) -> List[str]: | ||
"""Input variables for this prompt template. | ||
|
||
Returns: | ||
List of input variables. | ||
""" | ||
|
||
def pretty_repr(self, html: bool = False) -> str: | ||
"""Human-readable representation. | ||
|
||
Args: | ||
html: Whether to format as HTML. Defaults to False. | ||
|
||
Returns: | ||
Human-readable representation. | ||
""" | ||
raise NotImplementedError | ||
|
||
def pretty_print(self) -> None: | ||
"""Print a human-readable representation.""" | ||
print(self.pretty_repr(html=is_interactive_env())) # noqa: T201 | ||
|
||
def __add__(self, other: Any) -> ChatPromptTemplate: | ||
"""Combine two prompt templates. | ||
|
||
Args: | ||
other: Another prompt template. | ||
|
||
Returns: | ||
Combined prompt template. | ||
""" | ||
from langchain_core.prompts.chat import ChatPromptTemplate | ||
|
||
prompt = ChatPromptTemplate(messages=[self]) # type: ignore[call-arg] | ||
return prompt + other | ||
|
||
|
||
class _DictMessagePromptTemplate(BaseMessagePromptTemplate): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. new type |
||
"""Template represented by a dict that looks for input vars in all leaf vals. | ||
|
||
Special handling of any dict value that contains | ||
``{"type": "image_url", "image_url": {"path": "..."}}`` | ||
""" | ||
|
||
template: Dict[str, Any] | ||
template_format: Literal["f-string", "mustache"] | ||
|
||
def format_messages(self, **kwargs: Any) -> List[BaseMessage]: | ||
msg_dict = _insert_input_variables(self.template, kwargs, self.template_format) | ||
return convert_to_messages([msg_dict]) | ||
|
||
@property | ||
def input_variables(self) -> List[str]: | ||
return _get_input_variables(self.template, self.template_format) | ||
|
||
@property | ||
def _prompt_type(self) -> str: | ||
return "message-dict-prompt" | ||
|
||
|
||
def _get_input_variables( | ||
template: dict, template_format: Literal["f-string", "mustache"] | ||
) -> List[str]: | ||
input_variables = [] | ||
for k, v in template.items(): | ||
if isinstance(v, str): | ||
input_variables += get_template_variables(v, template_format) | ||
elif isinstance(v, dict): | ||
input_variables += _get_input_variables(v, template_format) | ||
elif isinstance(v, (list, tuple)): | ||
for x in v: | ||
if isinstance(x, str): | ||
input_variables += get_template_variables(x, template_format) | ||
elif isinstance(x, dict): | ||
input_variables += _get_input_variables(x, template_format) | ||
return list(set(input_variables)) | ||
|
||
|
||
def _insert_input_variables( | ||
template: Dict[str, Any], | ||
inputs: Dict[str, Any], | ||
template_format: Literal["f-string", "mustache"], | ||
) -> Dict[str, Any]: | ||
formatted = {} | ||
formatter = DEFAULT_FORMATTER_MAPPING[template_format] | ||
for k, v in template.items(): | ||
if isinstance(v, str): | ||
formatted[k] = formatter(v, **inputs) | ||
elif isinstance(v, dict): | ||
# Special handling for loading local images. | ||
if k == "image_url" and "path" in v: | ||
formatted_path = formatter(v.pop("path"), **inputs) | ||
v["url"] = image_to_data_url(formatted_path) | ||
formatted[k] = _insert_input_variables(v, inputs, template_format) | ||
elif isinstance(v, (list, tuple)): | ||
formatted_v = [] | ||
for x in v: | ||
if isinstance(x, str): | ||
formatted_v.append(formatter(x, **inputs)) | ||
elif isinstance(x, dict): | ||
formatted_v.append( | ||
_insert_input_variables(x, inputs, template_format) | ||
) | ||
formatted[k] = type(v)(formatted_v) | ||
return formatted |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Oops, something went wrong.
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
no change, just moved