拓冰建站拓冰建站
首页 / 资讯中心 / 正文

Haystack 中的 Cohere 集成完整指南:文本/图像嵌入、RAG 重排序与工具调用

Haystack 中的 Cohere 集成完整指南文本/图像嵌入、RAG 重排序与工具调用【免费下载链接】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/haystackCohere 集成cohere-haystack是 Haystack 生态中覆盖**嵌入Embedding、重排序Rerank与对话生成Chat**三大环节的官方组件集。本文基于仓库中 version-2.20 的 Cohere API 参考文档结合 Haystack 组件使用文档 与核心框架源码系统讲解如何用 Cohere 模型构建向量索引管道、语义检索管道、多模态 RAG 以及带工具调用的 Agent 管道。读完本文你将掌握全部六个组件的参数语义、调用方式与管道接线方法并能直接复制运行文中的代码示例。集成全景一个 Cohere 连接器覆盖索引、检索与生成Cohere 集成在 Haystack 中由六个核心组件与两个底层工具函数组成全部封装在cohere-haystack包中模块路径统一为haystack_integrations.components.*模块路径组件/函数职责embedders.cohere.document_embedderCohereDocumentEmbedder为文档列表计算向量写入每个Document的embedding字段embedders.cohere.text_embedderCohereTextEmbedder将单个字符串如查询编码为向量embedders.cohere.document_image_embedderCohereDocumentImageEmbedder基于图片/PDF 文件计算向量多模态嵌入generators.cohere.chat.chat_generatorCohereChatGenerator基于cohere.ClientV2.chat端点完成对话支持多模态与工具调用rankers.cohere.rankerCohereRanker依据与查询的语义相关性对文档重排序embedders.cohere.utilsget_response/get_async_response同步/异步批量调用的底层封装函数这些组件分属 Haystack 的索引管道Embedder → DocumentWriter与查询/RAG 管道TextEmbedder → Retriever → Ranker → ChatGenerator两大应用场景恰好对应文档中反复出现的“以embedding字段为核心”的向量检索范式。安装与认证所有组件都来自同一个集成包安装方式统一pip install cohere-haystack认证上组件默认从环境变量读取 API Key优先级顺序为COHERE_API_KEY、CO_API_KEY见各组件__init__签名中Secret.from_env_var([COHERE_API_KEY, CO_API_KEY])的默认值。也可以显式传入Secret对象from haystack.utils import Secret from haystack_integrations.components.embedders.cohere import CohereDocumentEmbedder embedder CohereDocumentEmbedder(api_keySecret.from_token(your-api-key))Secret是 Haystack 统一的凭据封装抽象定义于 haystack/utils/auth.pySecret.from_token创建不可序列化的明文密钥Secret.from_env_var按传入的环境变量列表依次解析strictTrue时若全部未设置会抛出异常。在序列化管道to_dict/from_dict时Secret能保证密钥不会泄露进序列化文件。CohereDocumentEmbedder文档批量向量化CohereDocumentEmbedder使用 Cohere 嵌入模型计算文档向量并将结果写回每个文档的embedding字段。这些向量是文档集合上执行嵌入检索Embedding Retrieval的前提检索时查询向量与文档向量逐一比较找出最相似的相关文档。from haystack import Document from haystack_integrations.components.embedders.cohere import CohereDocumentEmbedder doc Document(contentI love pizza!) document_embedder CohereDocumentEmbedder() result document_embedder.run([doc]) print(result[documents][0].embedding) # [-0.453125, 1.2236328, 2.0058594, ...]支持的模型组件维护一份SUPPORTED_MODELS列表非穷尽完整列表见 Cohere 官方 Embed 模型文档SUPPORTED_MODELS: list[str] [ embed-v4.0, embed-english-v3.0, embed-english-light-v3.0, embed-multilingual-v3.0, embed-multilingual-light-v3.0, ]默认模型为embed-v4.0。需要说明的是组件文档 coheredocumentembedder.mdx 补充了 v2 系列旧模型如embed-english-v2.0、embed-multilingual-v2.0也属于可用范围实际选择以 Cohere 官方模型列表为准。初始化参数参数类型默认值说明api_keySecretCOHERE_API_KEY/CO_API_KEYCohere API 密钥modelstrembed-v4.0模型名称input_typestrsearch_document输入类型可选search_document、search_query、classification、clusteringapi_base_urlstrhttps://api.cohere.comCohere API 基础地址truncatestrEND超长输入的截断策略NONE超长报错、START丢弃开头、END丢弃结尾截断直至剩余输入恰好等于模型最大输入 token 数timeoutfloat120.0请求超时秒batch_sizeint32单次编码的文档数量progress_barboolTrue是否显示进度条生产环境建议关闭以保持日志干净meta_fields_to_embedlist[str] \| NoneNone需要与文档正文一起参与嵌入的元数据字段列表embedding_separatorstr\n拼接元数据字段与文档正文时使用的分隔符embedding_typeEmbeddingTypes \| NoneNone返回的嵌入类型默认 floatint8、uint8、binary、ubinary仅对 v3 及以上模型有效注意input_type的默认值文档嵌入阶段固定为search_document这与查询编码阶段CohereTextEmbedder默认search_query形成语义区分是 Cohere 向量检索获得高质量相似度分数的关键约定。嵌入元数据以提升检索质量文本文档往往携带元数据。如果元数据具有区分度且语义明确如标题、页码将其与正文一起嵌入能显著改善检索效果from haystack import Document from haystack.utils import Secret from haystack_integrations.components.embedders.cohere import CohereDocumentEmbedder doc Document(contentsome text, meta{title: relevant title, page number: 18}) embedder CohereDocumentEmbedder( api_keySecret.from_token(your-api-key), meta_fields_to_embed[title], ) docs_w_embeddings embedder.run(documents[doc])[documents]嵌入检索管道索引 查询双管道将CohereDocumentEmbedder与CohereTextEmbedder配对即可构建一套完整的嵌入检索系统。索引管道负责写库查询管道负责将问题向量化并检索示例来自 coheredocumentembedder.mdxfrom haystack import Document, Pipeline from haystack.document_stores.in_memory import InMemoryDocumentStore from haystack.components.writers import DocumentWriter from haystack.components.retrievers.in_memory import InMemoryEmbeddingRetriever from haystack_integrations.components.embedders.cohere.document_embedder import ( CohereDocumentEmbedder, ) from haystack_integrations.components.embedders.cohere.text_embedder import ( CohereTextEmbedder, ) document_store InMemoryDocumentStore(embedding_similarity_functioncosine) documents [ Document(contentMy name is Wolfgang and I live in Berlin), Document(contentI saw a black horse running), Document(contentGermany has many big cities), ] indexing_pipeline Pipeline() indexing_pipeline.add_component(embedder, CohereDocumentEmbedder()) indexing_pipeline.add_component(writer, DocumentWriter(document_storedocument_store)) indexing_pipeline.connect(embedder, writer) indexing_pipeline.run({embedder: {documents: documents}}) query_pipeline Pipeline() query_pipeline.add_component(text_embedder, CohereTextEmbedder()) query_pipeline.add_component( retriever, InMemoryEmbeddingRetriever(document_storedocument_store), ) query_pipeline.connect(text_embedder.embedding, retriever.query_embedding) query Who lives in Berlin? result query_pipeline.run({text_embedder: {text: query}}) print(result[retriever][documents][0]) # Document(id..., content: My name is Wolfgang and I live in Berlin, score: ...)run/run_asyncrun(documents: list[Document])接收文档列表返回包含两个键的字典documents已写入embedding字段的文档列表meta嵌入过程的元数据。若输入不是Document列表抛出TypeError。run_async是异步版本签名与返回值完全一致可在asyncio环境中await调用。此外组件还提供warm_up()/warm_up_async()用于预先创建 Cohere 同步/异步客户端以及to_dict()/from_dict()完成管道序列化与反序列化。CohereTextEmbedder查询字符串向量化CohereTextEmbedder将单个字符串通常是查询编码为向量与文档嵌入器配套使用。它的run方法接受纯字符串输入返回结构与文档嵌入器不同——直接返回embedding和meta两个顶层键from haystack_integrations.components.embedders.cohere import CohereTextEmbedder text_to_embed I love pizza! text_embedder CohereTextEmbedder() print(text_embedder.run(text_to_embed)) # {embedding: [-0.453125, 1.2236328, 2.0058594, ...] # meta: {api_version: {version: 1}, billed_units: {input_tokens: 4}}}返回值中的meta由 Cohere API 返回包含 API 版本与计费单元信息billed_units.input_tokens表示本次请求消耗的输入 token 数。初始化参数参数类型默认值说明api_keySecretCOHERE_API_KEY/CO_API_KEYCohere API 密钥modelstrembed-v4.0模型名称input_typestrsearch_query输入类型可选值与文档嵌入器一致默认search_query表示查询侧输入api_base_urlstrhttps://api.cohere.comCohere API 基础地址truncatestrEND截断策略语义同文档嵌入器timeoutfloat120.0请求超时秒embedding_typeEmbeddingTypes \| NoneNone嵌入类型默认 floatint8、uint8、binary、ubinary仅对 v3 及以上模型有效对比可见CohereTextEmbedder精简掉了批处理与元数据嵌入相关参数——它只处理单条文本。非字符串输入会抛出TypeErrorrun_async为异步版本。CohereDocumentImageEmbedder图像/PDF 多模态嵌入CohereDocumentImageEmbedder基于图片或 PDF 文件计算文档向量同样将结果写入embedding字段。它依赖文档meta中的文件路径字段定位图像默认字段名file_path适合构建视觉检索与多模态 RAG 管道。当前版本兼容 Cohere Embed v3 及以上模型。from haystack import Document from haystack_integrations.components.embedders.cohere import CohereDocumentImageEmbedder embedder CohereDocumentImageEmbedder(modelembed-v4.0) documents [ Document(contentA photo of a cat, meta{file_path: cat.jpg}), Document(contentA photo of a dog, meta{file_path: dog.jpg}), ] result embedder.run(documentsdocuments) documents_with_embeddings result[documents] print(documents_with_embeddings) # [Document(id..., # contentA photo of a cat, # meta{file_path: cat.jpg, # embedding_source: {type: image, file_path_meta_field: file_path}}, # embeddingvector of size 1536), # ...]值得注意输出细节文档meta中会被写入embedding_source结构type: image与file_path_meta_field用于标记该向量的来源是图像文件及其路径字段方便下游调试与溯源。初始化参数参数类型默认值说明file_path_meta_fieldstrfile_path文档元数据中存放图片/PDF 路径的字段名root_pathstr \| NoneNone文档文件所在根目录提供后文件路径将相对该目录解析None时按绝对路径处理image_sizetuple[int, int] \| NoneNone指定 (宽, 高) 后按宽高比缩放图片减小体积、内存占用与处理耗时适合有分辨率约束的模型或远程传输场景api_keySecretCOHERE_API_KEY/CO_API_KEYCohere API 密钥modelstrembed-v4.0计算嵌入所用的模型api_base_urlstrhttps://api.cohere.comCohere API 基础地址timeoutfloat120.0请求超时秒embedding_dimensionint \| NoneNone返回向量的维度仅对 v4 及以上模型有效取值参见 Cohere Embed API 参考embedding_typeEmbeddingTypesEmbeddingTypes.FLOAT嵌入类型非 float 类型仅对 Embed v3.0 及以上模型支持progress_barboolTrue是否显示进度条生产环境建议关闭run(documents)只返回documents一个键文档列表异步版本run_async签名一致。此外同样具备warm_up/warm_up_async/to_dict/from_dict标准组件方法。多模态 RAG 管道图片索引 文本查询完整的多模态检索管道由三部分组成ImageFileToDocument转换器负责把图片变成携带meta.file_path的文档CohereDocumentImageEmbedder计算图像向量并写库DocumentWriter持久化查询侧则用同一个模型的CohereTextEmbedder编码文本查询示例来自 coheredocumentimageembedder.mdxfrom haystack import Pipeline from haystack.components.converters.image import ImageFileToDocument from haystack.components.retrievers.in_memory import InMemoryEmbeddingRetriever from haystack.components.writers import DocumentWriter from haystack.document_stores.in_memory import InMemoryDocumentStore from haystack_integrations.components.embedders.cohere import ( CohereDocumentImageEmbedder, CohereTextEmbedder, ) document_store InMemoryDocumentStore() # Indexing pipeline indexing_pipeline Pipeline() indexing_pipeline.add_component(image_converter, ImageFileToDocument()) indexing_pipeline.add_component( embedder, CohereDocumentImageEmbedder(modelembed-v4.0), ) indexing_pipeline.add_component(writer, DocumentWriter(document_storedocument_store)) indexing_pipeline.connect(image_converter, embedder) indexing_pipeline.connect(embedder, writer) indexing_pipeline.run(data{image_converter: {sources: [dog.jpg, hyena.jpeg]}}) # Multimodal retrieval pipeline retrieval_pipeline Pipeline() retrieval_pipeline.add_component(embedder, CohereTextEmbedder(modelembed-v4.0)) retrieval_pipeline.add_component( retriever, InMemoryEmbeddingRetriever(document_storedocument_store, top_k2), ) retrieval_pipeline.connect(embedder.embedding, retriever.query_embedding) result retrieval_pipeline.run(data{text: mans best friend}) print(result) # {retriever: {documents: [Document(id0c96..., meta{file_path: dog.jpg, ...}, score0.288), # Document(id5e76..., meta{file_path: hyena.jpeg, ...}, score0.248)]}}由于图像向量与文本向量位于同一语义空间mans best friend这类文本查询能正确召回dog.jpg——这正是多模态向量检索的核心价值。底层封装get_response 与 get_async_response嵌入类组件都基于embedders.cohere.utils中的两个函数完成 API 调用get_response( cohere_client: ClientV2, texts: list[str], model_name: str, input_type: str, truncate: str, batch_size: int 32, progress_bar: bool False, embedding_type: EmbeddingTypes | None None, ) - tuple[list[list[float]], dict[str, Any]]get_async_response的唯一区别是第一个参数为AsyncClientV2Cohere 异步客户端。两者都返回(embeddings, metadata)二元组并在 API 调用出错时抛出ValueError。从源码签名可以推断出如下实现细节分批调用Cohere Embed 端点对单次请求的文本条数有上限因此两个函数都按batch_size默认 32将texts分批发送同步与异步路径保持一致进度条复用progress_bar控制批处理进度显示默认False组件层再按需打开元数据透传返回的meta字典即 API 响应中的元信息如billed_units最终透出到组件run的返回值中。CohereChatGenerator对话生成、流式输出与工具调用CohereChatGenerator使用cohere.ClientV2的chat端点完成对话同时支持纯文本与多模态文本 图片对话。图片支持 PNG、JPEG、WEBP、GIF非动画单请求最多 20 张图、总大小 20MB。它可以通过**generation_kwargs透传任意 Cohere Chat 端点参数。支持的模型SUPPORTED_MODELS: list[str] [ command-a-03-2025, command-r7b-12-2024, command-a-translate-08-2025, command-a-reasoning-08-2025, command-a-vision-07-2025, command-r-08-2024, command-r-plus-08-2024, command-r-03-2024, command-r-plus-04-2024, command-r-plus, command-r, command-light, command, ]默认模型为command-a-03-2025完整列表以 Cohere Command 模型文档为准。初始化参数参数类型默认值说明api_keySecretCOHERE_API_KEY/CO_API_KEYCohere API 密钥modelstrcommand-a-03-2025Command 系列模型名称streaming_callbackStreamingCallbackT \| NoneNone流式回调收到新 token 时被调用参数为StreamingChunkapi_base_urlstr \| NoneNoneCohere API 基础地址未设置时使用 Cohere 客户端默认值generation_kwargsdict[str, Any] \| NoneNone生成参数透传给 Cohere Chat 端点。常用项messages多轮对话上下文、system_message对话开头的系统消息、citation_qualityRAG 引用质量默认accurate可设fast加速、temperature非负浮点数越低生成越确定toolsToolsType \| NoneNone模型可调用的工具支持 Tool 列表、Toolset 对象或二者混合timeoutfloat \| NoneNone客户端调用超时未设置时用 Cohere 客户端默认值max_retriesint \| NoneNone失败请求最大重试次数未设置时用 Cohere 客户端默认值基础对话from haystack.dataclasses import ChatMessage from haystack.utils import Secret from haystack_integrations.components.generators.cohere import CohereChatGenerator client CohereChatGenerator(api_keySecret.from_env_var(COHERE_API_KEY)) messages [ChatMessage.from_user(Whats Natural Language Processing?)] client.run(messages) # Output: {replies: [ChatMessage(_roleChatRole.ASSISTANT: assistant, # _content[TextContent(textNatural Language Processing (NLP) is an interdisciplinary...]输入messages支持list[ChatMessage]或裸字符串字符串会被自动包装为一条 user 角色的ChatMessage。输出字典只包含replies键即生成的ChatMessage列表。多模态对话使用ImageContent将图片附加到消息中配合视觉模型如command-a-vision-07-2025即可进行图文对话from haystack.dataclasses import ChatMessage, ImageContent from haystack.utils import Secret from haystack_integrations.components.generators.cohere import CohereChatGenerator # Create an image from file path or base64 image_content ImageContent.from_file_path(path/to/your/image.jpg) # Create a multimodal message with both text and image messages [ChatMessage.from_user(content_parts[Whats in this image?, image_content])] # Use a multimodal model like Command A Vision client CohereChatGenerator(modelcommand-a-vision-07-2025, api_keySecret.from_env_var(COHERE_API_KEY)) response client.run(messages) print(response)工具调用Function CallingCohereChatGenerator完整支持 Haystack 的工具架构可与ToolInvoker组成 Agent 管道实现工具自动调用。参考文档中的完整示例from haystack import Pipeline from haystack.dataclasses import ChatMessage from haystack.components.tools import ToolInvoker from haystack.tools import Tool from haystack_integrations.components.generators.cohere import CohereChatGenerator # Create a weather tool def weather(city: str) - str: return fThe weather in {city} is sunny and 32°C weather_tool Tool( nameweather, descriptionuseful to determine the weather in a given location, parameters{ type: object, properties: { city: { type: string, description: The name of the city to get weather for, e.g. Paris, London, } }, required: [city], }, functionweather, ) # Create and set up the pipeline pipeline Pipeline() pipeline.add_component(generator, CohereChatGenerator(tools[weather_tool])) pipeline.add_component(tool_invoker, ToolInvoker(tools[weather_tool])) pipeline.connect(generator, tool_invoker) # Run the pipeline with a weather query results pipeline.run( data{generator: {messages: [ChatMessage.from_user(Whats the weather like in Paris?)]}} ) # The tool result will be available in the pipeline output print(results[tool_invoker][tool_messages][0].tool_call_result.result) # Output: The weather in Paris is sunny and 32°C工具配置非常灵活既可以传Tool列表也可以直接传一个Toolset还可以把多个Toolset与独立Tool混在一个列表中。run()方法额外接受generation_kwargs、tools、streaming_callback三个可选参数其中generation_kwargs按 key 与初始化时传入的配置合并run级参数优先tools若传入则覆盖初始化时的工具配置。异步版本run_async具有完全相同的签名。流式输出组件支持流式输出向streaming_callback传入回调函数即可逐 token 接收内容回调参数为 Haystack 的StreamingChunk数据类。流式模式尤其适合对话类 UI 的实时渲染。在管道中使用CohereChatGenerator的典型位置是接在ChatPromptBuilder之后参见 coherechatgenerator.mdxfrom haystack import Pipeline from haystack.components.builders import ChatPromptBuilder from haystack.dataclasses import ChatMessage from haystack_integrations.components.generators.cohere import CohereChatGenerator pipe Pipeline() pipe.add_component(prompt_builder, ChatPromptBuilder()) pipe.add_component(llm, CohereChatGenerator()) pipe.connect(prompt_builder, llm) country Germany system_message ChatMessage.from_system( You are an assistant giving out valuable information to language learners., ) messages [ system_message, ChatMessage.from_user(Whats the official language of {{ country }}?), ] res pipe.run( data{ prompt_builder: { template_variables: {country: country}, template: messages, }, }, ) print(res)CohereRanker查询相关性重排序CohereRanker基于 Cohere Rerank 模型按照文档与查询的语义相关度对文档排序相关性从高到低输出。它通常放在检索器之后用于精排召回结果。from haystack import Document from haystack_integrations.components.rankers.cohere import CohereRanker ranker CohereRanker(modelrerank-v3.5, top_k2) docs [Document(contentParis), Document(contentBerlin)] query What is the capital of germany? output ranker.run(queryquery, documentsdocs) docs output[documents]初始化参数参数类型默认值说明modelstrrerank-v3.5Cohere Rerank 模型名称top_kint10最多返回的文档数量api_keySecretCOHERE_API_KEY/CO_API_KEYCohere API 密钥api_base_urlstrhttps://api.cohere.comCohere API 基础地址meta_fields_to_embedlist[str] \| NoneNone需要拼接到文档内容中一起参与重排序的元数据字段meta_data_separatorstr\n拼接元数据与文档内容的分隔符max_tokens_per_docint4096每个文档参与重排序的最大 token 数run(query, documents, top_kNone)中top_k可选覆盖初始化值query为字符串、documents为文档列表返回按相似度降序排列的文档列表。若top_k不大于 0初始化与运行阶段都会抛出ValueError。top_k 的语义与性能调优CohereRanker在管道中常与检索器串联此时两个组件的top_k含义不同详见 cohereranker.mdx 的说明Retriever 的top_k决定召回多少文档交给下游Ranker 的top_k决定精排后输出多少文档若它是管道最后一个组件管道结果就是按 Ranker 的top_k截断的 top N。性能优化建议让检索器用较小的top_k如 10~20减少 Ranker 需要精排的文档量从而缩短整个管道的响应时间——因为 Rerank 的耗时与输入文档数量正相关。重排序管道示例以下管道先经InMemoryBM25Retriever做关键词召回再用CohereRanker做语义精排示例来自 cohereranker.mdxfrom haystack import Document, Pipeline from haystack.components.retrievers.in_memory import InMemoryBM25Retriever from haystack.document_stores.in_memory import InMemoryDocumentStore from haystack_integrations.components.rankers.cohere import CohereRanker docs [ Document(contentParis is in France), Document(contentBerlin is in Germany), Document(contentLyon is in France), ] document_store InMemoryDocumentStore() document_store.write_documents(docs) retriever InMemoryBM25Retriever(document_storedocument_store) ranker CohereRanker() document_ranker_pipeline Pipeline() document_ranker_pipeline.add_component(instanceretriever, nameretriever) document_ranker_pipeline.add_component(instanceranker, nameranker) document_ranker_pipeline.connect(retriever.documents, ranker.documents) query Cities in France res document_ranker_pipeline.run( data{ retriever: {query: query, top_k: 3}, ranker: {query: query, top_k: 2}, }, )这个关键词粗召回 语义精排的组合是构建高质量 RAG 问答的常见模式BM25 保证高召回Rerank 提升排序精度两者结合优于单一检索策略。组合成完整 RAG从索引到生成综合上述组件一个基于 Cohere 的完整 RAG 应用可以这样组织各环节的接线方式均已在前面章节给出完整代码索引阶段CohereDocumentEmbedder或CohereDocumentImageEmbedder→DocumentWriter向量写入文档存储检索阶段CohereTextEmbedder编码查询 →InMemoryEmbeddingRetriever召回候选文档精排阶段CohereRanker按语义相关度重排序并截断top_k生成阶段CohereChatGenerator结合检索结果与用户消息生成带引用的回答配合citation_quality参数控制引用精度。每个组件的生命周期方法warm_up/warm_up_async预热客户端、to_dict/from_dict序列化都由 Haystack 组件协议统一管理接入Pipeline后即可享受自动的组件图校验、并行执行与序列化能力。参考文档中列出的全部方法与签名均可对照 Cohere 集成 API 参考 及其配套组件文档CohereDocumentEmbedder、CohereTextEmbedder、CohereDocumentImageEmbedder、CohereChatGenerator、CohereRanker进一步查阅。【免费下载链接】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),仅供参考
分享:

看完干货,该让你的企业上线了

免费需求沟通 · 48 小时内出具建站方案 · 河南本地可上门