用于构建提示和 ChatMessages 的组件。
模块 haystack_experimental.components.builders.chat_prompt_builder
ChatPromptBuilder
使用 Jinja2 语法从模板字符串渲染聊天提示。
它使用静态或动态模板来构建提示,您可以在每次管道运行时进行更新。
模板中的模板变量是可选的,除非另有说明。如果未提供可选变量,则默认为空字符串。使用variable和required_variables来定义输入类型和必需的变量。
使用示例
使用静态提示模板
template = [ChatMessage.from_user("Translate to {{ target_language }}. Context: {{ snippet }}; Translation:")]
builder = ChatPromptBuilder(template=template)
builder.run(target_language="spanish", snippet="I can't speak spanish.")
在运行时覆盖静态模板
template = [ChatMessage.from_user("Translate to {{ target_language }}. Context: {{ snippet }}; Translation:")]
builder = ChatPromptBuilder(template=template)
builder.run(target_language="spanish", snippet="I can't speak spanish.")
msg = "Translate to {{ target_language }} and summarize. Context: {{ snippet }}; Summary:"
summary_template = [ChatMessage.from_user(msg)]
builder.run(target_language="spanish", snippet="I can't speak spanish.", template=summary_template)
使用动态提示模板
from haystack_experimental.components.builders import ChatPromptBuilder
from haystack_experimental.dataclasses import ChatMessage
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack import Pipeline
from haystack.utils import Secret
# no parameter init, we don't use any runtime template variables
prompt_builder = ChatPromptBuilder()
llm = OpenAIChatGenerator(api_key=Secret.from_token("<your-api-key>"), model="gpt-4o-mini")
pipe = Pipeline()
pipe.add_component("prompt_builder", prompt_builder)
pipe.add_component("llm", llm)
pipe.connect("prompt_builder.prompt", "llm.messages")
location = "Berlin"
language = "English"
system_message = ChatMessage.from_system("You are an assistant giving information to tourists in {{language}}")
messages = [system_message, ChatMessage.from_user("Tell me about {{location}}")]
res = pipe.run(data={"prompt_builder": {"template_variables": {"location": location, "language": language},
"template": messages}})
print(res)
>> {'llm': {'replies': [ChatMessage(_role=<ChatRole.ASSISTANT: 'assistant'>, _content=[TextContent(text='Berlin is
the capital city of Germany and one of the most vibrant and diverse cities in Europe. Here are some key things to
know...Enjoy your time exploring the vibrant and dynamic capital of Germany!')], _meta={'model': 'gpt-4o-mini',
'index': 0, 'finish_reason': 'stop', 'usage': {'prompt_tokens': 27, 'completion_tokens': 681, 'total_tokens': 708
}})]}}
messages = [system_message, ChatMessage.from_user("What's the weather forecast for {{location}} in the next
{{day_count}} days?")]
res = pipe.run(data={"prompt_builder": {"template_variables": {"location": location, "day_count": "5"},
"template": messages}})
print(res)
>> {'llm': {'replies': [ChatMessage(_role=<ChatRole.ASSISTANT: 'assistant'>, _content=[TextContent(text='Here is
the weather forecast for Berlin in the next 5 days:\n\nDay 1: Mostly cloudy with a high of 22°C (72°F) and...so
it's always a good idea to check for updates closer to your visit.')], _meta={'model': 'gpt-4o-mini', 'index': 0,
'finish_reason': 'stop', 'usage': {'prompt_tokens': 37, 'completion_tokens': 201, 'total_tokens': 238}})]}}
新的实验性提示模板
from haystack_experimental.components.builders import ChatPromptBuilder
from haystack.dataclasses.image_content import ImageContent
template = """
{% message role="system" %}
You are a helpful assistant.
{% endmessage %}
{% message role="user" %}
Hello! I am {{user_name}}. What's the difference between the following images?
{% for image in images %}
{{ image | templatize_part }}
{% endfor %}
{% endmessage %}
"""
images = [ImageContent.from_file_path("apple.jpg"), ImageContent.from_file_path("orange.jpg")]
builder = ChatPromptBuilder(template=template)
builder.run(user_name="John", images=images)
ChatPromptBuilder.__init__
def __init__(template: Optional[Union[List[ChatMessage], str]] = None,
required_variables: Optional[Union[List[str],
Literal["*"]]] = None,
variables: Optional[List[str]] = None)
构造一个 ChatPromptBuilder 组件。
参数:
template: 一个ChatMessage对象列表或一个字符串模板。该组件查找 Jinja2 模板语法并使用提供的变量渲染提示。在init方法中提供模板或run`方法中。required_variables: 必须作为输入提供给 ChatPromptBuilder 的变量列表。如果提供的必需变量未提供,则会引发异常。如果设置为“*”,则提示中找到的所有变量都是必需的。可选。variables: 列表输入变量,用于提示模板而不是从template参数推断出的变量。例如,如果您想在提示工程中使用比默认模板中存在的变量更多的变量,可以在此处提供它们。
ChatPromptBuilder.run
@component.output_types(prompt=List[ChatMessage])
def run(template: Optional[Union[List[ChatMessage], str]] = None,
template_variables: Optional[Dict[str, Any]] = None,
**kwargs: Any) -> Dict[str, List[ChatMessage]]
使用提供的变量渲染提示模板。
它应用模板变量来渲染最终提示。您可以使用管道 kwargs 提供变量。要覆盖默认模板,您可以设置template参数。要覆盖管道 kwargs,您可以设置template_variables参数。
参数:
template: 一个可选的ChatMessage对象列表或字符串模板,用于覆盖 ChatPromptBuilder 的默认模板。如果None,则使用初始化时提供的默认模板。template_variables: 一个可选的模板变量字典,用于覆盖管道变量。kwargs: 用于渲染提示的管道变量。
引发:
ValueError: 如果chat_messages为空或包含不是实例的元素ChatMessage.
返回值:
包含以下键的字典
prompt: 渲染模板后更新的ChatMessage对象列表。
ChatPromptBuilder.to_dict
def to_dict() -> Dict[str, Any]
返回组件的字典表示。
返回值:
组件的序列化字典表示。
ChatPromptBuilder.from_dict
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "ChatPromptBuilder"
从字典反序列化此组件。
参数:
data: 要反序列化并创建组件的字典。
返回值:
反序列化后的组件。
