Haystack Ollama 集成指南:本地 LLM 嵌入与 Chat 生成全解析
2026/9/13 13:16:44 网站建设 项目流程

Haystack Ollama 集成指南:本地 LLM 嵌入与 Chat 生成全解析

【免费下载链接】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

导读

Ollama 是目前在本地机器上运行开源 LLM 最流行的方案之一,它默认使用量化后的 GGUF 格式,让开发者即使没有 GPU 也能在普通机器上跑起 LLM。Haystack 通过ollama-haystack集成包,将 Ollama 的嵌入模型与 Chat 模型无缝接入 Pipeline:OllamaDocumentEmbedder/OllamaTextEmbedder负责把文档和查询转为向量以支撑向量检索(RAG),OllamaChatGenerator则负责完成本地化的对话生成,并支持流式输出、工具调用、思考模式与结构化输出。读完本文,你将掌握这三个组件的完整参数体系、独立运行与 Pipeline 集成方式,以及背后的实现原理。

本文基于 docs-website/reference_versioned_docs/version-2.19/integrations-api/ollama.md 展开,并辅以同仓库内对应的组件文档(如 ollamadocumentembedder.mdx、ollamachatgenerator.mdx)与 Haystack 核心源码进行印证。


一、集成概览:安装与前置条件

Ollama 集成由独立的 Python 包ollama-haystack提供,不属于 Haystack 核心库。安装方式:

pip install ollama-haystack

在使用任何组件之前,需要确保本机有一个正在运行的 Ollama 实例。安装 Ollama 有两种常见方式:

  • 直接安装到本机系统(macOS、Linux、Windows 均支持);
  • 使用 Docker 快速启动:
docker run -d -p 11434:11434 --name ollama ollama/ollama:latest

之后拉取所需的模型。以 Zephyr 为例:

# 使用 Docker 时 docker exec ollama ollama pull zephyr # 本机已安装 Ollama 时 ollama pull zephyr

提示:选择模型的特定量化版本。Ollama 模型库的模型卡片会列出可用 tag,可以用model:tag语法拉取指定的量化版本,例如ollama pull zephyr:7b-alpha-q3_K_S。更小的量化(如 q3_K_S)占用内存更少、推理更快,但精度会略有下降。

由于 Ollama 本身就内置了 embedding API 与 chat API,安装ollama-haystack之后无需额外配置即可使用。绝大多数环境(Mac、Linux、Docker)下 Ollama 服务默认监听http://localhost:11434,这也是三个组件的默认url


二、OllamaDocumentEmbedder:为文档批量计算向量

OllamaDocumentEmbedder计算一组Document的嵌入向量,并把结果写入每个文档的embedding字段。这些向量是执行向量检索的前提——检索时,查询向量会与文档向量做相似度比较,找出最相关的文档。它通常出现在索引 Pipeline 中、DocumentWriter之前。

2.1 独立使用

