OpenAIChatGenerator
OpenAIChatGenerator 使用 OpenAI 的大型语言模型(LLMs)进行聊天补全。
| pipeline 中的最常见位置 | 在 ChatPromptBuilder 之后 |
| 必需的初始化变量 | "api_key": OpenAI API 密钥。可以使用OPENAI_API_KEY 环境变量设置。 |
| 强制运行变量 | “messages”:一个 ChatMessage 对象列表,代表聊天记录 |
| 输出变量 | “replies”:LLM 对输入聊天的替代回复列表 |
| API 参考 | Generators (生成器) |
| GitHub 链接 | https://github.com/deepset-ai/haystack/blob/main/haystack/components/generators/chat/openai.py |
概述
OpenAIChatGenerator 支持从 gpt-3.5-turbo 及更高版本开始的 OpenAI 模型(如 gpt-4、gpt-4-turbo 等)。
OpenAIChatGenerator 需要一个 OpenAI 密钥才能工作。默认情况下,它使用 OPENAI_API_KEY 环境变量。否则,您可以在初始化时通过以下方式传递 API 密钥:api_key:
generator = OpenAIChatGenerator(model="gpt-4o-mini")
然后,组件需要一个 ChatMessage 对象列表才能运行。ChatMessage 对象列表才能运行。ChatMessage 是一个数据类,其中包含消息、角色(谁生成了消息,例如user, assistant, system, function),以及可选的元数据。有关示例,请参阅使用部分。
您可以将适用于openai.ChatCompletion.create 方法的任何聊天补全参数直接传递给OpenAIChatGenerator,使用generation_kwargs 参数,无论是初始化时还是run() 方法。有关 OpenAI API 支持的参数的更多详细信息,请参阅OpenAI 文档。
OpenAIChatGenerator 可以通过api_base_url 初始化参数支持您的 OpenAI 模型的自定义部署。
结构化输出
OpenAIChatGenerator 支持结构化输出生成,允许您以可预测的格式接收响应。您可以使用 Pydantic 模型或 JSON Schema 来定义输出的结构,通过response_format 参数在generation_kwargs.
这对于需要从文本中提取结构化数据或生成与特定格式匹配的响应非常有用。
from pydantic import BaseModel
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.dataclasses import ChatMessage
class NobelPrizeInfo(BaseModel):
recipient_name: str
award_year: int
category: str
achievement_description: str
nationality: str
client = OpenAIChatGenerator(
model="gpt-4o-2024-08-06",
generation_kwargs={"response_format": NobelPrizeInfo}
)
response = client.run(messages=[
ChatMessage.from_user(
"In 2021, American scientist David Julius received the Nobel Prize in"
" Physiology or Medicine for his groundbreaking discoveries on how the human body"
" senses temperature and touch."
)
])
print(response["replies"][0].text)
>> {"recipient_name":"David Julius","award_year":2021,"category":"Physiology or Medicine",
>> "achievement_description":"David Julius was awarded for his transformative findings
>> regarding the molecular mechanisms underlying the human body's sense of temperature
>> and touch. Through innovative experiments, he identified specific receptors responsible
>> for detecting heat and mechanical stimuli, ranging from gentle touch to pain-inducing
>> pressure.","nationality":"American"}
模型兼容性和限制
- Pydantic 模型和 JSON Schema 支持最新的模型,从
gpt-4o-2024-08-06.- 开始。旧模型仅支持通过
{"type": "json_object"}进行基本的 JSON 模式。有关详细信息,请参阅OpenAI JSON 模式文档。- 流式输出限制:在使用流式输出和结构化输出时,您必须为
response_format.- 提供 JSON Schema 而不是 Pydantic 模型。有关完整信息,请查阅OpenAI 结构化输出文档。
流式传输
您可以随着输出的生成而流式传输。将回调函数传递给streaming_callback。使用内置的print_streaming_chunk 来打印文本 token 和工具事件(工具调用和工具结果)。
from haystack.components.generators.utils import print_streaming_chunk
# Configure any `Generator` or `ChatGenerator` with a streaming callback
component = SomeGeneratorOrChatGenerator(streaming_callback=print_streaming_chunk)
# If this is a `ChatGenerator`, pass a list of messages:
# from haystack.dataclasses import ChatMessage
# component.run([ChatMessage.from_user("Your question here")])
# If this is a (non-chat) `Generator`, pass a prompt:
# component.run({"prompt": "Your prompt here"})
流式输出仅适用于单个响应。如果提供程序支持多个候选,请将
n=1.
设置为 1。有关流式输出如何工作以及如何编写自定义回调函数,请参阅我们的流式输出支持文档。StreamingChunk 工作原理以及如何编写自定义回调。
默认首选print_streaming_chunk。仅当您需要特定的传输(例如 SSE/WebSocket)或自定义 UI 格式时,才编写自定义回调。
用法
单独使用
基本用法
from haystack.dataclasses import ChatMessage
from haystack.components.generators.chat import OpenAIChatGenerator
client = OpenAIChatGenerator()
response = client.run(
[ChatMessage.from_user("What's Natural Language Processing? Be brief.")]
)
print(response)
>> {'replies': [ChatMessage(_role=<ChatRole.ASSISTANT: 'assistant'>, _content=
>> [TextContent(text='Natural Language Processing (NLP) is a field of artificial
>> intelligence that focuses on the interaction between computers and humans through
>> natural language. It involves enabling machines to understand, interpret, and
>> generate human language in a meaningful way, facilitating tasks such as
>> language translation, sentiment analysis, and text summarization.')],
>> _name=None, _meta={'model': 'gpt-4o-mini-2024-07-18', 'index': 0,
>> 'finish_reason': 'stop', 'usage': {'completion_tokens': 59, 'prompt_tokens': 15,
>> 'total_tokens': 74, 'completion_tokens_details': {'accepted_prediction_tokens':
>> 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0},
>> 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}})]}
使用流式传输
from haystack.dataclasses import ChatMessage
from haystack.components.generators.chat import OpenAIChatGenerator
client = OpenAIChatGenerator(streaming_callback=lambda chunk: print(chunk.content, end="", flush=True))
response = client.run(
[ChatMessage.from_user("What's Natural Language Processing? Be brief.")]
)
print(response)
>> Natural Language Processing (NLP) is a field of artificial intelligence that
>> focuses on the interaction between computers and humans through natural language.
>> It involves enabling machines to understand, interpret, and generate human
>> language in a way that is both meaningful and useful. NLP encompasses various
>> tasks, including speech recognition, language translation, sentiment analysis,
>> and text summarization.{'replies': [ChatMessage(_role=<ChatRole.ASSISTANT:
>> 'assistant'>, _content=[TextContent(text='Natural Language Processing (NLP) is a
>> field of artificial intelligence that focuses on the interaction between computers
>> and humans through natural language. It involves enabling machines to understand,
>> interpret, and generate human language in a way that is both meaningful and
>> useful. NLP encompasses various tasks, including speech recognition, language
>> translation, sentiment analysis, and text summarization.')], _name=None, _meta={'
>> model': 'gpt-4o-mini-2024-07-18', 'index': 0, 'finish_reason': 'stop',
>> 'completion_start_time': '2025-05-15T13:32:16.572912', 'usage': None})]}
使用多模态输入
from haystack.dataclasses import ChatMessage, ImageContent
from haystack.components.generators.chat import OpenAIChatGenerator
llm = OpenAIChatGenerator(model="gpt-4o-mini")
image = ImageContent.from_file_path("apple.jpg", detail="low")
user_message = ChatMessage.from_user(content_parts=[
"What does the image show? Max 5 words.",
image
])
response = llm.run([user_message])["replies"][0].text
print(response)
>>> Red apple on straw.
在 Pipeline 中
from haystack.components.builders import ChatPromptBuilder
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.dataclasses import ChatMessage
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_env_var("OPENAI_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"
messages = [ChatMessage.from_system("Always respond in German even if some input data is in other languages."),
ChatMessage.from_user("Tell me about {{location}}")]
pipe.run(data={"prompt_builder": {"template_variables":{"location": location}, "template": messages}})
>> {'llm': {'replies': [ChatMessage(_role=<ChatRole.ASSISTANT: 'assistant'>,
>> _content=[TextContent(text='Berlin ist die Hauptstadt Deutschlands und eine der
>> bedeutendsten Städte Europas. Sie ist bekannt für ihre reiche Geschichte,
>> kulturelle Vielfalt und kreative Szene. \n\nDie Stadt hat eine bewegte
>> Vergangenheit, die stark von der Teilung zwischen Ost- und Westberlin während
>> des Kalten Krieges geprägt war. Die Berliner Mauer, die von 1961 bis 1989 die
>> Stadt teilte, ist heute ein Symbol für die Wiedervereinigung und die Freiheit.
>> \n\nBerlin bietet eine Fülle von Sehenswürdigkeiten, darunter das Brandenburger
>> Tor, den Reichstag, die Museumsinsel und den Alexanderplatz. Die Stadt ist auch
>> für ihre lebendige Kunst- und Musikszene bekannt, mit zahlreichen Galerien,
>> Theatern und Clubs. ')], _name=None, _meta={'model': 'gpt-4o-mini-2024-07-18',
>> 'index': 0, 'finish_reason': 'stop', 'usage': {'completion_tokens': 260,
>> 'prompt_tokens': 29, 'total_tokens': 289, 'completion_tokens_details':
>> {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0,
>> 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0,
>> 'cached_tokens': 0}}})]}}
其他参考资料
📓 教程:使用函数调用构建聊天应用程序
更新于 9 天前
