Haystack 集成 Amazon Bedrock 全指南:从生成、嵌入、检索到重排与 Token 计数的统一组件体系
【免费下载链接】haystackOpen-source AI orchestration framework for building context-engineered, production-ready LLM applications. Design modular pipelines and agent workflows with explicit control over retrieval, routing, memory, and generation. Built for scalable agents, RAG, multimodal applications, semantic search, and conversational systems.项目地址: https://gitcode.com/GitHub_Trending/ha/haystack
Amazon Bedrock 是 AWS 提供的全托管基础模型服务,通过统一 API 暴露 Anthropic、Cohere、Meta、Mistral 与 Amazon Titan 等多家厂商的模型。Haystack 通过amazon-bedrock-haystack集成包,把 Bedrock 的对话生成、文本/图像嵌入、文档重排、托管知识库检索、S3 文件下载与 Token 计数能力封装为一组可直接接入 Pipeline 的组件。本文基于 API 参考文档 展开,结合仓库内各组件用户指南(生成器指南、嵌入器指南、重排器指南 等),系统讲解每个组件的初始化参数、运行行为、底层调用机制与可运行示例,帮助你用一套 AWS 凭证打通从索引到检索、从对话到工具调用的完整 RAG 与 Agent 链路。
集成全景与安装
该集成包含的组件与工具类横跨 Haystack 的多个组件家族,全部通过一个包安装:
pip install amazon-bedrock-haystack从 API 参考 可以梳理出如下模块地图:
| 模块路径 | 组件/类 | 角色 |
|---|---|---|
components.generators.amazon_bedrock.chat.chat_generator | AmazonBedrockChatGenerator | 基于 Bedrock Converse API 的多轮对话、流式、工具调用与多模态生成 |
components.embedders.amazon_bedrock.text_embedder | AmazonBedrockTextEmbedder | 对单个字符串(查询)做向量化 |
components.embedders.amazon_bedrock.document_embedder | AmazonBedrockDocumentEmbedder | 对 Document 列表批量向量化 |
components.embedders.amazon_bedrock.document_image_embedder | AmazonBedrockDocumentImageEmbedder | 对图片/PDF 文件做多模态向量化 |
components.rankers.amazon_bedrock.ranker | AmazonBedrockRanker | 基于 Cohere/Amazon Rerank 模型对候选文档重排 |
components.retrievers.amazon_bedrock.knowledge_base_retriever | AmazonBedrockKnowledgeBaseRetriever | 检索 Bedrock 托管知识库 |
components.downloaders.s3.s3_downloader | S3Downloader | 从 S3 下载文件并回填本地路径 |
common.s3.utils | S3Storage | S3 下载底层存储工具类 |
token_counters.amazon_bedrock.token_counter | AmazonBedrockTokenCounter | 调用 Bedrock CountTokens API 精确计数 |
common.amazon_bedrock.errors/common.s3.errors | 各类异常 | 统一的错误分类体系 |
认证方式:环境变量、Secret 与 AWS CLI
所有组件共享同一套 AWS 认证逻辑。官方推荐优先使用 AWS CLI 配置凭证(aws configure),此时无需在组件初始化时传任何凭证参数,boto3 会自动从环境或~/.aws配置文件中加载。若 AWS 环境未配置,则需显式提供三个必填项:aws_access_key_id、aws_secret_access_key、aws_region_name(并确保所选区域支持 Amazon Bedrock)。
各组件构造函数默认都通过Secret.from_env_var(..., strict=False)读取以下环境变量:
AWS_ACCESS_KEY_ID→aws_access_key_idAWS_SECRET_ACCESS_KEY→aws_secret_access_keyAWS_SESSION_TOKEN→aws_session_token(临时凭证场景)AWS_DEFAULT_REGION→aws_region_nameAWS_PROFILE→aws_profile_name
也可以用 Secret 对象 直接注入,例如 Ranker 文档中的写法:
from haystack.utils import Secret from haystack_integrations.components.rankers.amazon_bedrock import AmazonBedrockRanker ranker = AmazonBedrockRanker( model="cohere.rerank-v3-5:0", top_k=2, aws_region_name=Secret.from_token("eu-central-1"), )此外所有组件都接受boto3_config: dict[str, Any] | None,用于向底层 boto3 客户端传递重试策略、超时与连接管理等低层配置。
异常体系:分层错误分类
集成把错误按来源分为两层,均在haystack_integrations.common命名空间下定义:
Amazon Bedrock 层(common.amazon_bedrock.errors):
| 异常 | 基类 | 触发场景 |
|---|---|---|
AmazonBedrockError | Exception | 集成产生的任何错误;它透明包装原始异常,原始异常的属性(如message)可直接访问 |
AWSConfigurationError | AmazonBedrockError | AWS 环境配置错误 |
AmazonBedrockConfigurationError | AmazonBedrockError | Bedrock 节点本身配置错误(如模型不支持、区域未启用 Bedrock) |
AmazonBedrockInferenceError | AmazonBedrockError | 推理/调用过程中的错误 |
S3 层(common.s3.errors):
| 异常 | 基类 | 触发场景 |
|---|---|---|
S3Error | Exception | S3 相关组件出现的问题 |
S3ConfigurationError | S3Error | S3 节点配置错误 |
S3StorageError | S3Error | 与S3Storage交互时出错(文件不存在、下载失败等) |
这种分层设计让上层管道可以按粒度捕获异常:既可以用AmazonBedrockError统一兜底 Bedrock 相关故障,也可以精确区分「配置问题」与「推理问题」采取不同重试/告警策略。
AmazonBedrockChatGenerator:基于 Converse API 的统一对话生成
这是集成中功能最丰富的组件,通过 Bedrock Converse API 完成对话补全,用一个组件对接 Amazon、Anthropic、Cohere、Meta、Mistral 等多厂商聊天模型。例如使用global.anthropic.claude-sonnet-4-6模型:
from haystack_integrations.components.generators.amazon_bedrock import ( AmazonBedrockChatGenerator, ) from haystack.dataclasses import ChatMessage messages = [ ChatMessage.from_system("You are a helpful assistant that answers question in Spanish only"), ChatMessage.from_user("What's Natural Language Processing? Be brief."), ] generator = AmazonBedrockChatGenerator(model="global.anthropic.claude-sonnet-4-6") response = generator.run(messages) print(response)run()的签名支持两种输入:messages: list[ChatMessage] | str,若直接传字符串会自动包装为一条 user 角色的ChatMessage;返回值统一放在"replies"键下,是模型生成的ChatMessage列表。ChatMessage是 Haystack 核心数据类(见 chat_message.py)。
生成参数 generation_kwargs
初始化与运行两个阶段都可以传generation_kwargs,运行期传入的字典按 key 与初始化期合并,运行期 key 优先。常见参数包括:
maxTokens:最大生成 token 数stopSequences:停止序列列表temperature:采样温度topP:核采样参数response_format:结构化 JSON 输出,需提供schema(必填 JSON Schema dict)、name(可选,默认"response_schema")、description(可选)
generation_kwargs = { "response_format": { "name": "person", "schema": { "type": "object", "properties": { "name": {"type": "string"}, "age": {"type": "integer"}, }, "required": ["name", "age"], "additionalProperties": False, }, } }启用response_format后,解析出的 JSON 对象存放在reply.meta["structured_output"]中。模型专有参数(如不同厂商的 temperature、topP 命名差异)请以 Bedrock 的模型参数文档为准。
流式输出与异步执行
流式输出通过streaming_callback开启。初始化时传入回调后组件即进入流式模式;回调接收 Haystack 的StreamingChunk对象。也可以在每个run()调用时临时传入回调覆盖。常用做法是配合仓库内置的print_streaming_chunk工具函数(见 generators/utils):
from haystack.components.generators.utils import print_streaming_chunk client = AmazonBedrockChatGenerator( model="global.anthropic.claude-sonnet-4-6", streaming_callback=print_streaming_chunk, ) client.run(messages, generation_kwargs={"max_tokens": 512})同时组件提供run_async(),签名与run()完全一致,专为非阻塞、并发执行场景设计;异步流式回调优先。
工具调用:复用 Haystack 统一工具架构
AmazonBedrockChatGenerator支持 Haystack 的统一工具体系,同一份Tool定义可以跨 Bedrock、OpenAI、Ollama 等不同提供商一致使用。tools参数接受ToolsType:可以是 Tool 对象列表、单个Toolset、或 Tool 与 Toolset 的混合列表(Tool/Toolset定义见 tool.py 与 toolset.py)。
from haystack.dataclasses import ChatMessage from haystack.tools import Tool from haystack_integrations.components.generators.amazon_bedrock import AmazonBedrockChatGenerator def weather(city: str): return f'The weather in {city} is sunny and 32°C' weather_tool = Tool( name="weather", description="useful to determine the weather in a given location", parameters={ "type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"], }, function=weather, ) client = AmazonBedrockChatGenerator( model="global.anthropic.claude-sonnet-4-6", tools=[weather_tool], ) messages = [ChatMessage.from_user("What's the weather like in Paris?")] results = client.run(messages=messages) # 取出模型发起的工具调用 tool_message = next(msg for msg in results["replies"] if msg.tool_call) tool_call = tool_message.tool_call # 执行工具并把结果回传给模型 weather_result = weather(**tool_call.arguments) new_messages = [ messages[0], tool_message, ChatMessage.from_tool(tool_result=weather_result, origin=tool_call), ] final_result = client.run(new_messages) print(final_result["replies"][0].text)工具列表也可以在run()时动态传入,每个工具名必须唯一。这正是构建 Agent 循环的关键:模型发起调用 → 应用执行 → 通过ChatMessage.from_tool回传 → 模型给出最终答复。
多模态输入
Converse API 天然支持图像输入。把ImageContent(见 image_content.py)与文本组合成一条 user 消息即可:
from haystack.dataclasses import ChatMessage, ImageContent from haystack_integrations.components.generators.amazon_bedrock import AmazonBedrockChatGenerator generator = AmazonBedrockChatGenerator(model="global.anthropic.claude-sonnet-4-6") image_content = ImageContent.from_file_path(file_path="apple.jpg") message = ChatMessage.from_user(content_parts=["Describe the image using 10 words at most.", image_content]) response = generator.run(messages=[message])["replies"][0].text提示缓存(Prompt Caching)
组件支持 Bedrock 的提示缓存以降低延迟与输入 token 成本。缓存点在请求内最多可设四个,并需满足模型特定的最小 token 阈值。两种配置途径:
缓存消息:在ChatMessage.meta中设置cachePoint:
msg = ChatMessage.from_user( "Long message...", meta={"cachePoint": {"type": "default", "ttl": "5m"}}, )缓存写入成功后,可在结果中读取缓存命中的输入 token 数:
result["replies"][0].meta["usage"]["cache_write_input_tokens"]缓存工具与系统消息:通过初始化参数tools_cachepoint_config与system_cachepoint_config,字典需匹配 BedrockCachePointBlock结构,例如{"type": "default", "ttl": "5m"}。传入tools_cachepoint_config后,所有发给模型的工具定义(超过最小阈值时)都会被缓存。
安全护栏 Guardrails
guardrail_config用于关联在 Bedrock 控制台创建的护栏,字典需匹配 BedrockGuardrailConfiguration(普通模式)或GuardrailStreamConfiguration(流式模式,即设置了streaming_callback时)。若trace设为enabled,护栏 trace 会写入结果ChatMessage的meta["trace"]。注意流式模式启用护栏可能引入额外延迟,可通过调整streamProcessingMode平衡。
嵌入组件三件套:文本、文档、图像
AmazonBedrockTextEmbedder:查询向量化
用于对单个字符串(通常是查询)做向量化,输出{"embedding": [...]}。支持 Amazon Titan 与 Cohere 嵌入模型,如amazon.titan-embed-text-v1、amazon.titan-embed-text-v2:0、amazon.titan-embed-image-v1、cohere.embed-english-v3、cohere.embed-multilingual-v3、cohere.embed-v4:0。除模型与凭证外,其余参数通过**kwargs透传给模型推理,例如 Cohere 的input_type(如search_query)与truncate,或 Titan V2 的dimensions、normalize。
import os from haystack_integrations.components.embedders.amazon_bedrock import AmazonBedrockTextEmbedder os.environ["AWS_ACCESS_KEY_ID"] = "..." os.environ["AWS_SECRET_ACCESS_KEY"] = "..." os.environ["AWS_DEFAULT_REGION"] = "us-east-1" text_embedder = AmazonBedrockTextEmbedder( model="cohere.embed-english-v3", input_type="search_query", truncate="LEFT", ) print(text_embedder.run("I love pizza!")) # {'embedding': [-0.453125, 1.2236328, 2.0058594, ...]}AmazonBedrockDocumentEmbedder:文档批量向量化
用于索引管道中在DocumentWriter之前批量嵌入文档,结果写入每个Document.embedding字段。关键参数:
| 参数 | 默认值 | 说明 |
|---|---|---|
batch_size | 32 | 一次编码的 Document 数;仅 Cohere 模型支持批量推理,Titan 模型忽略该参数 |
progress_bar | True | 是否显示进度条,生产环境建议关闭以保持日志干净 |
meta_fields_to_embed | None | 需要随正文一起嵌入的 meta 字段列表,可提升检索质量 |
embedding_separator | "\n" | 拼接 meta 字段与正文的分隔符 |
import os from haystack import Document from haystack_integrations.components.embedders.amazon_bedrock import AmazonBedrockDocumentEmbedder os.environ["AWS_ACCESS_KEY_ID"] = "..." os.environ["AWS_SECRET_ACCESS_KEY"] = "..." os.environ["AWS_DEFAULT_REGION"] = "us-east-1" doc = Document(content="some text", meta={"title": "relevant title", "page number": 18}) embedder = AmazonBedrockDocumentEmbedder( model="cohere.embed-english-v3", input_type="search_document", meta_fields_to_embed=["title"], ) docs_w_embeddings = embedder.run(documents=[doc])["documents"]AmazonBedrockDocumentImageEmbedder:图片/PDF 多模态向量化
该组件读取 Document 元数据中指向的图片或 PDF 文件,计算多模态嵌入后写入embedding字段。支持模型包括amazon.titan-embed-image-v1与 Cohere 多模态系列。初始化参数要点:
file_path_meta_field(默认"file_path"):存放文件路径的 meta 字段名root_path:文件路径的相对根目录;为None时按绝对路径解析image_size: tuple[int, int] | None:按指定宽高等比缩放图片,可显著降低体积、内存与传输开销,适合有分辨率约束的模型- 模型专有参数:Titan 用
embeddingConfig;Cohere v3 用embedding_types,只支持单一取值,传多个值会报错
import os from haystack import Document from haystack_integrations.components.embedders.amazon_bedrock import ( AmazonBedrockDocumentImageEmbedder, ) os.environ["AWS_ACCESS_KEY_ID"] = "..." os.environ["AWS_SECRET_ACCESS_KEY"] = "..." os.environ["AWS_DEFAULT_REGION"] = "us-east-1" documents = [ Document(content="A photo of a cat", meta={"file_path": "cat.jpg"}), Document( content="Invoice page", meta={"file_path": "invoice.pdf", "mime_type": "application/pdf", "page_number": 1}, ), ] embedder = AmazonBedrockDocumentImageEmbedder( model="amazon.titan-embed-image-v1", image_size=(1024, 1024), ) result = embedder.run(documents=documents)嵌入后的 Document 会带有meta["embedding_source"](如{"type": "image", "file_path_meta_field": "file_path"}),便于追溯向量来源。检索阶段使用同一模型的AmazonBedrockTextEmbedder编码查询,即可与图像向量做语义匹配。
AmazonBedrockRanker:语义重排
该组件基于 Bedrock Rerank API,将文档按与查询的语义相关度从高到低排序。API 参考中列出的支持模型为cohere.rerank-v3-5:0(默认)与amazon.rerank-v1:0。初始化参数包括:
top_k(默认10):最多返回的文档数,run()时也可传入top_k覆盖max_chunks_per_doc:当文档超过 512 token 时最多拆分的块数,默认10;文档说明该参数当前未在实现中使用,仅作未来兼容预留meta_fields_to_embed/meta_data_separator(默认"\n"):把 meta 字段拼接到文档内容中参与重排
from haystack import Document from haystack_integrations.components.rankers.amazon_bedrock import AmazonBedrockRanker docs = [Document(content="Paris"), Document(content="Berlin")] ranker = AmazonBedrockRanker() # 默认模型 cohere.rerank-v3-5:0 ranker.run(query="City in France", documents=docs, top_k=1)典型的管道位置是检索器之后、Prompt 构建器之前,用于把 BM25/向量检索的粗召回结果做精排。
AmazonBedrockKnowledgeBaseRetriever:托管知识库检索
该组件直接检索 Bedrock 托管知识库,不需要 Haystack Document Store 或 Embedder——索引与向量化完全由 AWS 负责,组件只需文本查询即可。初始化时通过knowledge_base_id指定知识库 ID,也可回退到AWS_KNOWLEDGE_BASE_ID环境变量;number_of_results默认5,run()的top_k参数可覆盖它。
检索行为由use_agentic_retrieval控制:默认尝试 AgenticRetrieveStream API,不可用时回退到标准 Retrieve API;该开关默认读取USE_AGENTIC_RETRIEVAL环境变量,未设置则为True。返回的每个 Document 带有score,以及来源元数据:source(底层内容的 S3、Web、Confluence、Salesforce、SharePoint 或自定义位置)、knowledge_base_id、knowledge_base_type。
from haystack.utils import Secret from haystack_integrations.components.retrievers.amazon_bedrock import AmazonBedrockKnowledgeBaseRetriever retriever = AmazonBedrockKnowledgeBaseRetriever( knowledge_base_id="ABCDEFGHIJ", aws_region_name=Secret.from_token("eu-central-1"), ) result = retriever.run(query="What are the benefits of managed knowledge bases?") for doc in result["documents"]: print(doc.content) print(doc.meta["source"]) print(doc.score)S3 生态:S3Downloader 与 S3Storage
S3Storage:底层存储工具类
S3Storage负责从 S3 桶下载文件的底层逻辑,构造参数为s3_bucket、session(boto3 Session)、s3_prefix(可选键前缀,如"folder/subfolder/")、endpoint_url(可选,兼容 MinIO/LocalStack 等 S3 兼容服务)、config(botocore Config)。主要方法:
download(key, local_file_path):按 key 下载文件到本地,目标目录不存在会自动创建;S3 客户端创建失败抛S3ConfigurationError,文件不存在或下载失败抛S3StorageErrorclose():关闭持有的 S3 客户端from_env(*, session, config, s3_bucket_name_env="S3_DOWNLOADER_BUCKET"):从环境变量构建实例,读取S3_DOWNLOADER_BUCKET(必填,缺失抛ValueError)、S3_DOWNLOADER_PREFIX(可选前缀)、AWS_ENDPOINT_URL(可选自定义端点)
S3Downloader:管道级下载组件
S3Downloader把文件从 S3 下载到本地文件系统,并给 Document 回填meta["file_path"],适用于需要本地文件路径的转换器/路由器之前。初始化参数要点:
| 参数 | 默认值 | 说明 |
|---|---|---|
file_root_path | None | 下载根目录,也可用FILE_ROOT_PATH环境变量;两者均未设置则抛ValueError。下载被限制在该目录内,文件名解析到目录外(绝对路径或含..)的文档会被记录并跳过,而不是写入 |
file_extensions | None | 允许下载的扩展名白名单,如[".pdf", ".txt"];默认允许全部 |
file_name_meta_key | "file_name" | 存放待下载文件名的 meta 键,同时用于构造本地路径 |
s3_key_generation_function | None | 自定义 S3 key 生成函数(接收Document返回字符串);默认使用Document.meta[file_name_meta_key],若设置S3_DOWNLOADER_PREFIX环境变量会自动加前缀 |
max_workers | 32 | 并发下载的最大 worker 数 |
max_cache_size | 100 | 本地文件缓存上限,超过后淘汰最久未访问的文件;已下载文件会被 touch 更新访问时间而不重新下载 |
s3_bucket_name_env | "S3_DOWNLOADER_BUCKET" | 指定桶名所在的环境变量名 |
run(documents)返回{"documents": [...]},每个文档带有meta["file_path"];文件名缺失或解析到根目录外的文档会被记录并跳过。warm_up()会校验桶环境变量并创建 S3 客户端,凭证无效时抛AWSConfigurationError。
最小可运行示例:
export AWS_ACCESS_KEY_ID="<your-access-key-id>" export AWS_SECRET_ACCESS_KEY="<your-secret-access-key>" export AWS_DEFAULT_REGION="<your-region>" export S3_DOWNLOADER_BUCKET="<your-bucket-name>"from haystack.dataclasses import Document from haystack_integrations.components.downloaders.s3 import S3Downloader documents = [ Document(meta={"file_name": "report.pdf"}), Document(meta={"file_name": "data.txt"}), ] downloader = S3Downloader(file_root_path="/tmp/s3_downloads") result = downloader.run(documents=documents) for doc in result["documents"]: print(f"File downloaded to: {doc.meta['file_path']}")结合文件类型路由与转换器的完整索引管道(完整示例见 S3Downloader 指南):
from haystack import Pipeline from haystack.components.converters import PDFMinerToDocument from haystack.components.routers import DocumentTypeRouter from haystack.dataclasses import Document from haystack_integrations.components.downloaders.s3 import S3Downloader pipe = Pipeline() pipe.add_component( "downloader", S3Downloader(file_root_path="/tmp/s3_downloads", file_extensions=[".pdf", ".txt"]), ) pipe.add_component( "router", DocumentTypeRouter(file_path_meta_field="file_path", mime_types=["application/pdf", "text/plain"]), ) pipe.add_component("pdf_converter", PDFMinerToDocument()) pipe.connect("downloader.documents", "router.documents") pipe.connect("router.application/pdf", "pdf_converter.documents") result = pipe.run({"downloader": {"documents": [Document(meta={"file_name": "report.pdf"})]}})AmazonBedrockTokenCounter:服务端精确 Token 计数
该组件实现 Haystack 的TokenCounter协议(见 protocol.py),通过 Bedrock 的CountTokensAPI 计数。与本地分词器计数器不同,它把输入发送到服务端,因此返回值反映模型的确切分词结果——包括 Bedrock 对消息、系统提示与工具 schema 施加的格式开销。消息与工具会按Converse格式转换(与AmazonBedrockChatGenerator完全相同的转换逻辑),所以计数结果与等价的 Converse 请求实际消耗一致。
from haystack.dataclasses import ChatMessage from haystack_integrations.token_counters.amazon_bedrock import AmazonBedrockTokenCounter counter = AmazonBedrockTokenCounter(model="anthropic.claude-3-5-sonnet-20240620-v1:0") messages = [ChatMessage.from_user("Hello, how are you?")] token_count = counter.count(messages) print(f"Token count: {token_count}")count(messages, tools=None)的tools参数用于把随请求发送的工具 schema 一并计入。使用边界:Bedrock 会像 Converse 推理 API 一样校验输入——对话必须以 user 消息开头,工具结果必须与产生它的工具调用成对出现——因此count()适合度量「完整的合法对话」以在发送前评估整体请求大小,不适合度量孤立片段(如单条 tool-result 消息)。片段级计数应使用本地计数器ApproximateTokenCounter(见 approximate_counter.py),例如压缩器(compactor)内部对单条消息的测量。无内容可度量时返回0;CountTokens请求失败抛AmazonBedrockInferenceError。
端到端:组装 RAG 与多模态管道
标准 RAG:嵌入 → 向量检索 → Bedrock 生成
把文档嵌入器、DocumentWriter、InMemoryDocumentStore(见 in_memory)、InMemoryEmbeddingRetriever与 Bedrock 组件串联(完整示例见 DocumentEmbedder 指南):
from haystack import Document, Pipeline from haystack.document_stores.in_memory import InMemoryDocumentStore from haystack.components.retrievers.in_memory import InMemoryEmbeddingRetriever from haystack.components.writers import DocumentWriter from haystack_integrations.components.embedders.amazon_bedrock import ( AmazonBedrockDocumentEmbedder, AmazonBedrockTextEmbedder, ) document_store = InMemoryDocumentStore(embedding_similarity_function="cosine") documents = [ Document(content="My name is Wolfgang and I live in Berlin"), Document(content="I saw a black horse running"), Document(content="Germany has many big cities"), ] indexing_pipeline = Pipeline() indexing_pipeline.add_component( "embedder", AmazonBedrockDocumentEmbedder(model="cohere.embed-english-v3") ) indexing_pipeline.add_component("writer", DocumentWriter(document_store=document_store)) indexing_pipeline.connect("embedder", "writer") indexing_pipeline.run({"embedder": {"documents": documents}}) query_pipeline = Pipeline() query_pipeline.add_component( "text_embedder", AmazonBedrockTextEmbedder(model="cohere.embed-english-v3") ) query_pipeline.add_component( "retriever", InMemoryEmbeddingRetriever(document_store=document_store) ) query_pipeline.connect("text_embedder.embedding", "retriever.query_embedding") result = query_pipeline.run({"text_embedder": {"text": "Who lives in Berlin?"}}) print(result["retriever"]["documents"][0])多模态检索:图像嵌入 + 文本查询
索引阶段用AmazonBedrockDocumentImageEmbedder处理图片/PDF,查询阶段用同一模型的AmazonBedrockTextEmbedder(完整示例见 DocumentImageEmbedder 指南):
indexing = Pipeline() indexing.add_component( "image_embedder", AmazonBedrockDocumentImageEmbedder(model="cohere.embed-english-v3") ) indexing.add_component("writer", DocumentWriter(document_store=document_store)) indexing.connect("image_embedder", "writer") indexing.run({"image_embedder": {"documents": documents}}) query = Pipeline() query.add_component( "text_embedder", AmazonBedrockTextEmbedder(model="cohere.embed-english-v3") ) query.add_component("retriever", InMemoryEmbeddingRetriever(document_store=document_store)) query.connect("text_embedder.embedding", "retriever.query_embedding") res = query.run({"text_embedder": {"text": "Which document shows a horse?"}})托管知识库 RAG:跳过本地索引
当知识库已在 AWS 侧建好,管道可以完全省略嵌入与文档存储环节(完整示例见 KnowledgeBaseRetriever 指南):
from haystack import Pipeline from haystack.components.builders import ChatPromptBuilder from haystack.dataclasses import ChatMessage from haystack.utils import Secret from haystack_integrations.components.generators.amazon_bedrock import AmazonBedrockChatGenerator from haystack_integrations.components.retrievers.amazon_bedrock import ( AmazonBedrockKnowledgeBaseRetriever, ) rag_pipeline = Pipeline() rag_pipeline.add_component( "retriever", AmazonBedrockKnowledgeBaseRetriever( knowledge_base_id="ABCDEFGHIJ", aws_region_name=Secret.from_token("eu-central-1"), ), ) rag_pipeline.add_component( "prompt_builder", ChatPromptBuilder( template=[ChatMessage.from_user( "Given these documents, answer the question.\nDocuments:\n" "{% for doc in documents %}{{ doc.content }}{% endfor %}\n" "\nQuestion: {{question}}\nAnswer:" )], required_variables="*", ), ) rag_pipeline.add_component( "llm", AmazonBedrockChatGenerator(model="global.anthropic.claude-sonnet-4-6") ) rag_pipeline.connect("retriever.documents", "prompt_builder.documents") rag_pipeline.connect("prompt_builder.prompt", "llm.messages") question = "What are the benefits of managed knowledge bases?" result = rag_pipeline.run( {"retriever": {"query": question}, "prompt_builder": {"question": question}} ) print(result["llm"]["replies"][0].text)序列化与总结
所有组件均实现to_dict()/from_dict(),可被 Haystack Pipeline 的 YAML/JSON 序列化机制完整保存与还原(凭证以Secret形式序列化,不会明文落盘)。各组件还统一提供warm_up()(创建/校验 Bedrock 客户端)与close()(释放客户端资源)生命周期方法,适配 Haystack 的组件资源管理约定。
这套集成把 AWS 生态中的生成、嵌入、重排、托管检索、对象存储与精确计数能力收敛为与 Haystack 组件协议完全一致的接口:查询侧与文档侧嵌入模型必须保持同型号以保证向量可比;AmazonBedrockChatGenerator是唯一同时支持流式、工具调用、多模态、提示缓存与护栏的生成组件,可作为 Agent 与复杂 RAG 的核心;Token 计数则让预算控制在发送请求前即可精确完成。若需更完整的组件速查表,可对照 API 参考 及各组件用户指南逐步验证。
【免费下载链接】haystackOpen-source AI orchestration framework for building context-engineered, production-ready LLM applications. Design modular pipelines and agent workflows with explicit control over retrieval, routing, memory, and generation. Built for scalable agents, RAG, multimodal applications, semantic search, and conversational systems.项目地址: https://gitcode.com/GitHub_Trending/ha/haystack
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考