在 LlamaIndex 中接入本地 Ollama 大模型:Ollama 集成包完整指南

原创2026-10-09 22:50:311,916 阅读
文章标签:人工智能大模型RAGAI AgentAgent 框架Agent 工作流Prompt 模板向量数据库Embedding

在 LlamaIndex 中接入本地 Ollama 大模型:Ollama 集成包完整指南

LlamaIndex 通过 llama-index-llms-ollama 集成包,将本地 Ollama 推理服务无缝接入统一的 LLM 抽象体系,让 llama3.1、qwen3、llama3.2-vision 等本地模型可以直接服务于索引构建、查询引擎与 Agent 编排。本文以 API 引用文档 docs/api_reference/api_reference/llms/ollama.md 指向的 llama_index.llms.ollama.Ollama 类为核心,结合集成包源码、官方 README 与示例 Notebook,完整讲解安装配置、全部构造参数、同步/异步/流式调用、JSON 模式、结构化输出、多模态、Thinking 推理与工具调用(Function Calling),并深入到源码层面剖析底层实现原理,帮助你快速把本地模型接入 LlamaIndex 生态。

Ollama 集成包的定位与包结构

llama-index-llms-ollama 是 LlamaIndex 官方 LLM 集成之一,核心职责是把 Ollama 本地服务暴露的 HTTP API 封装为符合 llama_index.core.base.llms 抽象的统一 LLM 接口。集成包位于仓库:

从 pyproject.toml 可以看到,该包当前版本为 0.11.0,声明依赖 ollama>=0.5.3(Ollama 官方 Python SDK)与 llama-index-core>=0.14.5,<0.15,运行环境要求 Python >=3.10,<4.0。也就是说所有请求最终都由官方 ollama SDK 发出,集成层只负责参数映射、消息转换与响应规范化。

安装与本地服务准备

安装 Python 包

pip install llama-index-llms-ollama

启动 Ollama 服务并拉取模型

  1. 按照 Ollama 官方说明在本地安装并启动 Ollama;
  2. 当 Ollama 应用运行后,本地所有模型会自动服务在 localhost:11434;
  3. 拉取需要的模型,例如:
ollama pull llama3.1:latest
ollama pull qwen3:8b        # 支持 thinking 推理
ollama pull llama3.2-vision # 支持多模态
  1. 指定模型时不写版本号(如 model="llama3.1")会自动选用最新版本;写完整标签(如 model="llama3.1:latest")则按标签精确匹配。

快速初始化

from llama_index.llms.ollama import Ollama

llm = Ollama(
    model="llama3.1:latest",
    request_timeout=120.0,
    # 手动设置上下文窗口以限制内存占用
    context_window=8000,
)

提示:默认请求超时为 30 秒,本地模型推理较大 prompt 时建议显式调大 request_timeout,例如 request_timeout=300.0。

Ollama 类构造参数全解析

Ollama 类继承自 llama_index.core.llms.function_calling.FunctionCallingLLM,全部构造参数以 Pydantic Field 定义在 base.py 中,下表参数名、默认值与语义均与源码一一对应:

参数 类型 默认值 源码说明
model str 必填 要使用的 Ollama 模型名,如 llama3.1:latest
base_url str http://localhost:11434 模型所在服务的基地址
temperature Optional[float] None 采样温度,不设置时交给服务端默认策略
context_window int -1 模型最大上下文 token 数;-1 表示自动从模型信息中探测
request_timeout float 30.0 请求 Ollama API 服务器的超时时间(秒)
prompt_key str prompt API 调用中 prompt 使用的键名
json_mode bool False 是否启用 JSON 模式,确保响应为合法 JSON
additional_kwargs Dict[str, Any] {} 透传给 Ollama API 的额外模型参数
is_function_calling_model bool True 当前模型是否为函数调用模型
keep_alive Optional[float|str] "5m" 控制请求后模型在内存中驻留的时间
thinking Optional[bool|Literal["low","medium","high"]] None 是否启用/禁用推理思考;对支持级别调节的模型可传字符串级别
headers Optional[Dict[str, str]] None 自定义 HTTP 请求头(如 Authorization)