from haystack import Document from haystack_integrations.components.embedders.ollama import OllamaDocumentEmbedder doc = Document(content="What 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:02<00:00, 2.82s/it] # [-0.16412407159805298, -3.8359334468841553, ... ]

2.2 构造参数全解析

OllamaDocumentEmbedder.__init__的完整签名(来自参考文档):

__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
参数类型默认值说明
modelstr"nomic-embed-text"使用的嵌入模型名称,必须是当前 Ollama 实例中已存在的模型
urlstr"http://localhost:11434"运行中的 Ollama 实例地址
generation_kwargsdict[str, Any] \| NoneNone透传给 Ollama 生成端点的可选参数(如temperaturetop_p等),可参考 Ollama Modelfile 文档中的合法参数表
timeoutint120从 Ollama API 抛出超时错误前的等待秒数
keep_alivefloat \| str \| NoneNone控制请求结束后模型在内存中驻留的时长,未设置时使用 Ollama 默认值(5 分钟)
prefixstr""追加到每段文本开头的字符串
suffixstr""追加到每段文本结尾的字符串
progress_barboolTrue运行时是否显示进度条
meta_fields_to_embedlist[str] \| NoneNone需要连同文档正文一起参与嵌入的元数据字段列表
embedding_separatorstr"\n"将元数据字段与文档正文拼接时使用的分隔符
batch_sizeint32每批处理的文档数量
dimensionsint \| NoneNone期望输出的嵌入向量维度,仅支持实现了 Matryoshka Representation Learning(MRL)的模型

keep_alive的取值规则需要特别说明:

  • 时长字符串:如"10m""24h"
  • 秒数:如3600
  • 任意负数:使模型在响应生成后持续驻留内存,如-1"-1m"
  • '0':生成响应后立即将模型从内存卸载。

dimensions参数只在实现 MRL(Matryoshka Representation Learning,嵌套向量表示学习)的模型中生效,参考文档点名的模型包括nomic-embed-text-v1.5mxbai-embed-largeqwen3-embedding。MRL 允许在不重新训练的情况下按需截取向量维度(例如把 1024 维截断为 256 维),从而显著降低存储与检索成本;当dimensions=None(默认)时返回完整向量。文档还注明该参数要求ollama-python >= 0.6.2

2.3 元数据嵌入与输出结构

通过meta_fields_to_embed可以让文档的部分元数据参与嵌入,使相似度检索能够感知元数据语义。拼接规则是:元数据字段值与文档正文之间用embedding_separator(默认换行"\n")连接;prefixsuffix则分别加在每段文本的最前与最后。

run(documents, generation_kwargs=None)的返回值为字典,包含两个键:

  • documents:已附加嵌入向量的文档列表;
  • meta:嵌入过程中收集的元数据。

其中meta会自动带上使用的模型名,例如使用nomic-embed-text时输出{"meta": {"model": "nomic-embed-text"}}run也支持在调用时通过generation_kwargs传入覆盖实例级参数的推理选项。

2.4 索引 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_function="cosine") embedder = OllamaDocumentEmbedder( model="nomic-embed-text", url="http://localhost:11434", ) # 这是默认模型与默认 URL cleaner = DocumentCleaner() splitter = DocumentSplitter() file_converter = PyPDFToDocument() writer = DocumentWriter(document_store=document_store, policy=DuplicatePolicy.OVERWRITE) indexing_pipeline = 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}}

注意InMemoryDocumentStore显式指定了embedding_similarity_function="cosine",这样后续检索时使用余弦相似度比较向量。关于 Pipeline 的完整组件能力,可参考 haystack/core/pipeline 目录下的实现。

2.5 生命周期方法

  • warm_up():创建同步 Ollama 客户端(在 Pipeline 首次运行前预加载,避免运行时才初始化造成延迟);
  • warm_up_async():创建异步 Ollama 客户端;
  • close():关闭同步客户端,释放连接资源;
  • close_async():关闭异步客户端。

run_async()则是对应run()的异步版本,用于在异步 Pipeline 中调用。这与 Haystack 核心库中AsyncPipeline并入Pipeline的设计一致(可参考 releasenotes 中 Merge-AsyncPipeline-into-Pipeline-73c83002fd647297.yaml)。


三、OllamaTextEmbedder:为查询字符串计算向量

OllamaTextEmbedder计算单个字符串的嵌入向量。在 RAG 查询 Pipeline 中,它通常位于嵌入检索器(如InMemoryEmbeddingRetriever)之前:先用它将用户查询转成向量,再交给检索器与文档向量比对。需要嵌入一批文档时则改用OllamaDocumentEmbedder

3.1 独立使用

