ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

Haystack 集成指南:通过 Ollama 实现本地向量化与对话生成(Embedder 与 ChatGenerator 全解)

Haystack 集成指南:通过 Ollama 实现本地向量化与对话生成(Embedder 与 ChatGenerator 全解) Haystack 集成指南通过 Ollama 实现本地向量化与对话生成Embedder 与 ChatGenerator 全解【免费下载链接】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本篇技术指南围绕 Haystack 官方 Ollama 集成展开系统讲解OllamaDocumentEmbedder、OllamaTextEmbedder与OllamaChatGenerator三个组件的 API 设计、初始化参数、运行方式与 Pipeline 集成方案。读者将掌握如何在完全本地的环境下完成文档向量化、语义检索与对话式生成并了解工具调用Tool Call、流式输出Streaming、结构化输出Structured Outputs与推理Thinking等高级能力的具体配置方法。1. 集成概览本地化 LLM 与向量化的接入方式Ollama 是一个专注于在本地运行大语言模型LLM的开源项目内部默认采用量化的 GGUF 格式。这意味着即使在没有 GPU 的标准机器上也可以运行 LLM而无需经历复杂的安装过程。Haystack 通过ollama-haystack集成包将 Ollama 的能力封装为标准 Haystack 组件使其能够无缝接入 RAG、语义搜索与 Agent 工作流。该集成在 2.22 版本中提供三个核心组件API 定义见 版本化 API 参考组件归属模块功能定位OllamaDocumentEmbedderhaystack_integrations.components.embedders.ollama计算一组Document的向量并写入每个文档的embedding字段OllamaTextEmbedderhaystack_integrations.components.embedders.ollama计算单个字符串的向量用于查询Query侧的语义检索OllamaChatGeneratorhaystack_integrations.components.generators.ollama.chat基于多轮ChatMessage历史完成对话式生成支持流式、工具调用、推理与结构化输出三者共同覆盖了「文档入库向量化 → 查询向量化 → 语义检索 → 对话生成」这一完整链路。所有组件默认连接http://localhost:11434这是 Mac、Linux 与 Docker 环境中最常见的 Ollama 服务端口。1.1 安装与运行前置条件使用该集成需要两步准备pip install ollama-haystack同时确保本机已有一个正在运行的 Ollama 实例本地安装或 Docker 容器均可。Ollama 自带 Embedding API因此向量化组件无需额外配置。快速启动 Ollama 的 Docker 方式docker run -d -p 11434:11434 --name ollama ollama/ollama:latest拉取所需模型以 Zephyr 为例# 使用 Docker 时 docker exec ollama ollama pull zephyr # Ollama 已直接安装在系统中时 ollama pull zephyr如需指定模型的量化版本可通过 tag 选择# ollama pull model:tag ollama pull zephyr:7b-alpha-q3_K_S2. OllamaDocumentEmbedder文档批量向量化OllamaDocumentEmbedder计算一组文档的向量并将结果存入每个Document的embedding字段。这些向量是后续嵌入检索Embedding Retrieval的基础——检索时查询向量会与文档向量进行比较以找出最相似的文档。完整说明与用例见 OllamaDocumentEmbedder 组件文档。在 Pipeline 中的典型位置索引 Pipeline 中、DocumentWriter之前。必填运行变量documents待向量化的文档列表。输出变量documents携带向量后的文档列表、meta元数据字典。2.1 独立使用from haystack import Document from haystack_integrations.components.embedders.ollama import OllamaDocumentEmbedder doc Document(contentWhat do llamas say once you have thanked them? No probllama!) document_embedder OllamaDocumentEmbedder() result document_embedder.run([doc]) print(result[documents][0].embedding) # Calculating embeddings: 100%|██████████| 1/1 [00:0200:00, 2.82s/it] # [-0.16412407159805298, -3.8359334468841553, ... ]2.2 构造函数与完整参数说明__init__( model: str nomic-embed-text, url: str http://localhost:11434, generation_kwargs: dict[str, Any] | None None, timeout: int 120, keep_alive: float | str | None None, prefix: str , suffix: str , progress_bar: bool True, meta_fields_to_embed: list[str] | None None, embedding_separator: str \n, batch_size: int 32, dimensions: int | None None, ) - None参数默认值说明modelnomic-embed-text使用的模型名称必须存在于正在运行的 Ollama 实例中。除默认模型外可选用 Ollama 模型库中的其他预构建模型或按照 Ollama 的 Modelfile 说明加载自定义模型urlhttp://localhost:11434运行中 Ollama 实例的 URLgeneration_kwargsNone传给 Ollama 生成端点的可选参数如temperature、top_p等可参考 Ollama Modelfile 文档中的「Valid Parameters and Values」章节timeout120抛出 Ollama API 超时错误前的等待秒数keep_aliveNone控制请求结束后模型在内存中的驻留时长。不设置时使用 Ollama 默认值5 分钟。可取值时长字符串如10m、24h秒数如3600任意负数表示常驻内存如-1或-1m0表示响应生成后立即卸载模型prefix附加到每段文本开头的字符串suffix附加到每段文本末尾的字符串progress_barTrue运行时是否显示进度条meta_fields_to_embedNone需要随文档文本一起向量化的元数据字段列表embedding_separator\n将元数据字段拼接到文档文本时使用的分隔符batch_size32一次处理的文档数量dimensionsNone期望的输出向量维度。仅对实现 Matryoshka Representation LearningMRL的模型有效如nomic-embed-text-v1.5、mxbai-embed-large、qwen3-embedding。为None默认时返回完整向量。需要ollama-python 0.6.22.3 生命周期方法warm_up() - None创建同步 Ollama 客户端供run()前预热使用。warm_up_async() - None创建异步 Ollama 客户端供run_async()前预热使用。close() - None关闭同步 Ollama 客户端。close_async() - None关闭异步 Ollama 客户端。2.4 run 与 run_asyncrun( documents: list[Document], generation_kwargs: dict[str, Any] | None None ) - dict[str, list[Document] | dict[str, Any]] run_async( documents: list[Document], generation_kwargs: dict[str, Any] | None None ) - dict[str, list[Document] | dict[str, Any]]documents需要转换为向量的文档列表。generation_kwargs每次调用时传给 Ollama 生成端点的可选参数如temperature、top_p等。返回值字典包含两个键——documents已附加 embedding 信息的文档与meta向量化过程中收集的元数据。2.5 元数据说明嵌入元数据中通常包含模型名称与类型信息且所用模型名会自动追加到文档元数据中。使用nomic-embed-text模型时的示例负载{meta: {model: nomic-embed-text}}2.6 在索引 Pipeline 中使用以下示例构建了一条完整的 PDF 索引 Pipeline转换 → 清洗 → 切分 → 向量化 → 写入文档库。from haystack import Pipeline from haystack_integrations.components.embedders.ollama import OllamaDocumentEmbedder from haystack.components.preprocessors import DocumentCleaner, DocumentSplitter from haystack.components.converters import PyPDFToDocument from haystack.components.writers import DocumentWriter from haystack.document_stores.types import DuplicatePolicy from haystack.document_stores.in_memory import InMemoryDocumentStore document_store InMemoryDocumentStore(embedding_similarity_functioncosine) embedder OllamaDocumentEmbedder( modelnomic-embed-text, urlhttp://localhost:11434, ) # 默认模型与 URL cleaner DocumentCleaner() splitter DocumentSplitter() file_converter PyPDFToDocument() writer DocumentWriter(document_storedocument_store, policyDuplicatePolicy.OVERWRITE) indexing_pipeline Pipeline() # 添加组件 indexing_pipeline.add_component(embedder, embedder) indexing_pipeline.add_component(converter, file_converter) indexing_pipeline.add_component(cleaner, cleaner) indexing_pipeline.add_component(splitter, splitter) indexing_pipeline.add_component(writer, writer) # 连接组件 indexing_pipeline.connect(converter, cleaner) indexing_pipeline.connect(cleaner, splitter) indexing_pipeline.connect(splitter, embedder) indexing_pipeline.connect(embedder, writer) # 运行 Pipeline indexing_pipeline.run({converter: {sources: [files/test_pdf_data.pdf]}}) # Calculating embeddings: 100%|██████████| 115/115 # {embedder: {meta: {model: nomic-embed-text}}, writer: {documents_written: 115}}3. OllamaTextEmbedder查询字符串向量化OllamaTextEmbedder计算单个字符串的向量用于查询Query侧的语义检索是 RAG 查询 Pipeline 中检索器之前的关键一环。完整说明见 OllamaTextEmbedder 组件文档。在 Pipeline 中的典型位置嵌入检索器Embedding Retriever之前。必填运行变量text字符串。输出变量embedding浮点数向量列表、meta元数据字典。3.1 独立使用from haystack_integrations.components.embedders.ollama import OllamaTextEmbedder embedder OllamaTextEmbedder() result embedder.run( textWhat do llamas say once you have thanked them? No probllama!, ) print(result[embedding])3.2 构造函数与完整参数说明__init__( model: str nomic-embed-text, url: str http://localhost:11434, generation_kwargs: dict[str, Any] | None None, timeout: int 120, keep_alive: float | str | None None, dimensions: int | None None, ) - None与OllamaDocumentEmbedder相比OllamaTextEmbedder的参数更精简没有prefix、suffix、progress_bar、meta_fields_to_embed、embedding_separator、batch_size。其中model、url、generation_kwargs、timeout的含义与文档向量化组件完全一致。keep_alive控制请求后模型在内存中的驻留时长取值规则与第 2.2 节相同时长字符串、秒数、负数常驻、0立即卸载。dimensions期望的输出向量维度仅对实现 MRL 的模型有效如nomic-embed-text-v1.5、mxbai-embed-large、qwen3-embeddingNone时返回完整向量。3.3 run 与 run_asyncrun( text: str, generation_kwargs: dict[str, Any] | None None ) - dict[str, list[float] | dict[str, Any]] run_async( text: str, generation_kwargs: dict[str, Any] | None None ) - dict[str, list[float] | dict[str, Any]]text需要转换为向量的文本。generation_kwargs传给 Ollama 生成端点的可选参数。返回值字典包含两个键——embedding计算得到的向量与meta向量化过程中收集的元数据。同时提供warm_up/warm_up_async创建同步/异步 Ollama 客户端与close/close_async关闭客户端。3.4 在语义检索 Pipeline 中使用以下示例展示了「文档向量化入库 查询向量化 嵌入检索」的完整闭环from haystack import Document from haystack import Pipeline from haystack.document_stores.in_memory import InMemoryDocumentStore from haystack_integrations.components.embedders.ollama import OllamaTextEmbedder, OllamaDocumentEmbedder from haystack.components.retrievers.in_memory import InMemoryEmbeddingRetriever 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), ] document_embedder OllamaDocumentEmbedder() documents_with_embeddings document_embedder.run(documents)[documents] document_store.write_documents(documents_with_embeddings) query_pipeline Pipeline() query_pipeline.add_component(text_embedder, OllamaTextEmbedder()) 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])4. OllamaChatGenerator本地对话式生成OllamaChatGenerator是为 Ollama 服务的模型提供的对话生成组件支持流式输出、工具调用、推理Thinking与结构化输出。它是构建本地 Agent 与对话式 RAG 应用的核心生成组件。完整说明见 OllamaChatGenerator 组件文档。在 Pipeline 中的典型位置ChatPromptBuilder之后。必填运行变量messagesChatMessage对象列表表示对话历史。输出变量repliesLLM 的回复列表。该组件通过ChatMessage数据类进行交互。ChatMessage包含消息内容、角色如user、assistant、system、tool以及可选元数据。4.1 独立使用from haystack_integrations.components.generators.ollama import OllamaChatGenerator from haystack.dataclasses import ChatMessage generator OllamaChatGenerator( modelzephyr, urlhttp://localhost:11434, generation_kwargs{ num_predict: 100, temperature: 0.9, }, ) messages [ ChatMessage.from_system(\nYou are a helpful, respectful and honest assistant), ChatMessage.from_user(Whats Natural Language Processing?), ] print(generator.run(messagesmessages))运行结果中replies为ChatMessage列表其中_meta会携带model等生成元数据。4.2 构造函数与完整参数说明__init__( model: str qwen3:0.6b, url: str http://localhost:11434, generation_kwargs: dict[str, Any] | None None, timeout: int 120, max_retries: int 0, keep_alive: float | str | None None, streaming_callback: Callable[[StreamingChunk], None] | None None, tools: ToolsType | None None, response_format: None | Literal[json] | JsonSchemaValue | None None, think: bool | Literal[low, medium, high] False, ) - None参数默认值说明modelqwen3:0.6b使用的模型名称必须已存在于运行中的 Ollama 实例即已 pull 完成urlhttp://localhost:11434Ollama 服务器的 Base URLgeneration_kwargsNone传给 Ollama 生成端点的可选参数如temperature、top_p等timeout120Ollama API 超时抛错前的等待秒数max_retries0请求失败HTTP 429、5xx、连接/超时错误时的最大重试次数使用指数退避策略0默认表示禁用重试keep_aliveNone模型驻留内存时长取值规则同前时长字符串、秒数、负数常驻、0立即卸载streaming_callbackNone收到新 token 时被调用的回调函数接收StreamingChunk作为参数toolsNone供模型准备调用的Tool和/或Toolset对象列表也可以是单个Toolset。每个工具需有唯一名称。并非所有模型都支持工具调用response_formatNone结构化输出的格式控制。None不施加任何结构按原样返回json响应格式化为 JSON 对象JSON Schema响应格式化为符合指定 Schema 的 JSON 对象需要 Ollama ≥ 0.1.34thinkFalse若为True模型在产出响应前会先「思考」。仅支持推理型模型部分模型如 gpt-oss支持low、medium、high不同思考级别。中间思考内容可通过返回ChatMessage的reasoning属性查看4.3 run 与 run_asyncrun( messages: list[ChatMessage] | str, generation_kwargs: dict[str, Any] | None None, tools: ToolsType | None None, *, streaming_callback: StreamingCallbackT | None None ) - dict[str, list[ChatMessage]] run_async( messages: list[ChatMessage] | str, generation_kwargs: dict[str, Any] | None None, tools: ToolsType | None None, *, streaming_callback: StreamingCallbackT | None None ) - dict[str, list[ChatMessage]]messagesChatMessage实例列表如果传入字符串会自动转换为包含一条 user 角色ChatMessage的列表。generation_kwargs单次调用的 Ollama 推理选项覆盖项会合并到实例级generation_kwargs之上。tools供模型准备调用的工具集合若设置将覆盖初始化时的tools参数。streaming_callback接收StreamingChunk的可调用对象。在此处或构造函数中提供回调都会使组件进入流式模式。返回值字典包含键replies——模型回复的ChatMessage列表。组件还提供to_dict()与from_dict(data)用于序列化/反序列化后者为类方法返回反序列化后的OllamaChatGenerator以及warm_up/warm_up_async、close/close_async生命周期方法。4.4 工具调用Tool SupportOllamaChatGenerator通过tools参数支持函数调用可接受灵活的配置形态Tool 对象列表将单个工具作为列表传入单个 Toolset直接传入整个 Toolset混合 Tools 与 Toolsets在同一个列表中组合多个 Toolset 与独立工具。这允许将相关工具组织为逻辑分组同时按需加入独立工具from haystack.tools import Tool, Toolset from haystack_integrations.components.generators.ollama import OllamaChatGenerator # 创建独立工具 weather_tool Tool( nameweather, descriptionGet weather info, parameters..., function... ) news_tool Tool( namenews, descriptionGet latest news, parameters..., function... ) # 将相关工具归组为 toolset math_toolset Toolset([add_tool, subtract_tool, multiply_tool]) # 混合传入 toolsets 与独立工具 generator OllamaChatGenerator( modelllama2, tools[math_toolset, weather_tool, news_tool], # Toolset 与 Tool 的混合 )4.5 流式输出Streaming通过streaming_callback即可启用流式输出。推荐使用内置的print_streaming_chunk打印文本 token 与工具事件工具调用与工具结果from haystack.components.generators.utils import print_streaming_chunk # 为任意 Generator/ChatGenerator 配置流式回调 component SomeGeneratorOrChatGenerator(streaming_callbackprint_streaming_chunk) # 如果是 ChatGenerator传入消息列表 # from haystack.dataclasses import ChatMessage # component.run([ChatMessage.from_user(Your question here)]) # 如果是普通 Generator传入 prompt # component.run({prompt: Your prompt here})需要注意流式仅适用于单一响应场景若供应商支持多个候选结果需设置n1。默认优先使用print_streaming_chunk只有需要特定传输方式如 SSE/WebSocket或自定义 UI 格式化时才编写自定义回调。流式还可以与工具调用组合使用同时传入tools与streaming_callback后当模型决定调用工具时流式 chunk 会携带工具调用增量tool-call deltas而非文本 token最终重建的ChatMessage会在replies[0]上暴露完整的tool_calls列表from haystack.dataclasses import ChatMessage from haystack.dataclasses.streaming_chunk import StreamingChunk from haystack.tools import create_tool_from_function from haystack_integrations.components.generators.ollama import OllamaChatGenerator def get_weather(city: str) - str: Get current weather for a city. return fSunny, 22°C in {city} def callback(chunk: StreamingChunk) - None: if chunk.tool_calls: print(f[tool delta] {chunk.tool_calls}) elif chunk.content: print(chunk.content, end, flushTrue) generator OllamaChatGenerator( modelllama3.1:8b, streaming_callbackcallback, tools[create_tool_from_function(get_weather)], ) result generator.run([ChatMessage.from_user(What is the weather in Berlin?)]) print(result[replies][0].tool_calls)4.6 多模态输入支持将图片内容以ImageContent的形式传入消息以llava多模态模型为例from haystack.dataclasses import ChatMessage, ImageContent from haystack_integrations.components.generators.ollama import OllamaChatGenerator llm OllamaChatGenerator(modelllava, urlhttp://localhost:11434) image ImageContent.from_file_path(apple.jpg) 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.4.7 在对话 Pipeline 中使用将OllamaChatGenerator与ChatPromptBuilder组合可实现基于模板的对话生成from haystack.components.builders import ChatPromptBuilder from haystack_integrations.components.generators.ollama import OllamaChatGenerator from haystack.dataclasses import ChatMessage from haystack import Pipeline # 不传入参数初始化运行时无需模板变量 prompt_builder ChatPromptBuilder() generator OllamaChatGenerator( modelzephyr, urlhttp://localhost:11434, generation_kwargs{temperature: 0.9}, ) pipe Pipeline() pipe.add_component(prompt_builder, prompt_builder) pipe.add_component(llm, generator) pipe.connect(prompt_builder.prompt, llm.messages) location Berlin messages [ ChatMessage.from_system(Always respond in Spanish even if some input data is in other languages.), ChatMessage.from_user(Tell me about {{location}}), ] print(pipe.run(data{ prompt_builder: { template_variables: {location: location}, template: messages, } }))运行结果中的replies为模型按模板变量生成的ChatMessage列表_meta中携带model信息。5. 实战组合本地 RAG 全流程将上述组件组合即可在纯本地环境下搭建完整的 RAG 应用用OllamaDocumentEmbedder完成文档入库向量化用OllamaTextEmbedder 检索器完成查询召回最后用OllamaChatGenerator基于召回上下文生成答案。from haystack import Pipeline, Document from haystack_integrations.components.embedders.ollama import ( OllamaDocumentEmbedder, OllamaTextEmbedder, ) from haystack_integrations.components.generators.ollama import OllamaChatGenerator from haystack.components.retrievers.in_memory import InMemoryEmbeddingRetriever from haystack.components.builders import ChatPromptBuilder from haystack.document_stores.in_memory import InMemoryDocumentStore from haystack.dataclasses import ChatMessage # 1) 准备文档库并向量化 document_store InMemoryDocumentStore(embedding_similarity_functioncosine) docs [ Document(contentHaystack is an open-source AI orchestration framework.), Document(contentOllama runs LLMs locally using quantized GGUF format.), ] document_embedder OllamaDocumentEmbedder(modelnomic-embed-text) document_store.write_documents(document_embedder.run(docs)[documents]) # 2) 构建查询 Pipeline向量化 - 检索 retrieval_pipeline Pipeline() retrieval_pipeline.add_component(query_embedder, OllamaTextEmbedder(modelnomic-embed-text)) retrieval_pipeline.add_component(retriever, InMemoryEmbeddingRetriever(document_storedocument_store)) retrieval_pipeline.connect(query_embedder.embedding, retriever.query_embedding) # 3) 组装生成 Pipeline模板 - 对话生成 prompt_builder ChatPromptBuilder() llm OllamaChatGenerator(modelzephyr, generation_kwargs{temperature: 0.7}) rag_pipeline Pipeline() rag_pipeline.add_component(prompt_builder, prompt_builder) rag_pipeline.add_component(llm, llm) rag_pipeline.connect(prompt_builder.prompt, llm.messages) query What format does Ollama use? hits retrieval_pipeline.run({query_embedder: {text: query}})[retriever][documents] context \n.join(d.content for d in hits) messages [ ChatMessage.from_system(Answer based only on the provided context.), ChatMessage.from_user(fContext:\n{context}\n\nQuestion: {query}), ] result rag_pipeline.run({prompt_builder: {template: messages}}) print(result[llm][replies][0].text)6. 版本差异与注意事项默认模型差异2.22 版本的OllamaChatGenerator默认模型为qwen3:0.6b而更早版本如 2.18 系列默认使用orca-miniOllamaDocumentEmbedder与OllamaTextEmbedder默认模型为nomic-embed-text。使用时建议显式指定model与url避免依赖默认值。dimensions参数仅对支持 MRL 的模型有效且要求ollama-python 0.6.2旧版本客户端可能无法识别该参数。response_format的 JSON Schema 模式需要 Ollama 服务端版本 ≥ 0.1.34。工具调用兼容性并非所有模型都支持工具调用使用前应确认所选模型具备工具能力每个工具的名称必须唯一。流式模式限制流式仅支持单一响应多候选场景需显式设置n1。7. 小结通过ollama-haystack集成Haystack 可以完全在本地完成从文档向量化OllamaDocumentEmbedder到查询向量化OllamaTextEmbedder、再到对话生成OllamaChatGenerator的完整 AI 应用链路。三者共享 Ollama 生态keep_alive控制模型驻留、generation_kwargs透传推理参数、timeout与max_retries保障稳定性。对话组件更可叠加工具调用、流式输出、多模态输入、结构化输出与推理能力为构建本地优先的 RAG 应用与 Agent 工作流提供了完整支撑。相关组件的详细 API 签名可继续查阅 版本 2.22 的 Ollama 集成 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),仅供参考
返回列表