几个关键参数的源码级解读

  • context_window 自动探测:get_context_window() 方法在 context_window == -1 时调用 self.client.show(self.model).modelinfo,遍历模型信息字典,只要键名包含 context_length 就取其值作为上下文窗口;若仍未探测到,则回退到 llama_index.core.constants.DEFAULT_CONTEXT_WINDOW(即 constants.py 中的 3900 tokens)。手动设置 context_window 可以主动限制内存占用,官方 Notebook 中即推荐这种做法。

  • _model_kwargs 的组装:每次请求时,集成层会把 temperature 与 num_ctx(即上下文窗口)作为基础参数,再合并 additional_kwargs 一起作为 options 传给 Ollama API。也就是说 additional_kwargs 里可以放 Ollama 运行时选项(如 top_p、repeat_penalty 等),实现细粒度采样控制。

  • keep_alive 控制内存驻留:默认 "5m",请求完成后模型会在内存中保留 5 分钟,方便后续请求复用;需要即时释放显存/内存可传较小的值,希望常驻可传更大值。

  • headers 用于私有部署鉴权:若你的 Ollama 服务前置了网关或需要 Bearer Token 鉴权,可在此传入自定义请求头;client 与 async_client 两个惰性属性(lazy property)在首次访问时会把 base_url、request_timeout、headers 注入到底层 ollama.Client / ollama.AsyncClient 实例中。

基础用法:文本补全与多轮对话

文本补全(complete)

resp = llm.complete("Who is Paul Graham?")
print(resp)

多轮对话(chat)

from llama_index.core.llms import ChatMessage

messages = [
    ChatMessage(
        role="system", content="You are a pirate with a colorful personality."
    ),
    ChatMessage(role="user", content="What is your name?"),
]
resp = llm.chat(messages)
print(resp)

complete 系列方法在源码中通过 chat_to_completion_decorator / achat_to_completion_decorator 等装饰器直接复用 chat 实现(见 base.py),因此两种调用方式的底层行为完全一致:所有请求统一走 Ollama 的 /chat 接口。

流式输出:stream_complete 与 stream_chat

流式补全

response = llm.stream_complete("Who is Paul Graham?")
for r in response:
    print(r.delta, end="")

流式对话

messages = [
    ChatMessage(
        role="system", content="You are a pirate with a colorful personality."
    ),
    ChatMessage(role="user", content="What is your name?"),
]
resp = llm.stream_chat(messages)
for r in resp:
    print(r.delta, end="")

源码中的 stream_chat 会累积各分片内容,并做三件额外的事:

  1. 去重工具调用:每个分片的 tool_calls 以 (name, arguments) 为键去重,保证同一工具调用只出现一次;
  2. 拆分 thinking 增量:thinking 字段通过 additional_kwargs["thinking_delta"] 独立透出,让调用方可以单独渲染"推理过程"与"最终回答";
  3. 统计 token:分片包含 prompt_eval_count / eval_count 时写入 usage。

JSON 模式

Ollama 原生支持 JSON 模式,保证输出是合法 JSON,非常适合下游程序解析:

llm = Ollama(
    model="llama3.1:latest",
    request_timeout=120.0,
    json_mode=True,
    context_window=8000,
)

response = llm.complete("Who is Paul Graham? Output as a structured JSON object.")
print(str(response))

从源码看,json_mode=True 等价于每次请求把 format 参数固定为 "json",而每次调用时也可以通过 format 关键字临时覆盖这一默认行为——这正是结构化输出的实现基础。

结构化输出:绑定 Pydantic 类

Ollama 支持内建的 JSON Schema 结构化输出。将 Pydantic 类绑定到 LLM 后,模型会严格按 Schema 生成结果:

from llama_index.core.bridge.pydantic import BaseModel
from llama_index.core.llms import ChatMessage


class Song(BaseModel):
    """A song with name and artist."""

    name: str
    artist: str


llm = Ollama(model="llama3.1:latest", request_timeout=120.0)
sllm = llm.as_structured_llm(Song)

response = sllm.chat([ChatMessage(role="user", content="Name a random song!")])
print(response.message.content)
# 例如:{"name": "Yesterday", "artist": "The Beatles"}