from haystack_integrations.components.embedders.ollama import OllamaTextEmbedder embedder = OllamaTextEmbedder() result = embedder.run( text="What 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相比,Text 版本参数更精简,去掉了与"批量文档"相关的prefixsuffixprogress_barmeta_fields_to_embedembedding_separatorbatch_size,保留并共享相同的核心参数语义:

  • model:默认"nomic-embed-text"
  • url:默认"http://localhost:11434"
  • generation_kwargs:透传的推理选项(temperaturetop_p等);
  • timeout:默认 120 秒;
  • keep_alive:模型内存驻留时长,规则与 Document 版本完全一致(时长字符串 / 秒数 / 负数常驻 /'0'立即卸载);
  • dimensions:MRL 模型的期望向量维度,None时返回完整向量。

3.3 输出结构

run(text, generation_kwargs=None)返回字典:

  • embedding:计算得到的嵌入向量(list[float]);
  • meta:嵌入过程的元数据,同样自动包含模型名(如{"model": "nomic-embed-text"})。

run_async提供异步等价实现。

3.4 RAG 查询 Pipeline 实战

下面的示例同时演示两个 Embedder 的配合:先用OllamaDocumentEmbedder为文档建索引,再用OllamaTextEmbedder编码查询并检索。

from 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_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"), ] 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_store=document_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])

这里query_pipeline.connect("text_embedder.embedding", "retriever.query_embedding")将查询向量直接接到检索器的query_embedding输入,是 Haystack 管道式连接的标准写法。


四、OllamaChatGenerator:本地 LLM 对话生成

OllamaChatGenerator是面向运行在 Ollama 上的 LLM(如llama2mixtralqwen3)的 Chat 生成组件。它基于ChatMessage对象工作——ChatMessage是 Haystack 的数据类,包含消息内容、角色(userassistantsystemtool)与可选元数据,定义见 haystack/dataclasses/chat_message.py(其中from_userfrom_system等工厂方法用于快速构造消息)。

它默认使用"qwen3:0.6b"模型和"http://localhost:11434"地址。除基本的对话生成外,参考文档明确指出它支持**流式输出(streaming)、工具调用(tool calls)、推理思考(reasoning)与结构化输出(structured outputs)**四大进阶能力。

4.1 独立使用

from haystack_integrations.components.generators.ollama.chat import OllamaChatGenerator from haystack.dataclasses import ChatMessage llm = OllamaChatGenerator(model="qwen3:0.6b") result = llm.run(messages=[ChatMessage.from_user("What is the capital of France?")]) print(result)

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
参数类型默认值说明
modelstr"qwen3:0.6b"模型名称,必须是当前 Ollama 实例中已 pull 的模型
urlstr"http://localhost:11434"Ollama 服务的基础地址
generation_kwargsdict[str, Any] \| NoneNone透传推理选项(temperaturetop_p等)
timeoutint120API 超时秒数
max_retriesint0失败请求(HTTP 429、5xx、连接/超时错误)的最大重试次数,采用指数退避;0表示禁用重试
keep_alivefloat \| str \| NoneNone模型内存驻留时长,规则同 Embedder
streaming_callbackCallable[[StreamingChunk], None] \| NoneNone每收到一个新 token 时被调用的回调函数,参数为StreamingChunk
toolsToolsType \| NoneNone可供模型发起调用的Tool/Toolset对象(可混合传入列表),每个工具需有唯一名称;并非所有模型支持工具调用
response_formatNone \| "json" \| JsonSchemaValueNone结构化输出格式
thinkbool \| "low" \| "medium" \| "high"False是否开启"思考"模式,仅思考型模型支持

关键参数详解:

max_retries:参考文档明确其作用于 HTTP 429、5xx 以及连接/超时错误,采用指数退避策略;默认0关闭重试。在本地网络不稳定或模型首次加载较慢时,适当调大该值可提升健壮性。

think(思考模式):设为True时,模型会在产出回答前先进行"思考",仅 [thinking models] 支持。部分模型(如 gpt-oss)支持"low"/"medium"/"high"三档思考强度。思考过程的中间输出可通过返回的ChatMessagereasoning属性查看——这与 Haystack 的StreamingChunk/ChatMessage中对reasoning内容的建模一脉相承(见 haystack/dataclasses/streaming_chunk.py 中的reasoning字段)。

response_format(结构化输出)

  • None:不对响应施加结构,原样返回;
  • "json":强制模型输出 JSON 对象;
  • JSON Schema:按指定 JSON Schema 约束输出(要求 Ollama ≥ 0.1.34)。

tools(工具调用)ToolsType在 Haystack 核心中的定义是Sequence[Tool | Toolset] | Toolset(见 haystack/tools/tool_types.py),即可以传入单个ToolsetTool列表,或 Tool 与 Toolset 混合的列表。Toolset的定义位于 haystack/tools/toolset.py,而create_tool_from_function可以将普通 Python 函数一键包装为 Tool(见 haystack/tools/from_function.py)。

4.3 工具调用(Function Calling)

支持三种灵活的传参方式:

  • Tool 对象列表:把单个工具作为列表元素传入;
  • 单个 Toolset:直接传入整个工具集;
  • 混合 Tools 与 Toolsets:在同一列表中组合多个 Toolset 与独立 Tool。
from haystack.tools import Tool, Toolset from haystack_integrations.components.generators.ollama import OllamaChatGenerator # 创建独立工具 weather_tool = Tool( name="weather", description="Get weather info", parameters=..., function=... ) news_tool = Tool( name="news", description="Get latest news", parameters=..., function=... ) # 将相关工具归组为 toolset math_toolset = Toolset([add_tool, subtract_tool, multiply_tool]) # 混合传入工具与工具集 generator = OllamaChatGenerator( model="llama2", tools=[math_toolset, weather_tool, news_tool], # Toolset 与 Tool 混用 )

run()中还可以通过tools参数按调用覆盖初始化时的工具配置。关于 Tool / Toolset 的完整用法,可参考 haystack/tools 目录,以及组件文档 tool.mdx、toolset.mdx。

4.4 流式输出(Streaming)

streaming_callback传入回调即可开启流式输出。内置的print_streaming_chunk(位于haystack.components.generators.utils)可直接打印文本 token 与工具事件(工具调用与工具结果):

from haystack.components.generators.utils import print_streaming_chunk # 为任意 Generator 或 ChatGenerator 配置流式回调 component = SomeGeneratorOrChatGenerator(streaming_callback=print_streaming_chunk) # ChatGenerator 传消息列表;Generator 传 prompt 字符串

注意事项:

  • 流式模式只支持单条响应,若供应商支持多个候选,需设置n=1
  • 默认优先使用print_streaming_chunk,仅当需要特定传输方式(如 SSE/WebSocket)或自定义 UI 格式化时才编写自定义回调。

StreamingChunk是流式回调收到的数据单元,其定义在 haystack/dataclasses/streaming_chunk.py,包含contenttool_callstool_call_resultreasoning等字段,且同一 chunk 中这四个字段最多只能设置一个。

4.5 流式 + 工具调用组合

toolsstreaming_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 f"Sunny, 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="", flush=True) generator = OllamaChatGenerator( model="llama3.1:8b", generation_kwargs={"temperature": 0.0}, tools=[create_tool_from_function(get_weather)], streaming_callback=callback, ) response = generator.run( messages=[ ChatMessage.from_user( "What's 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_name='get_weather', arguments={'city': 'Berlin'}, ...)]

如果不想手写回调,直接用内置的print_streaming_chunk即可同时处理文本 token 与工具事件。

4.6 多模态输入

OllamaChatGenerator还支持多模态模型(如llava),通过ImageContent传入图片:

from haystack.dataclasses import ChatMessage, ImageContent from haystack_integrations.components.generators.ollama import OllamaChatGenerator llm = OllamaChatGenerator(model="llava", url="http://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 run 方法签名与返回值

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:输入消息列表;如果传入字符串,会被自动转换为一个角色为userChatMessage
  • generation_kwargs单次调用级别的推理选项覆盖,会与实例级generation_kwargs合并(按调用覆盖实例);
  • tools:若设置则覆盖初始化时的tools配置;
  • streaming_callback:提供回调(此处或构造函数中)即切换为流式模式。

返回值字典仅包含一个键replies:模型响应的ChatMessage列表。run_async为对应的异步版本。

4.8 序列化支持

OllamaChatGenerator实现了to_dict()/from_dict(),用于与 Haystack 的 Pipeline YAML 序列化机制集成:

  • to_dict():将组件序列化为字典;
  • from_dict(data):从字典反序列化出组件实例。

这使整个 Pipeline 可以被保存为 YAML/JSON 配置并在其他环境中重建(Haystack 的 marshal 能力见 haystack/marshal)。

4.9 Chat Pipeline 实战

结合ChatPromptBuilder,将用户模板消息渲染后送入 LLM:

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( model="zephyr", url="http://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[0]是一个ChatRole.ASSISTANT角色的ChatMessage,其_meta中同样携带模型名(如{"model": "zephyr", ...})。


五、配套组件:OllamaGenerator(已弃用)

Haystack 还提供过一个面向 prompt 字符串的OllamaGenerator,其默认模型为"orca-mini"、默认 URL 同为http://localhost:11434。参考文档与组件文档均标注其为弃用状态,未来版本会移除,官方建议迁移到OllamaChatGenerator(后者也接受纯字符串输入)。本文不展开其细节,仅在文中明确其迁移方向,避免新项目继续选用。


六、生命周期管理与异步能力小结

三个组件(两个 Embedder 与 ChatGenerator)均实现了统一的生命周期方法,与 Haystack 核心的组件协议保持一致:

方法作用
warm_up()创建同步客户端,供 Pipeline 预加载模型与客户端,避免首次运行时延迟
warm_up_async()创建异步客户端
close()关闭同步客户端,释放资源
close_async()关闭异步客户端
run()同步执行推理
run_async()异步执行推理(OllamaChatGenerator另有to_dict/from_dict

这一设计呼应了 Haystack 将 AsyncPipeline 并入 Pipeline 的演进(参见 Merge-AsyncPipeline-into-Pipeline-73c83002fd647297.yaml),同步与异步可以在同一 Pipeline 框架内无缝混用。


七、快速决策表与最佳实践

需求推荐组件默认模型
为文档批量计算向量(索引阶段)OllamaDocumentEmbeddernomic-embed-text
为查询字符串计算向量(检索阶段)OllamaTextEmbeddernomic-embed-text
本地对话 / RAG 生成OllamaChatGeneratorqwen3:0.6b

实践建议(均有上文依据):

  1. Embedder 与 Retriever 的模型必须一致:索引时文档向量与查询向量需由同一模型(或同一 MRL 维度截断策略)产出,否则相似度比对失去意义;
  2. 长驻模型用keep_alive=-1:高频调用场景下避免反复加载/卸载模型带来的延迟抖动;低频场景用keep_alive='0'及时释放显存/内存;
  3. 结构化输出优先使用response_format:需要 JSON 时优先用"json"或 JSON Schema,而不是在 prompt 里"求"模型输出 JSON;
  4. 流式优先用内置回调:默认使用print_streaming_chunk,自定义回调仅用于 SSE/WebSocket 等特殊传输需求;
  5. 按调用覆盖参数run()中的generation_kwargs/tools会覆盖实例级配置,适合在同一组件上服务不同请求场景;
  6. 工具调用注意模型兼容性:并非所有 Ollama 模型支持 tools,选择模型前应先确认其工具调用能力。

结语

通过ollama-haystack,Haystack 可以在完全不依赖云服务的情况下完成"向量化 → 检索 → 生成"的完整本地 RAG 链路:OllamaDocumentEmbedderOllamaTextEmbedder撑起索引与检索两端,OllamaChatGenerator则提供了对话生成、工具调用、流式输出、思考模式与结构化输出等生产级能力。结合本文给出的参数说明与 Pipeline 示例,你可以快速在自己的机器上搭建一套完全本地化的 LLM 应用。

如需深入了解组件细节,建议继续阅读同仓库中的组件文档:ollamadocumentembedder.mdx、ollamatextembedder.mdx、ollamachatgenerator.mdx,以及 Haystack 核心数据类 chat_message.py 与 streaming_chunk.py 的源码实现。

【免费下载链接】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),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询