codekingpro/portable-devtools
114k
1"""Message prompt templates."""2 3from __future__ import annotations4 5from abc import ABC, abstractmethod6from typing import TYPE_CHECKING, Any7 8from langchain_core.load import Serializable9from langchain_core.utils.interactive_env import is_interactive_env10 11if TYPE_CHECKING:12 from langchain_core.messages import BaseMessage13 from langchain_core.prompts.chat import ChatPromptTemplate14 15 16class BaseMessagePromptTemplate(Serializable, ABC):17 """Base class for message prompt templates."""18 19 @classmethod20 def is_lc_serializable(cls) -> bool:21 """Return `True` as this class is serializable."""22 return True23 24 @classmethod25 def get_lc_namespace(cls) -> list[str]:26 """Get the namespace of the LangChain object.27 28 Returns:29 `["langchain", "prompts", "chat"]`30 """31 return ["langchain", "prompts", "chat"]32 33 @abstractmethod34 def format_messages(self, **kwargs: Any) -> list[BaseMessage]:35 """Format messages from kwargs.36 37 Should return a list of `BaseMessage` objects.38 39 Args:40 **kwargs: Keyword arguments to use for formatting.41 42 Returns:43 List of `BaseMessage` objects.44 """45 46 async def aformat_messages(self, **kwargs: Any) -> list[BaseMessage]:47 """Async format messages from kwargs.48 49 Args:50 **kwargs: Keyword arguments to use for formatting.51 52 Returns:53 List of `BaseMessage` objects.54 """55 return self.format_messages(**kwargs)56 57 @property58 @abstractmethod59 def input_variables(self) -> list[str]:60 """Input variables for this prompt template.61 62 Returns:63 List of input variables.64 """65 66 def pretty_repr(67 self,68 html: bool = False, # noqa: FBT001,FBT00269 ) -> str:70 """Human-readable representation.71 72 Args:73 html: Whether to format as HTML.74 75 Returns:76 Human-readable representation.77 """78 raise NotImplementedError79 80 def pretty_print(self) -> None:81 """Print a human-readable representation."""82 print(self.pretty_repr(html=is_interactive_env())) # noqa: T20183 84 def __add__(self, other: Any) -> ChatPromptTemplate:85 """Combine two prompt templates.86 87 Args:88 other: Another prompt template.89 90 Returns:91 Combined prompt template.92 """93 # Import locally to avoid circular import.94 from langchain_core.prompts.chat import ChatPromptTemplate # noqa: PLC041595 96 prompt = ChatPromptTemplate(messages=[self])97 return prompt.__add__(other)98 