其源码原理是:structured_predict 在默认的 PydanticProgramMode.DEFAULT 分支下,把 output_cls.model_json_schema() 作为 format 参数传给 chat(即 Ollama 的原生 JSON Schema 约束),再把返回内容用 output_cls.model_validate_json 解析为 Pydantic 对象。该方法同样有 astructured_predict、stream_structured_predict、astream_structured_predict 三套异步/流式变体。

结构化输出的流式与普通文本流不同:它逐步产出"当前最完整的结构化对象"生成器。官方 Notebook 展示了 Song 对象字段逐个被填充的过程({"name":null,"artist":null} → {"name":"Mr. Blue Sky","artist":"Electric Light Orchestra"}),这是通过 llama_index.core.program.utils.process_streaming_objects 实现的渐进式 JSON 解析。

异步调用:achat 与 acomplete

集成层为所有方法都提供了异步版本,底层使用 ollama.AsyncClient:

response = await sllm.achat(
    [ChatMessage(role="user", content="Name a random song!")]
)
print(response.message.content)

可用的异步方法包括:achat、acomplete、astream_chat、astream_complete、astructured_predict、astream_structured_predict,适合在高并发服务(如 FastAPI 场景)中使用。

多模态支持

Ollama 的视觉模型可以直接通过该集成使用,无需任何额外配置。核心是借助 LlamaIndex 的 Content Block 机制(TextBlock / ImageBlock),把图片以 base64 形式随消息发给模型:

from llama_index.core.llms import ChatMessage, TextBlock, ImageBlock
from llama_index.llms.ollama import Ollama

# 需要先执行:ollama pull llama3.2-vision
llm = Ollama(model="llama3.2-vision", request_timeout=120.0)

messages = [
    ChatMessage(
        role="user",
        blocks=[
            TextBlock(text="What type of animal is this?"),
            ImageBlock(path="ollama_image.jpg"),
        ],
    ),
]

resp = llm.chat(messages)
print(resp)

源码层面,_convert_to_ollama_messages 会遍历每条 ChatMessage 的 blocks:

  • TextBlock → 累加到消息 content;
  • ImageBlock → 通过 resolve_image(as_base64=True) 转为 base64 后追加到 images 数组;
  • ThinkingBlock → 映射为消息的 thinking 字段(用于回传历史推理);
  • ToolCallBlock → 映射为 Ollama 的 tool_calls 结构。

这保证了同一个类可以同时处理文本、图片、工具调用与推理轨迹的复合消息。

Thinking 推理模式

Ollama 中的 "thinking" 是模型在给出最终答案前进行推理反思的过程。通过 thinking 参数启用,支持布尔值(True/False)以及 "low"、"medium"、"high" 三个级别(级别用于调节推理轨迹长度,例如 gpt-oss 系列模型):

llm = Ollama(
    model="qwen3:8b",
    request_timeout=360,
    thinking=True,
    context_window=8000,
)

resp = llm.complete("What is 434 / 22?")
print(resp.additional_kwargs["thinking"])  # 完整推理过程
print(resp.text)                            # 最终回答

在流式模式下,推理内容与最终回答分别通过 additional_kwargs["thinking_delta"] 和 delta 两个通道输出,官方 Notebook 给出了分别渲染两部分的示例:

resp_gen = llm.stream_complete("What is 434 / 22?")
thinking_started = False
response_started = False

for resp in resp_gen:
    if resp.additional_kwargs.get("thinking_delta", None):
        if not thinking_started:
            print("\n\n-------- Thinking: --------\n")
            thinking_started = True
            response_started = False
        print(resp.additional_kwargs["thinking_delta"], end="", flush=True)
    if resp.delta:
        if not response_started:
            print("\n\n-------- Response: --------\n")
            response_started = True
            thinking_started = False
        print(resp.delta, end="", flush=True)

细节说明:thinking 是构造时全局开关,但每次调用还可以通过 think 关键字临时覆盖(llm.chat(messages, think=False));非流式响应中推理内容会被封装为 ThinkingBlock 放进 message.blocks,同时保留在 additional_kwargs["thinking"] 中以兼容旧版本。

函数调用与 Agent 工具集成

Ollama 默认就是函数调用模型(is_function_calling_model=True),可以直接与 LlamaIndex 的 FunctionTool 及 Agent 框架配合。官方测试展示了完整的工具调用链路:

from typing import Annotated
from llama_index.core.tools import FunctionTool
from llama_index.core.bridge.pydantic import BaseModel, Field


class Song(BaseModel):
    """A song with name and artist."""

    artist_name: str = Field(description="The name of the artist")
    song_name: str = Field(description="The name of the song")


def generate_song(
    artist_name: Annotated[str, "The name of the artist"],
    song_name: Annotated[str, "The name of the song"],
) -> Song:
    """Generates a song with provided name and artist."""
    return Song(artist_name=artist_name, song_name=song_name)


tool = FunctionTool.from_defaults(fn=generate_song)

llm = Ollama(model="llama3.1:latest", context_window=8000)
response = llm.chat_with_tools(
    [tool], user_msg="Hello! Generate a random artist and song."
)
tool_calls = llm.get_tool_calls_from_response(response)
assert tool_calls[0].tool_name == tool.metadata.name

tool_result = tool(**tool_calls[0].tool_kwargs)

源码中的相关实现值得注意:

  • 工具描述生成:_prepare_chat_with_tools 通过 tool.metadata.to_openai_tool(skip_length_check=True) 把 LlamaIndex 的 BaseTool 转为 OpenAI 兼容的工具 Schema 传给 Ollama;
  • 单工具约束:_validate_chat_with_tools_response 在 allow_parallel_tool_calls=False 时调用 force_single_tool_call,强制只保留第一个工具调用——因为 Ollama 目前不支持并行工具调用(源码注释明确指出这一点);
  • 工具 ID 兼容:Ollama 不返回工具 ID,get_tool_calls_from_response 中 tool_id 直接用工具名充当;
  • 空调用容错:测试 test_llms_ollama.py 验证了当模型没有调用任何工具时,get_tool_calls_from_response(response, error_on_no_tool_call=False) 返回空列表而非抛错,保证 Agent 循环可以优雅收尾。

元数据与 Token 统计

Ollama.metadata 属性返回的 LLMMetadata 中:is_chat_model=True(Ollama 对所有模型都提供 chat API)、num_output=DEFAULT_NUM_OUTPUTS(即 constants.py 中的 256 tokens)、model_name 为当前模型名。上下文窗口由前述 get_context_window() 动态探测。

Token 使用量方面,_get_response_token_counts 直接从 Ollama 响应的 prompt_eval_count(输入)与 eval_count(输出)字段求和,写入响应的 usage 字段,方便与 LlamaIndex 的观测/计费链路对接;字段缺失时静默返回空字典。

测试与验证方式

集成包自带的测试 test_llms_ollama.py 覆盖了完整的调用面:同步/异步的 chat、complete、stream_chat、stream_complete,工具调用(含流式与异步版本),thinking 模式(布尔开关、三级推理、历史推理回传)等。测试通过环境变量选择模型:

环境变量 默认模型 用途
OLLAMA_TEST_MODEL llama3.1:latest 常规 chat / complete / stream / 工具调用
OLLAMA_THINKING_TEST_MODEL qwen3:0.6b thinking 布尔开关与推理回传
THINKING_LEVEL_MODEL gpt-oss:20b thinking 级别(low/high)调节

测试还验证了一个细节:thinking="low" 与 thinking="high" 产出的推理块长度存在可观测差异(high 明显更长),可用于校验推理级别的实际效果。若本地没有 Ollama 服务或缺少模型,这些用例会被 pytest.mark.skipif 自动跳过,不会导致测试失败。

实践建议与注意事项

  1. 超时设置:本地推理慢模型或长 prompt 时务必调大 request_timeout(官方示例常用 120~360 秒),否则会触发默认 30 秒超时;
  2. 上下文窗口与内存:默认 -1 会自动使用模型最大上下文,但这可能带来较高的显存占用;在资源受限环境可手动 context_window=8000 之类限制;
  3. 模型标签:建议使用完整标签 model:tag,避免隐式拉取最新版导致行为漂移;
  4. 工具调用限制:Ollama 尚不支持并行工具调用与强制工具调用,Agent 编排时建议让模型单步只调一个工具;
  5. 多模态与推理:llama3.2-vision、qwen3 等模型可直接复用同一 Ollama 类,无需换 API。

延伸阅读

登录后查看全文
llama_index