Anthropic 集成,用于 Haystack
模块 haystack_integrations.components.generators.anthropic.generator
AnthropicGenerator
@component
class AnthropicGenerator()
使用 Anthropic 大型语言模型 (LLMs) 实现文本生成。它支持 Claude 系列模型。
虽然 Anthropic 本地支持更丰富的消息 API,但在此组件中,我们特意简化了它,以便主要输入/输出接口是基于字符串的。有关更全面的支持,请考虑使用 AnthropicChatGenerator。
from haystack_integrations.components.generators.anthropic import AnthropicGenerator
client = AnthropicGenerator(model="claude-sonnet-4-20250514")
response = client.run("What's Natural Language Processing? Be brief.")
print(response)
>>{'replies': ['Natural language processing (NLP) is a branch of artificial intelligence focused on enabling
>>computers to understand, interpret, and manipulate human language. The goal of NLP is to read, decipher,
>> understand, and make sense of the human languages in a manner that is valuable.'], 'meta': {'model':
>> 'claude-2.1', 'index': 0, 'finish_reason': 'end_turn', 'usage': {'input_tokens': 18, 'output_tokens': 58}}}
AnthropicGenerator.__init__
def __init__(api_key: Secret = Secret.from_env_var("ANTHROPIC_API_KEY"),
model: str = "claude-sonnet-4-20250514",
streaming_callback: Optional[Callable[[StreamingChunk],
None]] = None,
system_prompt: Optional[str] = None,
generation_kwargs: Optional[Dict[str, Any]] = None,
*,
timeout: Optional[float] = None,
max_retries: Optional[int] = None)
初始化 AnthropicGenerator。
参数:
api_key: Anthropic API 密钥。model: 要使用的 Anthropic 模型名称。streaming_callback: 一个可选的回调函数,用于处理流式响应块。system_prompt: 用于生成的可选系统提示。generation_kwargs: 生成的其他关键字参数。
AnthropicGenerator.to_dict
def to_dict() -> Dict[str, Any]
将此组件序列化为字典。
返回值:
序列化后的组件(字典格式)。
AnthropicGenerator.from_dict
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "AnthropicGenerator"
从字典反序列化此组件。
参数:
data:此组件的字典表示。
返回值:
反序列化的组件实例。
AnthropicGenerator.run
@component.output_types(replies=List[str], meta=List[Dict[str, Any]])
def run(
prompt: str,
generation_kwargs: Optional[Dict[str, Any]] = None,
streaming_callback: Optional[Callable[[StreamingChunk], None]] = None
) -> Dict[str, Union[List[str], List[Dict[str, Any]]]]
使用 Anthropic API 生成回复。
参数:
prompt: 生成的输入提示。generation_kwargs: 生成的其他关键字参数。streaming_callback: 一个可选的回调函数,用于处理流式响应块。
返回值:
一个包含
replies: 生成回复的列表。meta: 每个回复的元数据字典列表。
模块 haystack_integrations.components.generators.anthropic.chat.chat_generator
AnthropicChatGenerator
@component
class AnthropicChatGenerator()
使用 Anthropic 的大型语言模型 (LLMs) 完成聊天。
它在输入和输出中使用 ChatMessage 格式。支持包括文本和图像在内的多模态输入。
您可以通过将参数传递给 Anthropic API 来自定义文本的生成方式。在初始化组件时或运行时,使用**generation_kwargs 参数。任何适用于anthropic.Message.create 的参数都可以在此处使用。
有关 Anthropic API 参数的详细信息,请参阅 Anthropic 文档。
使用示例
from haystack_integrations.components.generators.anthropic import (
AnthropicChatGenerator,
)
from haystack.dataclasses import ChatMessage
generator = AnthropicChatGenerator(
model="claude-sonnet-4-20250514",
generation_kwargs={
"max_tokens": 1000,
"temperature": 0.7,
},
)
messages = [
ChatMessage.from_system(
"You are a helpful, respectful and honest assistant"
),
ChatMessage.from_user("What's Natural Language Processing?"),
]
print(generator.run(messages=messages))
带图片的用法示例
from haystack.dataclasses import ChatMessage, ImageContent
image_content = ImageContent.from_file_path("path/to/image.jpg")
messages = [
ChatMessage.from_user(
content_parts=["What's in this image?", image_content]
)
]
generator = AnthropicChatGenerator()
result = generator.run(messages)
AnthropicChatGenerator.__init__
def __init__(api_key: Secret = Secret.from_env_var("ANTHROPIC_API_KEY"),
model: str = "claude-sonnet-4-20250514",
streaming_callback: Optional[StreamingCallbackT] = None,
generation_kwargs: Optional[Dict[str, Any]] = None,
ignore_tools_thinking_messages: bool = True,
tools: Optional[Union[List[Tool], Toolset]] = None,
*,
timeout: Optional[float] = None,
max_retries: Optional[int] = None)
创建 AnthropicChatGenerator 的实例。
参数:
api_key: Anthropic API 密钥model: 要使用的模型名称。streaming_callback: 当从流中接收到新 token 时调用的回调函数。回调函数接受 StreamingChunk 作为参数。generation_kwargs: 用于模型的其他参数。这些参数将直接发送到 Anthropic 端点。有关更多详细信息,请参阅 Anthropic 文档。
支持的 generation_kwargs 参数有:
system: 要传递给模型的系统消息。max_tokens: 要生成的最大 token 数。metadata: 要传递给模型的元数据字典。stop_sequences: 模型应停止生成的字符串列表。temperature: 用于采样的温度。top_p: 用于核采样 (nucleus sampling) 的 top_p 值。top_k: 用于 top-k 采样的 top_k 值。extra_headers: 要传递给模型的额外标头字典 (例如,用于 Beta 功能)。thinking: 要传递给模型的思考参数字典。用于思考的budget_tokens应小于max_tokens。有关更多详细信息和支持的模型,请参阅:Anthropic 扩展思考ignore_tools_thinking_messages: Anthropic 处理工具 (函数调用) 解析的方法涉及在返回实际函数名和参数的消息之前,有一系列“思考”消息。如果ignore_tools_thinking_messages为True,则在检测到工具使用时,生成器将丢弃所谓的思考消息。有关更多详细信息,请参阅 Anthropic 工具。tools:模型可以使用的一系列 Tool 对象或 Toolset。每个工具都应有一个唯一的名称。timeout: Anthropic 客户端调用的超时时间。如果未设置,则默认为 Anthropic 客户端设置的默认值。max_retries: 尝试重试失败请求的最大次数。如果未设置,则默认为 Anthropic 客户端设置的默认值。
AnthropicChatGenerator.to_dict
def to_dict() -> Dict[str, Any]
将此组件序列化为字典。
返回值:
序列化后的组件(字典格式)。
AnthropicChatGenerator.from_dict
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "AnthropicChatGenerator"
从字典反序列化此组件。
参数:
data:此组件的字典表示。
返回值:
反序列化的组件实例。
AnthropicChatGenerator.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
) -> Dict[str, List[ChatMessage]]
使用给定的消息和 generation_kwargs 调用 Anthropic API。
参数:
messages: 一个 ChatMessage 实例列表,表示输入消息。streaming_callback: 当从流中接收到新 token 时调用的回调函数。generation_kwargs: 可选参数,用于传递给 Anthropic 生成端点。tools: 模型可以使用的一组 Tool 对象或 Toolset。每个工具都应有一个唯一的名称。如果设置,它将覆盖tools参数。
返回值:
包含以下键的字典
replies: 模型的响应
AnthropicChatGenerator.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
) -> Dict[str, List[ChatMessage]]
run 方法的异步版本。使用给定的消息和 generation_kwargs 调用 Anthropic API。
参数:
messages: 一个 ChatMessage 实例列表,表示输入消息。streaming_callback: 当从流中接收到新 token 时调用的回调函数。generation_kwargs: 可选参数,用于传递给 Anthropic 生成端点。tools: 模型可以使用的一组 Tool 对象或 Toolset。每个工具都应有一个唯一的名称。如果设置,它将覆盖tools参数。
返回值:
包含以下键的字典
replies: 模型的响应
模块 haystack_integrations.components.generators.anthropic.chat.vertex_chat_generator
AnthropicVertexChatGenerator
@component
class AnthropicVertexChatGenerator(AnthropicChatGenerator)
使用最新的 Claude 3 LLMs 通过 Anthropic Vertex AI API 实现文本生成。它支持的模型包括Claude 3.5 Sonnet, Claude 3 Opus, Claude 3 Sonnet,以及Claude 3 Haiku,可通过 Vertex AI API 端点访问。
要使用 AnthropicVertexChatGenerator,您必须拥有一个启用了 Vertex AI 的 GCP 项目。此外,请确保所需的 Anthropic 模型已在 Vertex AI 模型库中激活。在发出请求之前,您可能需要使用gcloud auth login 进行 GCP 身份验证。有关更多详细信息,请参阅 [指南] (https://docs.anthropic.com/en/api/claude-on-vertex-ai)。
Anthropic Messaging API 的任何有效文本生成参数都可以传递给 AnthropicVertex API。用户可以通过generation_kwargs 参数,将 Llama Chat Completion API 支持的任何文本生成参数直接传递给此组件,该参数位于__init__ 或run 方法中。
有关 Anthropic API 支持的参数的更多详细信息,请参阅 Anthropic Message API 文档。
from haystack_integrations.components.generators.anthropic import AnthropicVertexChatGenerator
from haystack.dataclasses import ChatMessage
messages = [ChatMessage.from_user("What's Natural Language Processing?")]
client = AnthropicVertexChatGenerator(
model="claude-sonnet-4@20250514",
project_id="your-project-id", region="your-region"
)
response = client.run(messages)
print(response)
>> {'replies': [ChatMessage(_role=<ChatRole.ASSISTANT: 'assistant'>, _content=[TextContent(text=
>> "Natural Language Processing (NLP) is a field of artificial intelligence that
>> focuses on enabling computers to understand, interpret, and generate human language. It involves developing
>> techniques and algorithms to analyze and process text or speech data, allowing machines to comprehend and
>> communicate in natural languages like English, Spanish, or Chinese.")],
>> _name=None, _meta={'model': 'claude-sonnet-4@20250514', 'index': 0, 'finish_reason': 'end_turn',
>> 'usage': {'input_tokens': 15, 'output_tokens': 64}})]}
有关支持的模型及其功能的更多详细信息,请参阅 Anthropic 文档。
AnthropicVertexChatGenerator.__init__
def __init__(region: str,
project_id: str,
model: str = "claude-sonnet-4@20250514",
streaming_callback: Optional[Callable[[StreamingChunk],
None]] = None,
generation_kwargs: Optional[Dict[str, Any]] = None,
ignore_tools_thinking_messages: bool = True,
tools: Optional[List[Tool]] = None,
*,
timeout: Optional[float] = None,
max_retries: Optional[int] = None)
创建 AnthropicVertexChatGenerator 的实例。
参数:
region: Anthropic 模型部署的区域。默认为 "us-central1"。project_id: 部署 Anthropic 模型的 GCP 项目 ID。model: 要使用的模型名称。streaming_callback: 当从流中接收到新 token 时调用的回调函数。回调函数接受 StreamingChunk 作为参数。generation_kwargs: 用于模型的其他参数。这些参数将直接发送到 AnthropicVertex 端点。有关更多详细信息,请参阅 Anthropic 文档。
支持的 generation_kwargs 参数有:
system: 要传递给模型的系统消息。max_tokens: 要生成的最大 token 数。metadata: 要传递给模型的元数据字典。stop_sequences: 模型应停止生成的字符串列表。temperature: 用于采样的温度。top_p: 用于核采样 (nucleus sampling) 的 top_p 值。top_k: 用于 top-k 采样的 top_k 值。extra_headers: 要传递给模型的额外标头字典 (例如,用于 Beta 功能)。ignore_tools_thinking_messages: Anthropic 处理工具 (函数调用) 解析的方法涉及在返回实际函数名和参数的消息之前,有一系列“思考”消息。如果ignore_tools_thinking_messages为True,则在检测到工具使用时,生成器将丢弃所谓的思考消息。有关更多详细信息,请参阅 Anthropic 工具。tools: 模型可以使用的一组 Tool 对象。每个工具都应有一个唯一的名称。timeout: Anthropic 客户端调用的超时时间。如果未设置,则默认为 Anthropic 客户端设置的默认值。max_retries: 尝试重试失败请求的最大次数。如果未设置,则默认为 Anthropic 客户端设置的默认值。
AnthropicVertexChatGenerator.to_dict
def to_dict() -> Dict[str, Any]
将此组件序列化为字典。
返回值:
序列化后的组件(字典格式)。
AnthropicVertexChatGenerator.from_dict
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "AnthropicVertexChatGenerator"
从字典反序列化此组件。
参数:
data:此组件的字典表示。
返回值:
反序列化的组件实例。
