启用使用大型语言模型 (LLM) 生成文本。
模块 azure
AzureOpenAIGenerator
使用 OpenAI 的大型语言模型 (LLM) 生成文本。
它适用于 gpt-4 类型模型,并支持从 OpenAI API 传输响应。
您可以通过将参数传递给 OpenAI API 来定制文本的生成方式。使用**generation_kwargs 参数在初始化组件或运行它时。任何适用于openai.ChatCompletion.create 的参数也适用于此处。
有关 OpenAI API 参数的详细信息,请参阅 OpenAI 文档。
使用示例
from haystack.components.generators import AzureOpenAIGenerator
from haystack.utils import Secret
client = AzureOpenAIGenerator(
azure_endpoint="<Your Azure endpoint e.g. `https://your-company.azure.openai.com/>",
api_key=Secret.from_token("<your-api-key>"),
azure_deployment="<this a model name, e.g. gpt-4o-mini>")
response = client.run("What's Natural Language Processing? Be brief.")
print(response)
>> {'replies': ['Natural Language Processing (NLP) is a branch of artificial intelligence that focuses on
>> the interaction between computers and human language. It involves enabling computers to understand, interpret,
>> and respond to natural human language in a way that is both meaningful and useful.'], 'meta': [{'model':
>> 'gpt-4o-mini', 'index': 0, 'finish_reason': 'stop', 'usage': {'prompt_tokens': 16,
>> 'completion_tokens': 49, 'total_tokens': 65}}]}
AzureOpenAIGenerator.__init__
def __init__(azure_endpoint: Optional[str] = None,
api_version: Optional[str] = "2023-05-15",
azure_deployment: Optional[str] = "gpt-4o-mini",
api_key: Optional[Secret] = Secret.from_env_var(
"AZURE_OPENAI_API_KEY", strict=False),
azure_ad_token: Optional[Secret] = Secret.from_env_var(
"AZURE_OPENAI_AD_TOKEN", strict=False),
organization: Optional[str] = None,
streaming_callback: Optional[StreamingCallbackT] = None,
system_prompt: Optional[str] = None,
timeout: Optional[float] = None,
max_retries: Optional[int] = None,
http_client_kwargs: Optional[dict[str, Any]] = None,
generation_kwargs: Optional[dict[str, Any]] = None,
default_headers: Optional[dict[str, str]] = None,
*,
azure_ad_token_provider: Optional[AzureADTokenProvider] = None)
初始化 Azure OpenAI 生成器。
参数:
azure_endpoint:已部署模型的终结点,例如https://example-resource.azure.openai.com/.api_version:要使用的 API 版本。默认为 2023-05-15。azure_deployment:模型的部署,通常是模型名称。api_key:用于身份验证的 API 密钥。azure_ad_token:Azure Active Directory 令牌。organization:您的组织 ID,默认为None。如需帮助,请参阅 设置您的组织。streaming_callback:当从流中接收到新令牌时调用的回调函数。它接受 StreamingChunk 作为参数。system_prompt:用于文本生成的系统提示。如果未提供,生成器将省略系统提示并使用默认系统提示。timeout:AzureOpenAI 客户端的超时时间。如果未设置,则从OPENAI_TIMEOUT环境变量推断或设置为 30。max_retries:如果 AzureOpenAI 返回内部错误,则与 AzureOpenAI 建立联系的最大重试次数。如果未设置,则从OPENAI_MAX_RETRIES环境变量推断或设置为 5。http_client_kwargs:用于配置自定义的关键字参数字典httpx.Client或httpx.AsyncClient。有关更多信息,请参阅 HTTPX 文档。generation_kwargs:用于模型的其他参数,直接发送到 OpenAI 终结点。有关详细信息,请参阅 OpenAI 文档。一些支持的参数max_tokens:输出文本可以拥有的最大 token 数。temperature:要使用的采样温度。较高的值意味着模型承担更大的风险。对于更具创意的应用程序,请尝试 0.9,对于具有明确答案的应用程序,请尝试 0(argmax 采样)。top_p:一种替代温度采样的方法,称为核采样,模型会考虑具有 top_p 概率质量的令牌结果。例如,0.1 意味着只考虑组成前 10% 概率质量的令牌。n:为每个提示生成的完成数。例如,对于 3 个提示和 n=2,LLM 将为每个提示生成两个完成,总共生成 6 个完成。stop:LLM 应停止生成令牌的一个或多个序列。presence_penalty:如果令牌已存在,则应用的惩罚。值越高,模型重复该令牌的可能性越小。frequency_penalty:如果令牌已生成,则应用的惩罚。值越高,模型重复该令牌的可能性越小。logit_bias:向特定令牌添加 logit 偏差。字典的键是令牌,值是添加到该令牌的偏差。default_headers:用于 AzureOpenAI 客户端的默认头。azure_ad_token_provider:一个返回 Azure Active Directory 令牌的函数,将在每个请求上调用。
AzureOpenAIGenerator.to_dict
def to_dict() -> dict[str, Any]
将此组件序列化为字典。
返回值:
序列化后的组件(字典格式)。
AzureOpenAIGenerator.from_dict
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "AzureOpenAIGenerator"
从字典反序列化此组件。
参数:
data:此组件的字典表示。
返回值:
反序列化的组件实例。
AzureOpenAIGenerator.run
@component.output_types(replies=list[str], meta=list[dict[str, Any]])
def run(prompt: str,
system_prompt: Optional[str] = None,
streaming_callback: Optional[StreamingCallbackT] = None,
generation_kwargs: Optional[dict[str, Any]] = None)
根据提供的消息和生成参数调用文本生成推理。
参数:
prompt:用于文本生成的字符串提示。system_prompt:用于文本生成的系统提示。如果省略此运行时系统提示,则使用初始化时定义的系统提示(如果已定义)。streaming_callback: 当从流中接收到新 token 时调用的回调函数。generation_kwargs:用于文本生成的附加关键字参数。这些参数可能会覆盖在__init__方法。有关 OpenAI API 支持的参数的更多详细信息,请参阅 OpenAI 文档。
返回值:
包含生成的响应的字符串列表和包含每个响应元数据的字典列表。
模块 hugging_face_local
HuggingFaceLocalGenerator
使用在本地运行的 Hugging Face 模型生成文本。
在本地运行的 LLM 可能需要强大的硬件。
使用示例
from haystack.components.generators import HuggingFaceLocalGenerator
generator = HuggingFaceLocalGenerator(
model="google/flan-t5-large",
task="text2text-generation",
generation_kwargs={"max_new_tokens": 100, "temperature": 0.9})
generator.warm_up()
print(generator.run("Who is the best American actor?"))
# {'replies': ['John Cusack']}
HuggingFaceLocalGenerator.__init__
def __init__(model: str = "google/flan-t5-base",
task: Optional[Literal["text-generation",
"text2text-generation"]] = None,
device: Optional[ComponentDevice] = None,
token: Optional[Secret] = Secret.from_env_var(
["HF_API_TOKEN", "HF_TOKEN"], strict=False),
generation_kwargs: Optional[dict[str, Any]] = None,
huggingface_pipeline_kwargs: Optional[dict[str, Any]] = None,
stop_words: Optional[list[str]] = None,
streaming_callback: Optional[StreamingCallbackT] = None)
创建 HuggingFaceLocalGenerator 实例。
参数:
model:Hugging Face 文本生成模型名称或路径。task:Hugging Face 管道的任务。可能的选项text-generation:由解码器模型支持,例如 GPT。text2text-generation:由编码器-解码器模型支持,例如 T5。如果任务在huggingface_pipeline_kwargs中指定,则忽略此参数。如果未指定,则组件调用 Hugging Face API 以从模型名称推断任务。device:加载模型的设备。如果None,自动选择默认设备。如果设备或设备映射在huggingface_pipeline_kwargs中指定了设备/设备映射,它将覆盖此参数。token:用作远程文件的 HTTP bearer 授权令牌。如果令牌在huggingface_pipeline_kwargs中指定,则忽略此参数。generation_kwargs:一个字典,包含用于自定义文本生成的关键字参数。一些示例max_length,max_new_tokens,temperature,top_k,top_p。有关更多信息,请参阅 Hugging Face 文档- customize-text-generation
- transformers.GenerationConfig
huggingface_pipeline_kwargs:一个字典,包含用于初始化 Hugging Face 文本生成管道的关键字参数。这些关键字参数提供对 Hugging Face 管道的精细控制。如果重复,这些 kwargs 会覆盖model,task,device,和token初始化参数。有关可用 kwargs,请参阅 Hugging Face 文档。在此字典中,您还可以包含model_kwargs以指定模型初始化的 kwargs:transformers.PreTrainedModel.from_pretrainedstop_words:如果模型生成一个停止词,则生成停止。如果您提供此参数,请不要在generation_kwargs中指定stopping_criteria。对于某些聊天模型,输出包括新文本和原始提示。在这种情况下,请确保您的提示没有停止词。generation_kwargs。对于某些聊天模型,输出包括新文本和原始提示。在这种情况下,请确保您的提示没有停止词。streaming_callback:一个可选的可调用对象,用于处理流式响应。
HuggingFaceLocalGenerator.warm_up
def warm_up()
Initializes the component.
HuggingFaceLocalGenerator.to_dict
def to_dict() -> dict[str, Any]
将组件序列化为字典。
返回值:
包含序列化数据的字典。
HuggingFaceLocalGenerator.from_dict
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "HuggingFaceLocalGenerator"
从字典反序列化组件。
参数:
data: 要反序列化的字典。
返回值:
反序列化后的组件。
HuggingFaceLocalGenerator.run
@component.output_types(replies=list[str])
def run(prompt: str,
streaming_callback: Optional[StreamingCallbackT] = None,
generation_kwargs: Optional[dict[str, Any]] = None)
对给定提示运行文本生成模型。
参数:
prompt:表示提示的字符串。streaming_callback: 当从流中接收到新 token 时调用的回调函数。generation_kwargs:文本生成的附加关键字参数。
返回值:
包含生成的回复的字典。
- replies:表示生成的回复的字符串列表。
模块 hugging_face_api
HuggingFaceAPIGenerator
使用 Hugging Face API 生成文本。
与以下 Hugging Face API 一起使用
注意:截至 2025 年 7 月,Hugging Face 推理 API 不再通过text_generation 终结点提供生成模型。生成模型现在仅通过支持chat_completion 终结点的提供商提供。因此,此组件可能不再与 Hugging Face 推理 API 配合使用。请使用支持HuggingFaceAPIChatGenerator 组件。chat_completion 终结点。
使用示例
使用 Hugging Face 推理终结点
使用自托管文本生成推理
使用免费的无服务器推理 API
请注意,此示例可能无效,因为 Hugging Face 推理 API 不再提供支持text_generation 终结点的模型。请使用HuggingFaceAPIChatGenerator 用于通过chat_completion 终结点。
from haystack.components.generators import HuggingFaceAPIGenerator
from haystack.utils import Secret
generator = HuggingFaceAPIGenerator(api_type="inference_endpoints",
api_params={"url": "<your-inference-endpoint-url>"},
token=Secret.from_token("<your-api-key>"))
result = generator.run(prompt="What's Natural Language Processing?")
print(result)
from haystack.components.generators import HuggingFaceAPIGenerator
generator = HuggingFaceAPIGenerator(api_type="text_generation_inference",
api_params={"url": "https://:8080"})
result = generator.run(prompt="What's Natural Language Processing?")
print(result)
from haystack.components.generators import HuggingFaceAPIGenerator
from haystack.utils import Secret
generator = HuggingFaceAPIGenerator(api_type="serverless_inference_api",
api_params={"model": "HuggingFaceH4/zephyr-7b-beta"},
token=Secret.from_token("<your-api-key>"))
result = generator.run(prompt="What's Natural Language Processing?")
print(result)
HuggingFaceAPIGenerator.__init__
def __init__(api_type: Union[HFGenerationAPIType, str],
api_params: dict[str, str],
token: Optional[Secret] = Secret.from_env_var(
["HF_API_TOKEN", "HF_TOKEN"], strict=False),
generation_kwargs: Optional[dict[str, Any]] = None,
stop_words: Optional[list[str]] = None,
streaming_callback: Optional[StreamingCallbackT] = None)
初始化 HuggingFaceAPIGenerator 实例。
参数:
api_type:要使用的 Hugging Face API 类型。可用类型text_generation_inference:请参阅 TGI。inference_endpoints:请参阅 推理终结点。serverless_inference_api:请参阅 无服务器推理 API。由于 Hugging Face 推理 API 中提供的模型发生变化,这可能不再有效。请改用HuggingFaceAPIChatGenerator组件。api_params:包含以下键的字典model: Hugging Face 模型 ID。当api_type是SERVERLESS_INFERENCE_API.url: 推理终结点的 URL。当api_type是INFERENCE_ENDPOINTS或TEXT_GENERATION_INFERENCE.- 特定于所选 API 类型的其他参数,例如
timeout,headers,provider等。 token: 用于作为 HTTP bearer 授权的 Hugging Face 令牌。请在您的 账户设置 中查看您的 HF 令牌。generation_kwargs:一个字典,包含用于自定义文本生成的关键字参数。一些示例max_new_tokens,temperature,top_k,top_p。有关详细信息,请参阅 Hugging Face 文档。stop_words:一个可选的字符串列表,表示停止词。streaming_callback:一个可选的可调用对象,用于处理流式响应。
HuggingFaceAPIGenerator.to_dict
def to_dict() -> dict[str, Any]
将此组件序列化为字典。
返回值:
包含序列化组件的字典。
HuggingFaceAPIGenerator.from_dict
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "HuggingFaceAPIGenerator"
从字典反序列化此组件。
HuggingFaceAPIGenerator.run
@component.output_types(replies=list[str], meta=list[dict[str, Any]])
def run(prompt: str,
streaming_callback: Optional[StreamingCallbackT] = None,
generation_kwargs: Optional[dict[str, Any]] = None)
调用给定提示和生成参数的文本生成推理。
参数:
prompt:表示提示的字符串。streaming_callback: 当从流中接收到新 token 时调用的回调函数。generation_kwargs:文本生成的附加关键字参数。
返回值:
包含生成的回复和元数据的字典。两者都是长度为 n 的列表。
- replies:表示生成的回复的字符串列表。
模块 openai
OpenAIGenerator
使用 OpenAI 的大型语言模型 (LLM) 生成文本。
它与 gpt-4 和 o-系列模型配合使用,并支持从 OpenAI API 传输响应。它使用字符串作为输入和输出。
您可以通过将参数传递给 OpenAI API 来定制文本的生成方式。使用**generation_kwargs 参数在初始化组件或运行它时。任何适用于openai.ChatCompletion.create 的参数也适用于此处。
有关 OpenAI API 参数的详细信息,请参阅 OpenAI 文档。
使用示例
from haystack.components.generators import OpenAIGenerator
client = OpenAIGenerator()
response = client.run("What's Natural Language Processing? Be brief.")
print(response)
>> {'replies': ['Natural Language Processing (NLP) is a branch of artificial intelligence that focuses on
>> the interaction between computers and human language. It involves enabling computers to understand, interpret,
>> and respond to natural human language in a way that is both meaningful and useful.'], 'meta': [{'model':
>> 'gpt-4o-mini', 'index': 0, 'finish_reason': 'stop', 'usage': {'prompt_tokens': 16,
>> 'completion_tokens': 49, 'total_tokens': 65}}]}
OpenAIGenerator.__init__
def __init__(api_key: Secret = Secret.from_env_var("OPENAI_API_KEY"),
model: str = "gpt-4o-mini",
streaming_callback: Optional[StreamingCallbackT] = None,
api_base_url: Optional[str] = None,
organization: Optional[str] = None,
system_prompt: Optional[str] = None,
generation_kwargs: Optional[dict[str, Any]] = None,
timeout: Optional[float] = None,
max_retries: Optional[int] = None,
http_client_kwargs: Optional[dict[str, Any]] = None)
创建 OpenAIGenerator 实例。除非在model 中另有指定,否则使用 OpenAI 的 gpt-4o-mini
通过设置“OPENAI_TIMEOUT”和“OPENAI_MAX_RETRIES”,您可以更改 OpenAI 客户端中的超时和 max_retries 参数。
参数:
api_key:连接到 OpenAI 的 OpenAI API 密钥。model: 要使用的模型名称。streaming_callback: 当从流中接收到新 token 时调用的回调函数。回调函数接受 StreamingChunk 作为参数。api_base_url:一个可选的基本 URL。organization:组织 ID,默认为None.system_prompt:用于文本生成的系统提示。如果未提供,则省略系统提示,并使用模型的默认系统提示。generation_kwargs:用于模型的其他参数。这些参数直接发送到 OpenAI 终结点。有关详细信息,请参阅 OpenAI 文档。一些支持的参数max_tokens:输出文本可以拥有的最大 token 数。temperature:要使用的采样温度。值越高,模型承担的风险越大。对于更具创造性的应用,请尝试 0.9,对于有明确答案的应用,请尝试 0(argmax 采样)。top_p:一种替代温度采样的方法,称为核采样,模型会考虑具有 top_p 概率质量的令牌结果。因此,0.1 意味着只考虑组成前 10% 概率质量的令牌。n:为每个提示生成的完成数。例如,如果 LLM 获得 3 个提示且 n 为 2,它将为每个提示生成两个完成,最终总共生成 6 个完成。stop:LLM 应停止生成令牌的一个或多个序列。presence_penalty:如果令牌已完全存在,则应用的惩罚。值越大,模型在文本中重复相同令牌的可能性越小。frequency_penalty:如果文本中已生成令牌,则应用的惩罚。值越大,模型在文本中重复相同令牌的可能性越小。logit_bias:向特定令牌添加 logit 偏差。字典的键是令牌,值是添加到该令牌的偏差。timeout:OpenAI 客户端调用的超时时间,如果未设置,则从OPENAI_TIMEOUT环境变量推断或设置为 30。max_retries:如果 OpenAI 返回内部错误,则与 OpenAI 建立联系的最大重试次数,如果未设置,则从OPENAI_MAX_RETRIES环境变量推断或设置为 5。http_client_kwargs:用于配置自定义的关键字参数字典httpx.Client或httpx.AsyncClient。有关更多信息,请参阅 HTTPX 文档。
OpenAIGenerator.to_dict
def to_dict() -> dict[str, Any]
将此组件序列化为字典。
返回值:
序列化后的组件(字典格式)。
OpenAIGenerator.from_dict
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "OpenAIGenerator"
从字典反序列化此组件。
参数:
data:此组件的字典表示。
返回值:
反序列化的组件实例。
OpenAIGenerator.run
@component.output_types(replies=list[str], meta=list[dict[str, Any]])
def run(prompt: str,
system_prompt: Optional[str] = None,
streaming_callback: Optional[StreamingCallbackT] = None,
generation_kwargs: Optional[dict[str, Any]] = None)
根据提供的消息和生成参数调用文本生成推理。
参数:
prompt:用于文本生成的字符串提示。system_prompt:用于文本生成的系统提示。如果省略此运行时系统提示,则使用初始化时定义的系统提示(如果已定义)。streaming_callback: 当从流中接收到新 token 时调用的回调函数。generation_kwargs:用于文本生成的附加关键字参数。这些参数可能会覆盖在__init__方法。有关 OpenAI API 支持的参数的更多详细信息,请参阅 OpenAI 文档。
返回值:
包含生成的响应的字符串列表和包含每个响应元数据的字典列表。
模块 openai_dalle
DALLEImageGenerator
使用 OpenAI 的 DALL-E 模型生成图像。
有关 OpenAI API 参数的详细信息,请参阅 OpenAI 文档。
使用示例
from haystack.components.generators import DALLEImageGenerator
image_generator = DALLEImageGenerator()
response = image_generator.run("Show me a picture of a black cat.")
print(response)
DALLEImageGenerator.__init__
def __init__(model: str = "dall-e-3",
quality: Literal["standard", "hd"] = "standard",
size: Literal["256x256", "512x512", "1024x1024", "1792x1024",
"1024x1792"] = "1024x1024",
response_format: Literal["url", "b64_json"] = "url",
api_key: Secret = Secret.from_env_var("OPENAI_API_KEY"),
api_base_url: Optional[str] = None,
organization: Optional[str] = None,
timeout: Optional[float] = None,
max_retries: Optional[int] = None,
http_client_kwargs: Optional[dict[str, Any]] = None)
创建 DALLEImageGenerator 实例。除非在model 中另有指定,否则使用 OpenAI 的 dall-e-3。
参数:
model:用于图像生成的模型。可以是“dall-e-2”或“dall-e-3”。quality:生成图像的质量。可以是“standard”或“hd”。size:生成图像的大小。对于 dall-e-2,必须是 256x256、512x512 或 1024x1024 之一。对于 dall-e-3 模型,必须是 1024x1024、1792x1024 或 1024x1792 之一。response_format:响应的格式。可以是“url”或“b64_json”。api_key:连接到 OpenAI 的 OpenAI API 密钥。api_base_url:一个可选的基本 URL。organization:组织 ID,默认为None.timeout:OpenAI 客户端调用的超时时间。如果未设置,则从OPENAI_TIMEOUT环境变量推断或设置为 30。max_retries:如果 OpenAI 返回内部错误,则与 OpenAI 建立联系的最大重试次数。如果未设置,则从OPENAI_MAX_RETRIES环境变量推断或设置为 5。http_client_kwargs:用于配置自定义的关键字参数字典httpx.Client或httpx.AsyncClient。有关更多信息,请参阅 HTTPX 文档。
DALLEImageGenerator.warm_up
def warm_up() -> None
预热 OpenAI 客户端。
DALLEImageGenerator.run
@component.output_types(images=list[str], revised_prompt=str)
def run(prompt: str,
size: Optional[Literal["256x256", "512x512", "1024x1024", "1792x1024",
"1024x1792"]] = None,
quality: Optional[Literal["standard", "hd"]] = None,
response_format: Optional[Optional[Literal["url",
"b64_json"]]] = None)
根据提供的提示和生成参数调用图像生成推理。
参数:
prompt:生成图像的提示。size:如果提供,则覆盖初始化时提供的大小。quality:如果提供,则覆盖初始化时提供的质量。response_format:如果提供,则覆盖初始化时提供的响应格式。
返回值:
包含生成的图像列表和修订提示的字典。根据response_format 参数,图像列表可以是 URL 或 Base64 编码的 JSON 字符串。修订提示是用于生成图像的提示,如果 OpenAI 对提示进行了任何修订。
DALLEImageGenerator.to_dict
def to_dict() -> dict[str, Any]
将此组件序列化为字典。
返回值:
序列化后的组件(字典格式)。
DALLEImageGenerator.from_dict
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "DALLEImageGenerator"
从字典反序列化此组件。
参数:
data:此组件的字典表示。
返回值:
反序列化的组件实例。
模块 chat/azure
AzureOpenAIChatGenerator
使用 Azure 上的 OpenAI 模型生成文本。
它适用于 gpt-4 类型模型,并支持从 OpenAI API 传输响应。它使用 ChatMessage 格式进行输入和输出。
您可以通过将参数传递给 OpenAI API 来定制文本的生成方式。使用**generation_kwargs 参数在初始化组件或运行它时。任何适用于openai.ChatCompletion.create 的参数也适用于此处。
有关 OpenAI API 参数的详细信息,请参阅 OpenAI 文档。
使用示例
from haystack.components.generators.chat import AzureOpenAIChatGenerator
from haystack.dataclasses import ChatMessage
from haystack.utils import Secret
messages = [ChatMessage.from_user("What's Natural Language Processing?")]
client = AzureOpenAIChatGenerator(
azure_endpoint="<Your Azure endpoint e.g. `https://your-company.azure.openai.com/>",
api_key=Secret.from_token("<your-api-key>"),
azure_deployment="<this a model name, e.g. gpt-4o-mini>")
response = client.run(messages)
print(response)
{'replies':
[ChatMessage(_role=<ChatRole.ASSISTANT: 'assistant'>, _content=[TextContent(text=
"Natural Language Processing (NLP) is a branch of artificial intelligence that focuses on
enabling computers to understand, interpret, and generate human language in a way that is useful.")],
_name=None,
_meta={'model': 'gpt-4o-mini', 'index': 0, 'finish_reason': 'stop',
'usage': {'prompt_tokens': 15, 'completion_tokens': 36, 'total_tokens': 51}})]
}
AzureOpenAIChatGenerator.__init__
def __init__(azure_endpoint: Optional[str] = None,
api_version: Optional[str] = "2023-05-15",
azure_deployment: Optional[str] = "gpt-4o-mini",
api_key: Optional[Secret] = Secret.from_env_var(
"AZURE_OPENAI_API_KEY", strict=False),
azure_ad_token: Optional[Secret] = Secret.from_env_var(
"AZURE_OPENAI_AD_TOKEN", strict=False),
organization: Optional[str] = None,
streaming_callback: Optional[StreamingCallbackT] = None,
timeout: Optional[float] = None,
max_retries: Optional[int] = None,
generation_kwargs: Optional[dict[str, Any]] = None,
default_headers: Optional[dict[str, str]] = None,
tools: Optional[Union[list[Tool], Toolset]] = None,
tools_strict: bool = False,
*,
azure_ad_token_provider: Optional[Union[
AzureADTokenProvider, AsyncAzureADTokenProvider]] = None,
http_client_kwargs: Optional[dict[str, Any]] = None)
初始化 Azure OpenAI 聊天生成器组件。
参数:
azure_endpoint:已部署模型的终结点,例如"https://example-resource.azure.openai.com/".api_version:要使用的 API 版本。默认为 2023-05-15。azure_deployment:模型的部署,通常是模型名称。api_key:用于身份验证的 API 密钥。azure_ad_token:Azure Active Directory 令牌。organization:您的组织 ID,默认为None。如需帮助,请参阅 设置您的组织。streaming_callback:当从流中接收到新令牌时调用的回调函数。它接受 StreamingChunk 作为参数。timeout:OpenAI 客户端调用的超时时间。如果未设置,则默认为OPENAI_TIMEOUT环境变量,或 30 秒。max_retries: 在发生内部错误后联系 OpenAI 的最大重试次数。如果未设置,则默认为OPENAI_MAX_RETRIES环境变量,或设置为 5。generation_kwargs:用于模型的其他参数。这些参数直接发送到 OpenAI 终结点。有关详细信息,请参阅 OpenAI 文档。一些支持的参数max_tokens:输出文本可以拥有的最大 token 数。temperature:要使用的采样温度。较高的值意味着模型承担更大的风险。对于更具创意的应用程序,请尝试 0.9,对于具有明确答案的应用程序,请尝试 0(argmax 采样)。top_p:核采样是温度采样的一种替代方法,模型会考虑具有 top_p 概率质量的令牌。例如,0.1 意味着只考虑组成前 10% 概率质量的令牌。n:为每个提示生成的完成数。例如,对于 3 个提示和 n=2,LLM 将为每个提示生成两个完成,总共生成 6 个完成。stop:LLM 应停止生成令牌的一个或多个序列。presence_penalty:如果令牌已存在,则应用的惩罚。值越高,模型重复该令牌的可能性越小。frequency_penalty:如果令牌已生成,则应用的惩罚。值越高,模型重复该令牌的可能性越小。logit_bias:向特定令牌添加 logit 偏差。字典的键是令牌,值是添加到该令牌的偏差。response_format:一个 JSON Schema 或 Pydantic 模型,用于强制模型的响应结构。如果提供,输出将始终根据此格式进行验证(除非模型返回工具调用)。有关详细信息,请参阅 OpenAI 结构化输出文档。注意- 此参数接受 Pydantic 模型和 JSON Schema,适用于 GPT-4o 及更高版本的最新模型。旧模型仅通过
{"type": "json_object"}支持结构化输出的基本版本。有关 JSON 模式的详细信息,请参阅 OpenAI 结构化输出文档。 - 对于带有流的结构化输出,
response_format必须是 JSON Schema,而不是 Pydantic 模型。
- 此参数接受 Pydantic 模型和 JSON Schema,适用于 GPT-4o 及更高版本的最新模型。旧模型仅通过
default_headers:用于 AzureOpenAI 客户端的默认头。tools: 一个工具列表或 Toolset,模型可以为此准备调用。此参数可以接受一个Tool对象列表或一个Toolset实例。tools_strict:是否启用对工具调用的严格模式遵循。如果设置为True,模型将严格遵循工具定义中的parameters字段,但这可能会增加延迟。azure_ad_token_provider:一个返回 Azure Active Directory 令牌的函数,将在每个请求上调用。http_client_kwargs:用于配置自定义的关键字参数字典httpx.Client或httpx.AsyncClient。有关更多信息,请参阅 HTTPX 文档。
AzureOpenAIChatGenerator.to_dict
def to_dict() -> dict[str, Any]
将此组件序列化为字典。
返回值:
序列化后的组件(字典格式)。
AzureOpenAIChatGenerator.from_dict
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "AzureOpenAIChatGenerator"
从字典反序列化此组件。
参数:
data:此组件的字典表示。
返回值:
反序列化的组件实例。
AzureOpenAIChatGenerator.run
@component.output_types(replies=list[ChatMessage])
def run(messages: list[ChatMessage],
streaming_callback: Optional[StreamingCallbackT] = None,
generation_kwargs: Optional[dict[str, Any]] = None,
*,
tools: Optional[Union[list[Tool], Toolset]] = None,
tools_strict: Optional[bool] = None)
根据提供的消息和生成参数调用聊天完成。
参数:
messages: 一个 ChatMessage 实例列表,表示输入消息。streaming_callback: 当从流中接收到新 token 时调用的回调函数。generation_kwargs:文本生成的附加关键字参数。这些参数将覆盖组件初始化期间传递的参数。有关 OpenAI API 参数的详细信息,请参阅 OpenAI 文档。tools: 一个工具列表或 Toolset,模型可以为此准备调用。如果设置,它将覆盖tools参数在组件初始化期间设置。此参数可以接受列表或Tool对象列表或一个Toolset实例。tools_strict:是否启用对工具调用的严格模式遵循。如果设置为True,模型将严格遵循工具定义中的parameters字段,但这可能会增加延迟。如果设置,它将覆盖在组件初始化期间设置的tools_strict参数。
返回值:
一个字典,其中包含以下键
replies:包含生成的响应作为 ChatMessage 实例的列表。
AzureOpenAIChatGenerator.run_async
@component.output_types(replies=list[ChatMessage])
async def run_async(messages: list[ChatMessage],
streaming_callback: Optional[StreamingCallbackT] = None,
generation_kwargs: Optional[dict[str, Any]] = None,
*,
tools: Optional[Union[list[Tool], Toolset]] = None,
tools_strict: Optional[bool] = None)
根据提供的消息和生成参数异步调用聊天完成。
这是run 方法。它具有相同的参数和返回值,但可以在异步代码中与await 一起使用。
参数:
messages: 一个 ChatMessage 实例列表,表示输入消息。streaming_callback:当从流中接收到新令牌时调用的回调函数。必须是协程。generation_kwargs:文本生成的附加关键字参数。这些参数将覆盖组件初始化期间传递的参数。有关 OpenAI API 参数的详细信息,请参阅 OpenAI 文档。tools: 一个工具列表或 Toolset,模型可以为此准备调用。如果设置,它将覆盖tools参数在组件初始化期间设置。此参数可以接受列表或Tool对象列表或一个Toolset实例。tools_strict:是否启用对工具调用的严格模式遵循。如果设置为True,模型将严格遵循工具定义中的parameters字段,但这可能会增加延迟。如果设置,它将覆盖在组件初始化期间设置的tools_strict参数。
返回值:
一个字典,其中包含以下键
replies:包含生成的响应作为 ChatMessage 实例的列表。
模块 chat/hugging_face_local
default_tool_parser
def default_tool_parser(text: str) -> Optional[list[ToolCall]]
解析模型输出文本中的工具调用的默认实现。
使用 DEFAULT_TOOL_PATTERN 提取工具调用。
参数:
text:用于解析工具调用的文本。
返回值:
如果找到有效的工具调用,则包含单个 ToolCall 的列表,否则为 None。
HuggingFaceLocalChatGenerator
使用在本地运行的 Hugging Face 模型生成聊天响应。
将此组件与基于聊天的模型一起使用,例如HuggingFaceH4/zephyr-7b-beta 或meta-llama/Llama-2-7b-chat-hf。在本地运行的 LLM 可能需要强大的硬件。
使用示例
from haystack.components.generators.chat import HuggingFaceLocalChatGenerator
from haystack.dataclasses import ChatMessage
generator = HuggingFaceLocalChatGenerator(model="HuggingFaceH4/zephyr-7b-beta")
generator.warm_up()
messages = [ChatMessage.from_user("What's Natural Language Processing? Be brief.")]
print(generator.run(messages))
{'replies':
[ChatMessage(_role=<ChatRole.ASSISTANT: 'assistant'>, _content=[TextContent(text=
"Natural Language Processing (NLP) is a subfield of artificial intelligence that deals
with the interaction between computers and human language. It enables computers to understand, interpret, and
generate human language in a valuable way. NLP involves various techniques such as speech recognition, text
analysis, sentiment analysis, and machine translation. The ultimate goal is to make it easier for computers to
process and derive meaning from human language, improving communication between humans and machines.")],
_name=None,
_meta={'finish_reason': 'stop', 'index': 0, 'model':
'mistralai/Mistral-7B-Instruct-v0.2',
'usage': {'completion_tokens': 90, 'prompt_tokens': 19, 'total_tokens': 109}})
]
}
HuggingFaceLocalChatGenerator.__init__
def __init__(model: str = "HuggingFaceH4/zephyr-7b-beta",
task: Optional[Literal["text-generation",
"text2text-generation"]] = None,
device: Optional[ComponentDevice] = None,
token: Optional[Secret] = Secret.from_env_var(
["HF_API_TOKEN", "HF_TOKEN"], strict=False),
chat_template: Optional[str] = None,
generation_kwargs: Optional[dict[str, Any]] = None,
huggingface_pipeline_kwargs: Optional[dict[str, Any]] = None,
stop_words: Optional[list[str]] = None,
streaming_callback: Optional[StreamingCallbackT] = None,
tools: Optional[Union[list[Tool], Toolset]] = None,
tool_parsing_function: Optional[Callable[
[str], Optional[list[ToolCall]]]] = None,
async_executor: Optional[ThreadPoolExecutor] = None) -> None
初始化 HuggingFaceLocalChatGenerator 组件。
参数:
model:Hugging Face 文本生成模型名称或路径,例如mistralai/Mistral-7B-Instruct-v0.2或TheBloke/OpenHermes-2.5-Mistral-7B-16k-AWQ。模型必须是支持 ChatML 消息格式的聊天模型。如果模型在huggingface_pipeline_kwargs中指定,则忽略此参数。task:Hugging Face 管道的任务。可能的选项text-generation:由解码器模型支持,例如 GPT。text2text-generation:由编码器-解码器模型支持,例如 T5。如果任务在huggingface_pipeline_kwargs中指定,则忽略此参数。如果未指定,则组件调用 Hugging Face API 以从模型名称推断任务。device:加载模型的设备。如果None,自动选择默认设备。如果设备或设备映射在huggingface_pipeline_kwargs中指定了设备/设备映射,它将覆盖此参数。token:用作远程文件的 HTTP bearer 授权令牌。如果令牌在huggingface_pipeline_kwargs中指定,则忽略此参数。chat_template:指定用于格式化聊天消息的可选 Jinja 模板。大多数高质量聊天模型都有自己的模板,但对于没有此功能的模型或如果您喜欢自定义模板,请使用此参数。generation_kwargs:一个字典,包含用于自定义文本生成的关键字参数。一些示例max_length,max_new_tokens,temperature,top_k,top_p。有关更多信息,请参阅 Hugging Face 文档-
- GenerationConfig 唯一
generation_kwargs默认设置为max_new_tokens,设置为 512 个令牌。
- GenerationConfig 唯一
huggingface_pipeline_kwargs:一个字典,包含用于初始化 Hugging Face 文本生成管道的关键字参数。这些关键字参数提供对 Hugging Face 管道的精细控制。如果重复,这些 kwargs 会覆盖model,task,device,和token初始化参数。有关 kwargs,请参阅 Hugging Face 文档。在此字典中,您还可以包含model_kwargs以指定 模型初始化 的 kwargs。stop_words:停止词列表。如果模型生成停止词,则生成停止。如果您提供此参数,请不要指定generation_kwargs中指定stopping_criteria。对于某些聊天模型,输出包括新文本和原始提示。在这种情况下,请确保您的提示没有停止词。generation_kwargs。对于某些聊天模型,输出包括新文本和原始提示。在这种情况下,请确保您的提示没有停止词。streaming_callback:一个可选的可调用对象,用于处理流式响应。tools: 一个工具列表或 Toolset,模型可以为此准备调用。此参数可以接受一个Tool对象列表或一个Toolset实例。tool_parsing_function:一个可调用对象,它接受字符串并返回 ToolCall 对象列表或 None。如果为 None,则将使用 default_tool_parser,它使用预定义模式提取工具调用。async_executor:用于异步调用的可选 ThreadPoolExecutor。如果未提供,将初始化并使用单线程执行器。
HuggingFaceLocalChatGenerator.__del__
def __del__() -> None
实例销毁时的清理。
HuggingFaceLocalChatGenerator.shutdown
def shutdown() -> None
如果拥有执行器,则显式关闭它。
HuggingFaceLocalChatGenerator.warm_up
def warm_up() -> None
Initializes the component.
HuggingFaceLocalChatGenerator.to_dict
def to_dict() -> dict[str, Any]
将组件序列化为字典。
返回值:
包含序列化数据的字典。
HuggingFaceLocalChatGenerator.from_dict
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "HuggingFaceLocalChatGenerator"
从字典反序列化组件。
参数:
data: 要反序列化的字典。
返回值:
反序列化后的组件。
HuggingFaceLocalChatGenerator.run
@component.output_types(replies=list[ChatMessage])
def run(
messages: list[ChatMessage],
generation_kwargs: Optional[dict[str, Any]] = None,
streaming_callback: Optional[StreamingCallbackT] = None,
tools: Optional[Union[list[Tool], Toolset]] = None
) -> dict[str, list[ChatMessage]]
根据提供的消息和生成参数调用文本生成推理。
参数:
messages:表示输入消息的 ChatMessage 对象列表。generation_kwargs:文本生成的附加关键字参数。streaming_callback:一个可选的可调用对象,用于处理流式响应。tools: 一个工具列表或 Toolset,模型可以为此准备调用。如果设置,它将覆盖tools参数在初始化期间提供。此参数可以接受列表或Tool对象列表或一个Toolset实例。
返回值:
包含以下键的字典
replies:包含生成的响应作为 ChatMessage 实例的列表。
HuggingFaceLocalChatGenerator.create_message
def create_message(text: str,
index: int,
tokenizer: Union["PreTrainedTokenizer",
"PreTrainedTokenizerFast"],
prompt: str,
generation_kwargs: dict[str, Any],
parse_tool_calls: bool = False) -> ChatMessage
从提供的文本创建 ChatMessage 实例,并填充元数据。
参数:
text:生成的文本。index:生成文本的索引。tokenizer:用于生成的 tokenizer。prompt:用于生成的提示。generation_kwargs:生成参数。parse_tool_calls:是否尝试从文本中解析工具调用。
返回值:
一个 ChatMessage 实例。
HuggingFaceLocalChatGenerator.run_async
@component.output_types(replies=list[ChatMessage])
async def run_async(
messages: list[ChatMessage],
generation_kwargs: Optional[dict[str, Any]] = None,
streaming_callback: Optional[StreamingCallbackT] = None,
tools: Optional[Union[list[Tool], Toolset]] = None
) -> dict[str, list[ChatMessage]]
根据提供的消息和生成参数异步调用文本生成推理。
这是run 方法。它具有相同的参数和返回值,但可以在异步代码中与await 在异步代码中。
参数:
messages:表示输入消息的 ChatMessage 对象列表。generation_kwargs:文本生成的附加关键字参数。streaming_callback:一个可选的可调用对象,用于处理流式响应。tools: 一个工具列表或 Toolset,模型可以为此准备调用。此参数可以接受一个Tool对象列表或一个Toolset实例。
返回值:
包含以下键的字典
replies:包含生成的响应作为 ChatMessage 实例的列表。
模块 chat/hugging_face_api
HuggingFaceAPIChatGenerator
使用 Hugging Face API 完成聊天。
HuggingFaceAPIChatGenerator 使用 ChatMessage 格式进行输入和输出。使用它通过 Hugging Face API 生成文本
使用示例
使用无服务器推理 API(推理提供商)- 提供免费套餐
from haystack.components.generators.chat import HuggingFaceAPIChatGenerator
from haystack.dataclasses import ChatMessage
from haystack.utils import Secret
from haystack.utils.hf import HFGenerationAPIType
messages = [ChatMessage.from_system("\nYou are a helpful, respectful and honest assistant"),
ChatMessage.from_user("What's Natural Language Processing?")]
# the api_type can be expressed using the HFGenerationAPIType enum or as a string
api_type = HFGenerationAPIType.SERVERLESS_INFERENCE_API
api_type = "serverless_inference_api" # this is equivalent to the above
generator = HuggingFaceAPIChatGenerator(api_type=api_type,
api_params={"model": "Qwen/Qwen2.5-7B-Instruct",
"provider": "together"},
token=Secret.from_token("<your-api-key>"))
result = generator.run(messages)
print(result)
使用无服务器推理 API(推理提供商)和文本+图像输入
from haystack.components.generators.chat import HuggingFaceAPIChatGenerator
from haystack.dataclasses import ChatMessage, ImageContent
from haystack.utils import Secret
from haystack.utils.hf import HFGenerationAPIType
# Create an image from file path, URL, or base64
image = ImageContent.from_file_path("path/to/your/image.jpg")
# Create a multimodal message with both text and image
messages = [ChatMessage.from_user(content_parts=["Describe this image in detail", image])]
generator = HuggingFaceAPIChatGenerator(
api_type=HFGenerationAPIType.SERVERLESS_INFERENCE_API,
api_params={
"model": "Qwen/Qwen2.5-VL-7B-Instruct", # Vision Language Model
"provider": "hyperbolic"
},
token=Secret.from_token("<your-api-key>")
)
result = generator.run(messages)
print(result)
使用付费推理终结点
from haystack.components.generators.chat import HuggingFaceAPIChatGenerator
from haystack.dataclasses import ChatMessage
from haystack.utils import Secret
messages = [ChatMessage.from_system("\nYou are a helpful, respectful and honest assistant"),
ChatMessage.from_user("What's Natural Language Processing?")]
generator = HuggingFaceAPIChatGenerator(api_type="inference_endpoints",
api_params={"url": "<your-inference-endpoint-url>"},
token=Secret.from_token("<your-api-key>"))
result = generator.run(messages)
print(result)
#### With self-hosted text generation inference
```python
from haystack.components.generators.chat import HuggingFaceAPIChatGenerator
from haystack.dataclasses import ChatMessage
messages = [ChatMessage.from_system("\nYou are a helpful, respectful and honest assistant"),
ChatMessage.from_user("What's Natural Language Processing?")]
generator = HuggingFaceAPIChatGenerator(api_type="text_generation_inference",
api_params={"url": "https://:8080"})
result = generator.run(messages)
print(result)
HuggingFaceAPIChatGenerator.__init__
def __init__(api_type: Union[HFGenerationAPIType, str],
api_params: dict[str, str],
token: Optional[Secret] = Secret.from_env_var(
["HF_API_TOKEN", "HF_TOKEN"], strict=False),
generation_kwargs: Optional[dict[str, Any]] = None,
stop_words: Optional[list[str]] = None,
streaming_callback: Optional[StreamingCallbackT] = None,
tools: Optional[Union[list[Tool], Toolset]] = None)
初始化 HuggingFaceAPIChatGenerator 实例。
参数:
api_type:要使用的 Hugging Face API 类型。可用类型text_generation_inference:请参阅 TGI。inference_endpoints:请参阅 推理终结点。serverless_inference_api:请参阅 无服务器推理 API - 推理提供商。api_params:包含以下键的字典model: Hugging Face 模型 ID。当api_type是SERVERLESS_INFERENCE_API.provider:提供商名称。建议在api_type是SERVERLESS_INFERENCE_API.url: 推理终结点的 URL。当api_type是INFERENCE_ENDPOINTS或TEXT_GENERATION_INFERENCE.- 特定于所选 API 类型的其他参数,例如
timeout,headers等。 token: 用于作为 HTTP bearer 授权的 Hugging Face 令牌。请在您的 账户设置 中查看您的 HF 令牌。generation_kwargs:一个字典,包含用于自定义文本生成的关键字参数。一些示例max_tokens,temperature,top_p。有关详细信息,请参阅 Hugging Face chat_completion 文档。stop_words:一个可选的字符串列表,表示停止词。streaming_callback:一个可选的可调用对象,用于处理流式响应。tools:模型可以准备调用的工具列表或工具集。所选模型应根据模型卡支持工具/函数调用。Hugging Face API 和 TGI 中对工具的支持尚未完全完善,您可能会遇到意外行为。此参数可以接受列表或Tool对象列表或一个Toolset实例。
HuggingFaceAPIChatGenerator.to_dict
def to_dict() -> dict[str, Any]
将此组件序列化为字典。
返回值:
包含序列化组件的字典。
HuggingFaceAPIChatGenerator.from_dict
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "HuggingFaceAPIChatGenerator"
从字典反序列化此组件。
HuggingFaceAPIChatGenerator.run
@component.output_types(replies=list[ChatMessage])
def run(messages: list[ChatMessage],
generation_kwargs: Optional[dict[str, Any]] = None,
tools: Optional[Union[list[Tool], Toolset]] = None,
streaming_callback: Optional[StreamingCallbackT] = None)
根据提供的消息和生成参数调用文本生成推理。
参数:
messages:表示输入消息的 ChatMessage 对象列表。generation_kwargs:文本生成的附加关键字参数。tools: 一个工具列表或 Toolset,模型可以为此准备调用。如果设置,它将覆盖tools参数在组件初始化期间设置。此参数可以接受列表或Tool对象列表或一个Toolset实例。streaming_callback:用于处理流式响应的可选可调用对象。如果设置,它将覆盖在组件初始化期间设置的streaming_callback参数。
返回值:
包含以下键的字典
replies:包含生成的响应作为 ChatMessage 对象的列表。
HuggingFaceAPIChatGenerator.run_async
@component.output_types(replies=list[ChatMessage])
async def run_async(messages: list[ChatMessage],
generation_kwargs: Optional[dict[str, Any]] = None,
tools: Optional[Union[list[Tool], Toolset]] = None,
streaming_callback: Optional[StreamingCallbackT] = None)
根据提供的消息和生成参数异步调用文本生成推理。
这是run 方法。它具有相同的参数和返回值,但可以在异步代码中与await 在异步代码中。
参数:
messages:表示输入消息的 ChatMessage 对象列表。generation_kwargs:文本生成的附加关键字参数。tools: 一个工具列表或 Toolset,模型可以为此准备调用。如果设置,它将覆盖tools参数在组件初始化期间设置。此参数可以接受列表或Tool对象列表或一个Toolset实例。streaming_callback:用于处理流式响应的可选可调用对象。如果设置,它将覆盖在组件初始化期间设置的streaming_callback参数。
返回值:
包含以下键的字典
replies:包含生成的响应作为 ChatMessage 对象的列表。
模块 chat/openai
OpenAIChatGenerator
使用 OpenAI 的大型语言模型 (LLM) 完成聊天。
它与 gpt-4 和 o-系列模型配合使用,并支持从 OpenAI API 传输响应。它使用 ChatMessage 格式进行输入和输出。
您可以通过将参数传递给 OpenAI API 来定制文本的生成方式。使用**generation_kwargs 参数在初始化组件或运行它时。任何适用于openai.ChatCompletion.create 的参数也适用于此处。
有关 OpenAI API 参数的详细信息,请参阅 OpenAI 文档。
使用示例
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.dataclasses import ChatMessage
messages = [ChatMessage.from_user("What's Natural Language Processing?")]
client = OpenAIChatGenerator()
response = client.run(messages)
print(response)
输出
{'replies':
[ChatMessage(_role=<ChatRole.ASSISTANT: 'assistant'>, _content=
[TextContent(text="Natural Language Processing (NLP) is a branch of artificial intelligence
that focuses on enabling computers to understand, interpret, and generate human language in
a way that is meaningful and useful.")],
_name=None,
_meta={'model': 'gpt-4o-mini', 'index': 0, 'finish_reason': 'stop',
'usage': {'prompt_tokens': 15, 'completion_tokens': 36, 'total_tokens': 51}})
]
}
OpenAIChatGenerator.__init__
def __init__(api_key: Secret = Secret.from_env_var("OPENAI_API_KEY"),
model: str = "gpt-4o-mini",
streaming_callback: Optional[StreamingCallbackT] = None,
api_base_url: Optional[str] = None,
organization: Optional[str] = None,
generation_kwargs: Optional[dict[str, Any]] = None,
timeout: Optional[float] = None,
max_retries: Optional[int] = None,
tools: Optional[Union[list[Tool], Toolset]] = None,
tools_strict: bool = False,
http_client_kwargs: Optional[dict[str, Any]] = None)
创建 OpenAIChatGenerator 实例。除非在model 中另有指定,否则使用 OpenAI 的 gpt-4o-mini
在初始化组件之前,您可以设置“OPENAI_TIMEOUT”和“OPENAI_MAX_RETRIES”环境变量,以分别覆盖 OpenAI 客户端中的timeout 和max_retries 参数。
参数:
api_key:OpenAI API 密钥。您可以使用环境变量设置它OPENAI_API_KEY,或者在初始化时通过此参数传递。model: 要使用的模型名称。streaming_callback:当从流中接收到新令牌时调用的回调函数。回调函数接受 StreamingChunk 作为参数。api_base_url:一个可选的基本 URL。organization:您的组织 ID,默认为None。请参阅 生产最佳实践。generation_kwargs:用于模型的其他参数。这些参数直接发送到 OpenAI 终结点。有关详细信息,请参阅 OpenAI 文档。一些支持的参数max_tokens:输出文本可以拥有的最大 token 数。temperature:要使用的采样温度。值越高,模型承担的风险越大。对于更具创造性的应用,请尝试 0.9,对于有明确答案的应用,请尝试 0(argmax 采样)。top_p:一种替代温度采样的方法,称为核采样,模型会考虑具有 top_p 概率质量的令牌结果。例如,0.1 意味着只考虑组成前 10% 概率质量的令牌。n:为每个提示生成的完成数。例如,如果 LLM 获得 3 个提示且 n 为 2,它将为每个提示生成两个完成,最终总共生成 6 个完成。stop:LLM 应停止生成令牌的一个或多个序列。presence_penalty:如果令牌已完全存在,则应用的惩罚。值越大,模型在文本中重复相同令牌的可能性越小。frequency_penalty:如果文本中已生成令牌,则应用的惩罚。值越大,模型在文本中重复相同令牌的可能性越小。logit_bias:向特定令牌添加 logit 偏差。字典的键是令牌,值是添加到该令牌的偏差。response_format:一个 JSON Schema 或 Pydantic 模型,用于强制模型的响应结构。如果提供,输出将始终根据此格式进行验证(除非模型返回工具调用)。有关详细信息,请参阅 OpenAI 结构化输出文档。注意- 此参数接受 Pydantic 模型和 JSON Schema,适用于 GPT-4o 及更高版本的最新模型。旧模型仅通过
{"type": "json_object"}支持结构化输出的基本版本。有关 JSON 模式的详细信息,请参阅 OpenAI 结构化输出文档。 - 对于带有流的结构化输出,
response_format必须是 JSON Schema,而不是 Pydantic 模型。
- 此参数接受 Pydantic 模型和 JSON Schema,适用于 GPT-4o 及更高版本的最新模型。旧模型仅通过
timeout:OpenAI 客户端调用的超时时间。如果未设置,则默认为OPENAI_TIMEOUT环境变量,或 30 秒。max_retries: 在发生内部错误后联系 OpenAI 的最大重试次数。如果未设置,则默认为OPENAI_MAX_RETRIES环境变量,或设置为 5。tools: 一个工具列表或 Toolset,模型可以为此准备调用。此参数可以接受一个Tool对象列表或一个Toolset实例。tools_strict:是否启用对工具调用的严格模式遵循。如果设置为True,模型将严格遵循工具定义中的parameters字段,但这可能会增加延迟。http_client_kwargs:用于配置自定义的关键字参数字典httpx.Client或httpx.AsyncClient。有关更多信息,请参阅 HTTPX 文档。
OpenAIChatGenerator.to_dict
def to_dict() -> dict[str, Any]
将此组件序列化为字典。
返回值:
序列化后的组件(字典格式)。
OpenAIChatGenerator.from_dict
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "OpenAIChatGenerator"
从字典反序列化此组件。
参数:
data:此组件的字典表示。
返回值:
反序列化的组件实例。
OpenAIChatGenerator.run
@component.output_types(replies=list[ChatMessage])
def run(messages: list[ChatMessage],
streaming_callback: Optional[StreamingCallbackT] = None,
generation_kwargs: Optional[dict[str, Any]] = None,
*,
tools: Optional[Union[list[Tool], Toolset]] = None,
tools_strict: Optional[bool] = None)
根据提供的消息和生成参数调用聊天完成。
参数:
messages: 一个 ChatMessage 实例列表,表示输入消息。streaming_callback: 当从流中接收到新 token 时调用的回调函数。generation_kwargs:文本生成的附加关键字参数。这些参数将覆盖组件初始化期间传递的参数。有关 OpenAI API 参数的详细信息,请参阅 OpenAI 文档。tools: 一个工具列表或 Toolset,模型可以为此准备调用。如果设置,它将覆盖tools参数在组件初始化期间设置。此参数可以接受列表或Tool对象列表或一个Toolset实例。tools_strict:是否启用对工具调用的严格模式遵循。如果设置为True,模型将严格遵循工具定义中的parameters字段,但这可能会增加延迟。如果设置,它将覆盖在组件初始化期间设置的tools_strict参数。
返回值:
一个字典,其中包含以下键
replies:包含生成的响应作为 ChatMessage 实例的列表。
OpenAIChatGenerator.run_async
@component.output_types(replies=list[ChatMessage])
async def run_async(messages: list[ChatMessage],
streaming_callback: Optional[StreamingCallbackT] = None,
generation_kwargs: Optional[dict[str, Any]] = None,
*,
tools: Optional[Union[list[Tool], Toolset]] = None,
tools_strict: Optional[bool] = None)
根据提供的消息和生成参数异步调用聊天完成。
这是run 方法。它具有相同的参数和返回值,但可以在异步代码中与await 一起使用。
参数:
messages: 一个 ChatMessage 实例列表,表示输入消息。streaming_callback:当从流中接收到新令牌时调用的回调函数。必须是协程。generation_kwargs:文本生成的附加关键字参数。这些参数将覆盖组件初始化期间传递的参数。有关 OpenAI API 参数的详细信息,请参阅 OpenAI 文档。tools: 一个工具列表或 Toolset,模型可以为此准备调用。如果设置,它将覆盖tools参数在组件初始化期间设置。此参数可以接受列表或Tool对象列表或一个Toolset实例。tools_strict:是否启用对工具调用的严格模式遵循。如果设置为True,模型将严格遵循工具定义中的parameters字段,但这可能会增加延迟。如果设置,它将覆盖在组件初始化期间设置的tools_strict参数。
返回值:
一个字典,其中包含以下键
replies:包含生成的响应作为 ChatMessage 实例的列表。
