十年匠心定制 · 商业建站与技术教学双线并行 咨询热线:400-886-1026 service@lmnt.cn
ARTICLE DETAIL

资讯详情

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

Haystack × Ollama 集成指南:OllamaDocumentEmbedder、OllamaTextEmbedder 与 OllamaChatGenerator 实战解析

Haystack × Ollama 集成指南:OllamaDocumentEmbedder、OllamaTextEmbedder 与 OllamaChatGenerator 实战解析 Haystack × Ollama 集成指南OllamaDocumentEmbedder、OllamaTextEmbedder 与 OllamaChatGenerator 实战解析【免费下载链接】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/haystackHaystack 官方集成文档integrations-api/ollama.md系统性地收录了 Ollama 生态的三个核心组件OllamaDocumentEmbedder、OllamaTextEmbedder与OllamaChatGenerator。本文以此为骨架结合仓库内的组件使用文档与 API 参考深入讲解每个组件的初始化参数、run调用签名、同步/异步生命周期以及如何将它们接入索引管道与 RAG 查询管道帮助你完全掌握本地大模型 Haystack 编排的实战路径。Ollama 是一个专注于本地运行 LLM 的开源项目默认使用量化 GGUF 格式因此即使在无 GPU 的普通机器上也能运行主流模型且无需复杂安装流程。Haystack 通过ollama-haystack集成包将 Ollama 提供的 embedding 与 chat completion 能力封装为标准的 Haystack 组件可直接嵌入Pipeline中与文档转换、清洗、切分、写入、检索等组件无缝衔接。环境准备安装与启动 Ollama在使用任意 Ollama 组件之前需要完成两项准备工作。第一步安装ollama-haystack集成包pip install ollama-haystack第二步准备一个正在运行的 Ollama 实例Ollama 既可以本机安装也可以通过 Docker 快速启动docker run -d -p 11434:11434 --name ollama ollama/ollama:latest随后拉取所需的模型以 zephyr 为例本机安装则直接执行ollama pull zephyrdocker exec ollama ollama pull zephyr如需指定量化版本可以使用 tag 精确拉取# ollama pull model:tag ollama pull zephyr:7b-alpha-q3_K_S需要注意OllamaChatGenerator所需的对话模型必须已 pull 到运行中的 Ollama 实例中embedding 组件所需的嵌入模型默认nomic-embed-text同理。所有组件默认连接http://localhost:11434因为大多数环境Mac、Linux、Docker的默认端口均为 11434。文档嵌入OllamaDocumentEmbedderOllamaDocumentEmbedder计算一组Document的嵌入向量并将结果写入每个 Document 的embedding字段。它在索引管道中通常位于DocumentWriter之前参见 documentwriter.mdx文档向量是后续 embedding 检索的必要前提检索阶段会用查询向量与文档向量比较找出最相似的相关文档。初始化参数详解__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 实例中可用urlhttp://localhost:11434运行中的 Ollama 实例 URLgeneration_kwargsNone传递给 Ollama generation 端点的可选参数如temperature、top_p等有效参数见 Ollama Modelfile 文档timeout120抛出 Ollama API 超时错误前的等待秒数keep_aliveNone控制请求后模型在内存中驻留时长未设置时使用 Ollama 默认值5 分钟prefix添加在每段文本开头的字符串suffix添加在每段文本末尾的字符串progress_barTrue为True时运行中显示进度条meta_fields_to_embedNone需随文档文本一起嵌入的元数据字段列表embedding_separator\n拼接元数据字段与文档文本时使用的分隔符batch_size32一次处理的文档数量dimensionsNone嵌入输出期望的向量维度其中keep_alive的取值规则较为灵活支持四类值时长字符串如10m、24h秒数如3600任意负数表示让模型一直驻留内存如-1或-1m0表示响应生成后立即卸载模型。dimensions参数仅对实现了 Matryoshka Representation LearningMRL的模型生效例如nomic-embed-text-v1.5、mxbai-embed-large、qwen3-embedding。设置为None默认时返回完整向量该特性要求ollama-python 0.6.2。meta_fields_to_embed与embedding_separator的组合允许把元数据如标题、来源拼入文本一起编码从而提升检索语义相关性。run 与生命周期方法run( documents: list[Document], generation_kwargs: dict[str, Any] | None None ) - dict[str, list[Document] | dict[str, Any]]参数documents待计算嵌入的 Document 列表参数generation_kwargs可选的按次调用端点参数覆盖或补充初始化时的配置返回字典包含两个键documents已附加嵌入信息的文档列表与meta嵌入过程中收集的元数据。组件同时提供run_async异步版本以及用于创建/销毁底层客户端的生命周期方法warm_up()创建同步 Ollama 客户端warm_up_async()创建异步 Ollama 客户端close()关闭同步客户端close_async()关闭异步客户端。独立使用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, ... ]输出中的meta会自动带上模型名例如使用 nomic-embed-text 时形如{meta: {model: nomic-embed-text}}。接入索引管道将 OllamaDocumentEmbedder 与转换、清洗、切分、写入组件串联即可构建一条完整的本地索引管道完整示例见 ollamadocumentembedder.mdxfrom 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) 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}}文本嵌入OllamaTextEmbedderOllamaTextEmbedder计算单个字符串的嵌入向量通常放在 embeddingRetriever之前参见 retrievers.mdx用于把查询query转换为向量再由检索器据此查找相关文档。如果需要嵌入一批文档则应使用OllamaDocumentEmbedder。初始化参数详解__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完全一致model默认nomic-embed-text、url默认http://localhost:11434、timeout默认 120 秒generation_kwargs透传给 Ollama 端点keep_alive支持时长字符串、秒数、负数常驻内存与0立即卸载dimensions仅对支持 MRL 的模型如nomic-embed-text-v1.5、mxbai-embed-large、qwen3-embedding生效None时返回完整向量。run 与生命周期方法run( text: str, generation_kwargs: dict[str, Any] | None None ) - dict[str, list[float] | dict[str, Any]]参数text待嵌入的字符串返回字典包含embedding计算得到的向量float 列表与meta嵌入过程收集的元数据同样会自动包含模型名。组件同样提供run_async异步版本及warm_up/warm_up_async/close/close_async生命周期方法。独立使用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])构建完整的本地 RAG 查询管道将两个 embedding 组件配合InMemoryDocumentStore与InMemoryEmbeddingRetriever即可实现本地向量化 检索的闭环完整示例见 ollamatextembedder.mdxfrom haystack import Document from haystack import Pipeline from haystack.document_stores.in_memory import InMemoryDocumentStore from haystack_integrations.components.embedders.ollama import ( OllamaDocumentEmbedder, OllamaTextEmbedder, ) 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])对话生成OllamaChatGeneratorOllamaChatGenerator是面向 Ollama 服务的 Haystack Chat Generator支持流式输出、工具调用、推理thinking与结构化输出。它接收ChatMessage对象进行多轮对话在管道中通常位于ChatPromptBuilder之后参见 chatpromptbuilder.mdx。ChatMessage是包含消息内容、角色user、assistant、system、tool与可选元数据的数据类详见 chatmessage.mdx。初始化参数详解__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使用的模型名必须已 pull 到运行中的 Ollama 实例urlhttp://localhost:11434Ollama 服务器基础 URLgeneration_kwargsNone透传给 Ollama 生成端点的可选参数如temperature、top_ptimeout120抛出 Ollama API 超时错误前的秒数max_retries0失败请求HTTP 429、5xx、连接/超时错误的最大重试次数采用指数退避设为 0默认禁用重试keep_aliveNone模型驻留内存时长控制取值规则与 embedding 组件一致streaming_callbackNone收到新 token 时被调用的回调函数接收StreamingChunk参数toolsNone可供模型调用准备的Tool和/或Toolset对象列表或单个Toolset每个工具名须唯一。并非所有模型支持工具response_formatNone结构化输出格式见下文thinkFalse若为True模型在产出响应前先思考仅思考型模型支持部分模型如 gpt-oss支持low、medium、high不同思考级别。中间思考输出可通过返回ChatMessage的reasoning属性查看response_format支持三种取值None不施加任何结构约束响应原样返回json响应格式化为 JSON 对象JSON SchemaJsonSchemaValue响应按指定 JSON Schema 格式化为 JSON 对象需要 Ollama ≥ 0.1.34。run、run_async 与序列化run( messages: list[ChatMessage] | str, generation_kwargs: dict[str, Any] | None None, tools: ToolsType | None None, *, streaming_callback: StreamingCallbackT | None None ) - dict[str, list[ChatMessage]]messages输入消息的ChatMessage列表若传入字符串会被转换为包含一条 user 角色消息的列表generation_kwargs按次调用覆盖会与实例级generation_kwargs合并tools若设置将覆盖初始化时的tools参数streaming_callback在构造函数或此处提供回调都会使组件进入流式模式返回字典包含键replies模型响应的ChatMessage列表。run_async为run的异步版本签名一致。此外该组件还实现了to_dict()/from_dict()序列化接口可配合 Haystack 的 YAML/JSON 管道序列化机制使用。独立使用from haystack_integrations.components.generators.ollama.chat import OllamaChatGenerator from haystack.dataclasses import ChatMessage llm OllamaChatGenerator(modelqwen3:0.6b) result llm.run(messages[ChatMessage.from_user(What is the capital of France?)]) print(result)带系统提示词与生成参数控制的完整示例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( # _roleChatRole.ASSISTANT: assistant, # _content[TextContent(textNatural Language Processing (NLP) is a subfield of ...)], # _meta{model: zephyr, ...} # ) # ] # }多模态输入Ollama 的视觉模型如llava支持图像输入配合 Haystack 的ImageContent数据类即可完成多模态问答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.工具调用Function Calling通过tools参数可以启用函数调用它接受三种灵活的配置形态详细机制见 tool.mdx 与 toolset.mdxTool 对象列表逐个传入独立工具单个 Toolset直接传入整个 ToolsetTool 与 Toolset 混合列表在同一个列表中组合多个 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]) # 混合传入 toolset 与独立工具 generator OllamaChatGenerator( modelllama2, tools[math_toolset, weather_tool, news_tool], )流式输出Streaming通过streaming_callback参数可以按 token 流式接收输出。可以优先使用 Haystack 内置的print_streaming_chunk同时打印文本 token 与工具事件仅在需要特定传输方式如 SSE/WebSocket或自定义 UI 时才编写自定义回调详见 choosing-the-right-generator.mdx。from haystack.components.generators.utils import print_streaming_chunk component SomeGeneratorOrChatGenerator(streaming_callbackprint_streaming_chunk)需要注意流式模式仅支持单个响应若提供方支持多候选应设置n1。流式 工具调用组合流式可以与工具调用同时使用。同时传入tools与streaming_callback后当模型决定调用工具时流式 chunk 携带的是工具调用增量而非文本 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, generation_kwargs{temperature: 0.0}, tools[create_tool_from_function(get_weather)], streaming_callbackcallback, ) response generator.run( messages[ ChatMessage.from_user( Whats the weather in Berlin? Use the get_weather tool., ), ], ) # 最终重建的消息tool_calls 已填充text 为 None assistant_message response[replies][0] print(assistant_message.tool_calls) # - [ToolCall(tool_nameget_weather, arguments{city: Berlin}, ...)]在管道中使用将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, } } ) )组件选型速查组件输入输出典型位置OllamaDocumentEmbedderdocuments: list[Document]documents带嵌入、meta索引管道中DocumentWriter之前OllamaTextEmbeddertext: strembeddingfloat 列表、meta查询/RAG 管道中 embeddingRetriever之前OllamaChatGeneratormessagesChatMessage 列表或字符串repliesChatMessage 列表对话管道中ChatPromptBuilder之后三者共用同一套 Ollama 连接约定默认 URLhttp://localhost:11434、timeout120、keep_alive四类取值并统一遵循 Haystack 的warm_up/close生命周期与run_async异步接口因此可以自然地混合编排用两个 embedding 组件构建本地向量索引与检索再用 ChatGenerator 基于检索结果完成生成式问答。延伸阅读完整 API 参考integrations-ollama组件使用文档ollamadocumentembedder.mdx、ollamatextembedder.mdx、ollamachatgenerator.mdx选型对比choosing-the-right-embedder.mdx、choosing-the-right-generator.mdx快速上手Ollama 集成入门可参考 get-started.mdx【免费下载链接】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),仅供参考
返回列表