您能告诉我何时使用以及为什么使用上述功能吗?
我尝试阅读文档,但没有理解太多。任何对此博客或链接的引用也会有所帮助。
提前致谢。
你应该去源代码实现。在代码中他们注释掉了,你也可以看到发生了什么。这些方法实际上是通过额外的配置和验证来实例化类实例。例如,如果您查看
from_messages
实现:
@classmethod
def from_messages(
cls,
messages: Sequence[
Union[
BaseMessagePromptTemplate,
BaseChatPromptTemplate,
BaseMessage,
Tuple[str, str],
Tuple[Type, str],
str,
]
],
) -> ChatPromptTemplate:
"""Create a chat prompt template from a variety of message formats.
Examples:
Instantiation from a list of message templates:
.. code-block:: python
template = ChatPromptTemplate.from_messages([
("human", "Hello, how are you?"),
("ai", "I'm doing well, thanks!"),
("human", "That's good to hear."),
])
Instantiation from mixed message formats:
.. code-block:: python
template = ChatPromptTemplate.from_messages([
SystemMessage(content="hello"),
("human", "Hello, how are you?"),
])
Args:
messages: sequence of message representations.
A message can be represented using the following formats:
(1) BaseMessagePromptTemplate, (2) BaseMessage, (3) 2-tuple of
(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}"
Returns:
a chat prompt template
"""
_messages = [_convert_to_message(message) for message in messages]
# Automatically infer input variables from messages
input_vars = 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)
这个方法,
首先使用
_convert_to_message
帮助器,它将每条消息转换为 ChatPromptTemplate 类可以使用的标准化格式
然后使用
input_vars = set
消除重复消息。
input_variables
是消息模板中的占位符,在使用模板时将替换为实际值。例如,消息可能具有类似“Hello, {user_name}!”的模板,其中 {user_name} 是输入变量。
然后检查他们接受什么样的消息:
BaseChatPromptTemplate, BaseMessagePromptTemplate
收集所有唯一的输入变量后,返回
return cls(input_variables=sorted(input_vars), messages=_messages)
此行使用推断的输入变量和处理的消息创建并返回 ChatPromptTemplate 的实例。
这是
from_template
方法:
@classmethod
def from_template(
cls: Type[MessagePromptTemplateT],
template: str,
template_format: str = "f-string",
**kwargs: Any,
) -> MessagePromptTemplateT:
"""Create a class from a string template.
Args:
template: a template.
template_format: format of the template.
**kwargs: keyword arguments to pass to the constructor.
Returns:
A new instance of this class.
"""
prompt = PromptTemplate.from_template(template, template_format=template_format)
return cls(prompt=prompt, **kwargs)
from_template
采用单个模板字符串(和可选格式)来创建实例。 from_messages
采用各种格式的消息序列来创建实例。