奥拉玛·查特

通过 Ollama 你可以在本地运行各种大型语言模型(LLM),并从中生成文本。 Spring AI 支持 Ollama 聊天补全功能,支持以下功能OllamaChatModel应用程序接口。spring-doc.cadn.net.cn

Ollama 也提供兼容 OpenAI API 的端点。 OpenAI API 兼容性部分解释了如何使用 Spring AI OpenAI 连接到 Ollama 服务器。

前提条件

你首先需要访问一个Ollama实例。有几种选择,包括以下几种:spring-doc.cadn.net.cn

你可以从 Ollama 模型库中提取你想在应用中使用的模型:spring-doc.cadn.net.cn

ollama pull <model-name>

你也可以抽取成千上万个免费的GGUF拥抱面模特spring-doc.cadn.net.cn

ollama pull hf.co/<username>/<model-repository>

或者,你也可以启用自动下载任何需要模型的选项:自动拉取模型spring-doc.cadn.net.cn

自动配置

春季AI自动配置、起始模块的工件名称发生了重大变化。 更多信息请参阅升级说明spring-doc.cadn.net.cn

Spring AI 为 Ollama 聊天集成提供了 Spring Boot 自动配置。 要启用它,请在项目的Maven中添加以下依赖pom.xml或者Gradlebuild.gradle构建文件:spring-doc.cadn.net.cn

<dependency>
   <groupId>org.springframework.ai</groupId>
   <artifactId>spring-ai-starter-model-ollama</artifactId>
</dependency>
dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-model-ollama'
}
请参考依赖管理部分,将Spring AI的物料清单添加到你的构建文件中。

基础性质

前缀spring.ai.ollama是配置与Ollama连接的属性前缀。spring-doc.cadn.net.cn

属性spring-doc.cadn.net.cn

描述spring-doc.cadn.net.cn

默认值spring-doc.cadn.net.cn

spring.ai.ollama.base-urlspring-doc.cadn.net.cn

Ollama API 服务器运行的基础网址。spring-doc.cadn.net.cn

http://localhost:11434spring-doc.cadn.net.cn

以下是初始化 Ollama 积分和自动拉取模型的属性。spring-doc.cadn.net.cn

属性spring-doc.cadn.net.cn

描述spring-doc.cadn.net.cn

默认值spring-doc.cadn.net.cn

spring.ai.ollama.init.pull-model-strategyspring-doc.cadn.net.cn

是否在启动时拉取模型以及如何进行。spring-doc.cadn.net.cn

从不spring-doc.cadn.net.cn

spring.ai.ollama.init.timeoutspring-doc.cadn.net.cn

模型被拉出需要等多久。spring-doc.cadn.net.cn

5米spring-doc.cadn.net.cn

spring.ai.ollama.init.max重试spring-doc.cadn.net.cn

模型拉取作的最大重试次数。spring-doc.cadn.net.cn

0spring-doc.cadn.net.cn

spring.ai.ollama.init.chat.includespring-doc.cadn.net.cn

在初始化任务中包含这类模型。spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

spring.ai.ollama.init.chat.additional-modelsspring-doc.cadn.net.cn

除了通过默认属性配置的模型外,还需要初始化更多模型。spring-doc.cadn.net.cn

[]spring-doc.cadn.net.cn

聊天属性

现在,启用和禁用聊天自动配置通过带有前缀的顶层属性进行配置spring.ai.model.chat.spring-doc.cadn.net.cn

要启用,spring.ai.model.chat=ollama(默认是启用的)spring-doc.cadn.net.cn

要禁用,可以选择 spring.ai.model.chat=none(或任何不匹配 ollama 的值)spring-doc.cadn.net.cn

此改动旨在允许配置多个模型。spring-doc.cadn.net.cn

前缀spring.ai.ollama.chat.options.是配置 Ollama 聊天模型的属性前缀。 它包含了 Ollama 请求(高级)参数,例如,保持生命格式以及Ollama模型选项性能。spring-doc.cadn.net.cn

以下是 Ollama 聊天模型的高级请求参数:spring-doc.cadn.net.cn

属性spring-doc.cadn.net.cn

描述spring-doc.cadn.net.cn

默认值spring-doc.cadn.net.cn

spring.ai.ollama.chat.enabled(已移除且不再有效)spring-doc.cadn.net.cn

启用 Ollama 聊天模式。spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

spring.ai.model.chatspring-doc.cadn.net.cn

启用 Ollama 聊天模式。spring-doc.cadn.net.cn

奥拉玛spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.modelspring-doc.cadn.net.cn

支持的型号名称。spring-doc.cadn.net.cn

密斯特拉尔spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.formatspring-doc.cadn.net.cn

回复的格式。目前,唯一被接受的值为JSONspring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.keep_alivespring-doc.cadn.net.cn

控制模型在请求后存储在内存中的持续时间spring-doc.cadn.net.cn

5米spring-doc.cadn.net.cn

剩余的选项属性基于 Ollama 有效参数和值以及 Ollama 类型。默认值基于 Ollama 类型的默认值spring-doc.cadn.net.cn

属性spring-doc.cadn.net.cn

描述spring-doc.cadn.net.cn

默认值spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.numaspring-doc.cadn.net.cn

是否使用NUMA。spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

spring.ai.ollama.chat.options.num-ctxspring-doc.cadn.net.cn

设置用于生成下一个Tokens的上下文窗口大小。spring-doc.cadn.net.cn

2048spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.num-batchspring-doc.cadn.net.cn

提示处理最大批次大小。spring-doc.cadn.net.cn

512spring-doc.cadn.net.cn

Spring.ai.ollama.chat.options.num-GPUspring-doc.cadn.net.cn

要发送给GPU的层数。在macOS上,默认设置为1以启用金属支持,使用0用于禁用。这里的 1 表示 NumGPU 应动态设置spring-doc.cadn.net.cn

-1spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.main-GPUspring-doc.cadn.net.cn

使用多GPU时,该选项控制用于小型张量,因此分散计算在所有GPU上的开销不值得。这块GPU会用更多的显存来存储临时缓冲区以实现临时效果。spring-doc.cadn.net.cn

0spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.low-vramspring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

spring.ai.ollama.chat.options.f16-kvspring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

spring.ai.ollama.chat.options.logits-allspring-doc.cadn.net.cn

返回所有Tokens的日志,而不仅仅是最后一个。为了使完备化返回 logprobs,这必须成立。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.vocab-onlyspring-doc.cadn.net.cn

只加载词汇,不要加载权重。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.use-mmapspring-doc.cadn.net.cn

默认情况下,模型会映射到内存中,这使得系统只能根据需要加载模型的必要部分。然而,如果模型大于你的总内存,或者系统内存不足,使用mmap可能会增加分页出错的风险,从而对性能产生负面影响。禁用 mmap 会让加载时间变慢,但如果你没用 mlock,可能会减少页面导出。注意,如果模型内存大于总内存,关闭 mmap 会阻止模型加载。spring-doc.cadn.net.cn

spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.use-mlockspring-doc.cadn.net.cn

将模型锁定在内存中,防止在内存映射时被替换。这可以提升性能,但会牺牲内存映射的一些优势,因为需要更多内存运行,且模型加载到内存时可能变慢加载速度。spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

spring.ai.ollama.chat.options.num-threadspring-doc.cadn.net.cn

设定计算过程中使用的线程数量。默认情况下,Ollama 会检测到这些数据以实现最佳性能。建议将该值设置为系统物理CPU核心数(而非逻辑核心数)。0 = 让运行时间决定spring-doc.cadn.net.cn

0spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.num-keepspring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

4spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.seedspring-doc.cadn.net.cn

设置随机数种子用于生成。将此数值设置为特定数值,模型会为同一提示生成相同的文本。spring-doc.cadn.net.cn

-1spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.num-predictspring-doc.cadn.net.cn

生成文本时预测的最大标记数。(-1 = 无限生成,-2 = 填充上下文)spring-doc.cadn.net.cn

-1spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.top-kspring-doc.cadn.net.cn

减少产生无意义的概率。数值越高(例如100)答案越多样,而数值越低(例如10)越保守。spring-doc.cadn.net.cn

40spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.top-pspring-doc.cadn.net.cn

和 top-k 一起用。值越高(例如0.95)文本越丰富,而值越低(例如0.5)文本越集中且更保守。spring-doc.cadn.net.cn

0.9spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.min-pspring-doc.cadn.net.cn

作为top_p的替代方案,旨在确保质量与多样性的平衡。参数p表示相对于最可能Tokens概率的最小概率。例如,当p=0.05且最可能的token概率为0.9时,值小于0.045的logit会被过滤掉。spring-doc.cadn.net.cn

0.0spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.tfs-zspring-doc.cadn.net.cn

无尾抽样用于减少输出中较不可能的标记的影响。更高的数值(例如2.0)会更小地减少影响,而1.0的数值则禁用该设置。spring-doc.cadn.net.cn

1.0spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.typical-pspring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

1.0spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.repeat-last-nspring-doc.cadn.net.cn

设定模型回溯的时间长度,以防止重复。(默认:64,0 = 禁用,-1 = num_ctx)spring-doc.cadn.net.cn

64spring-doc.cadn.net.cn

Spring.ai.ollama.chat.options.temperature。spring-doc.cadn.net.cn

模型的温度。提高温度会让模型更有创意地回答。spring-doc.cadn.net.cn

0.8spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.重复-罚球spring-doc.cadn.net.cn

规定重复行为应受到多大的惩罚。更高的数值(例如1.5)会更严厉地惩罚重复,而较低的数值(例如0.9)则更宽松。spring-doc.cadn.net.cn

1.1spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.presence-penaltyspring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

0.0spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.frequency-penaltyspring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

0.0spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.mirostatspring-doc.cadn.net.cn

启用Mirostat采样以控制迷惑度。(默认:0,0 = 禁用,1 = Mirostat,2 = Mirostat 2.0)spring-doc.cadn.net.cn

0spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.mirostat-tauspring-doc.cadn.net.cn

控制输出的连贯性和多样性之间的平衡。较低的数值会带来更集中且连贯的文本。spring-doc.cadn.net.cn

5.0spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.mirostat-etaspring-doc.cadn.net.cn

影响算法对生成文本反馈的响应速度。较低的学习率会导致调整更慢,而较高的学习率则使算法响应更灵敏。spring-doc.cadn.net.cn

0.1spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.penalize-newlinespring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

spring.ai.ollama.chat.options.stop.spring-doc.cadn.net.cn

设置停止序列的使用。当遇到这种模式时,LLM会停止生成文本并返回。通过在模型文件中指定多个独立的停止参数,可以设置多个停止模式。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.tool-namesspring-doc.cadn.net.cn

列出了工具,按名称标识,用于在一次提示请求中实现函数调用。带有这些名称的工具必须存在于 ToolCallback 注册表中。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.tool-callbacksspring-doc.cadn.net.cn

工具回调以注册到聊天模型。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.internal-tool-execution-enabledspring-doc.cadn.net.cn

如果为 false,Spring AI 不会在内部处理工具调用,而是代理到客户端。然后由客户端负责处理工具调用,将其派遣到相应函数,并返回结果。如果为真(默认为真),Spring AI 会在内部处理函数调用。仅适用于支持函数调用的聊天模型spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

所有以spring.ai.ollama.chat.options.可以通过在运行时为 Run 添加请求特定的运行时选项来覆盖提示叫。

运行时选项

OllamaChatOptions.java类提供模型配置,如使用模型、温度、思维模式等。spring-doc.cadn.net.cn

奥拉玛选项职业已被弃用。用奥拉玛聊天选项对于聊天模型和OllamaEmbeddingOptions而是用来嵌入模型。新类别提供了类型安全的、针对特定型号的配置选项。

启动时,默认选项可以配置为OllamaChatModel(api, options)构造者或spring.ai.ollama.chat.options.*性能。spring-doc.cadn.net.cn

运行时,您可以通过添加新的、针对特定请求的选项来覆盖默认选项提示叫。 例如,要覆盖特定请求的默认型号和温度:spring-doc.cadn.net.cn

ChatResponse response = chatModel.call(
    new Prompt(
        "Generate the names of 5 famous pirates.",
        OllamaChatOptions.builder()
            .model(OllamaModel.LLAMA3_1)
            .temperature(0.4)
            .build()
    ));
除了模型专用的 OllamaChatOptions 外,你还可以使用用 ChatOptions#builder() 创建的便携式 ChatOptions 实例。

自动拉车模型

Spring AI Ollama 可以在模型不在你的 Ollama 实例中时自动拉取模型。 此功能在开发和测试以及将应用部署到新环境中尤其有用。spring-doc.cadn.net.cn

你也可以按名字抽取成千上万个免费的GGUF抱脸模型

拉取模型有三种策略:spring-doc.cadn.net.cn

  • 总是(定义于拉取模型策略。始终):即使模型已经可用,也一定要拉出。这有助于确保你使用的是最新版本的模型。spring-doc.cadn.net.cn

  • when_missing(定义于PullModelStrategy.WHEN_MISSING只有当模型还没出现时才会拉出。这可能导致使用旧版本的模型。spring-doc.cadn.net.cn

  • 从不(定义于PullModelStrategy.绝不绝不要自动拉取模型。spring-doc.cadn.net.cn

由于下载模型时可能出现延迟,生产环境中不建议自动拉取。相反,建议提前评估并预先下载所需的模型。

通过配置属性和默认选项定义的所有模型,启动时都可以自动拉取。 您可以使用配置属性配置拉取策略、超时和最大重试次数:spring-doc.cadn.net.cn

spring:
  ai:
    ollama:
      init:
        pull-model-strategy: always
        timeout: 60s
        max-retries: 1
应用程序在所有指定模型都可用 Ollama 之前,不会完成初始化。根据型号大小和网络连接速度,这可能会显著降低应用启动速度。

你可以在启动时初始化额外的模型,这对运行时动态使用的模型非常有用:spring-doc.cadn.net.cn

spring:
  ai:
    ollama:
      init:
        pull-model-strategy: always
        chat:
          additional-models:
            - llama3.2
            - qwen2.5

如果你只想将拉取策略应用于特定类型的模型,可以将聊天模型排除在初始化任务之外:spring-doc.cadn.net.cn

spring:
  ai:
    ollama:
      init:
        pull-model-strategy: always
        chat:
          include: false

该配置将拉取策略应用于除聊天模型外的所有模型。spring-doc.cadn.net.cn

函数调用

你可以用OllamaChatModel并让 Ollama 模型智能地选择输出包含参数的 JSON 对象,以调用一个或多个注册函数。 这是一种强大的技术,将LLM功能与外部工具和API连接起来。 阅读更多关于工具调用的信息。spring-doc.cadn.net.cn

你需要 Ollama 0.2.8 或更新版本才能使用功能调用功能,需要 Ollama 0.4.6 或更新版本才能在流式模式下使用。

思考模式(推理)

Ollama 支持推理模型的思维模式,这些推理模型可以在给出最终答案前先发出内部推理过程。此功能适用于Qwen3、DeepSeek-v3.1、DeepSeek R1和GPT-OSS等型号。spring-doc.cadn.net.cn

思考模式帮助你理解模型的推理过程,并能提升复杂问题的响应质量。
默认行为(Ollama 0.12+):具备思考能力的模型(例如QWEN3:*-思考,深搜-R1,DeepSeek-v3.1) 当思考选项未被明确设置时,自动启用思考。标准模型(例如:qwen2.5:*,骆马3.2) 不要默认启用思考。要明确控制这种行为,请使用.enableThinking().disableThinking().

启用思维模式

大多数模型(Qwen3、DeepSeek-v3.1、DeepSeek R1)支持简单的布尔启用/禁用:spring-doc.cadn.net.cn

ChatResponse response = chatModel.call(
    new Prompt(
        "How many letter 'r' are in the word 'strawberry'?",
        OllamaChatOptions.builder()
            .model("qwen3")
            .enableThinking()
            .build()
    ));

// Access the thinking process
String thinking = response.getResult().getMetadata().get("thinking");
String answer = response.getResult().getOutput().getContent();

你也可以明确地禁用思考:spring-doc.cadn.net.cn

ChatResponse response = chatModel.call(
    new Prompt(
        "What is 2+2?",
        OllamaChatOptions.builder()
            .model("deepseek-r1")
            .disableThinking()
            .build()
    ));

思维层级(仅限GPT-OSS)

GPT-OSS模型需要明确的思维层级而非布尔值:spring-doc.cadn.net.cn

// Low thinking level
ChatResponse response = chatModel.call(
    new Prompt(
        "Generate a short headline",
        OllamaChatOptions.builder()
            .model("gpt-oss")
            .thinkLow()
            .build()
    ));

// Medium thinking level
ChatResponse response = chatModel.call(
    new Prompt(
        "Analyze this dataset",
        OllamaChatOptions.builder()
            .model("gpt-oss")
            .thinkMedium()
            .build()
    ));

// High thinking level
ChatResponse response = chatModel.call(
    new Prompt(
        "Solve this complex problem",
        OllamaChatOptions.builder()
            .model("gpt-oss")
            .thinkHigh()
            .build()
    ));

访问思考内容

思考内容可在回答元数据中获得:spring-doc.cadn.net.cn

ChatResponse response = chatModel.call(
    new Prompt(
        "Calculate 17 × 23",
        OllamaChatOptions.builder()
            .model("deepseek-r1")
            .enableThinking()
            .build()
    ));

// Get the reasoning process
String thinking = response.getResult().getMetadata().get("thinking");
System.out.println("Reasoning: " + thinking);
// Output: "17 × 20 = 340, 17 × 3 = 51, 340 + 51 = 391"

// Get the final answer
String answer = response.getResult().getOutput().getContent();
System.out.println("Answer: " + answer);
// Output: "The answer is 391"

思维直播

思考模式也适用于流式回复:spring-doc.cadn.net.cn

Flux<ChatResponse> stream = chatModel.stream(
    new Prompt(
        "Explain quantum entanglement",
        OllamaChatOptions.builder()
            .model("qwen3")
            .enableThinking()
            .build()
    ));

stream.subscribe(response -> {
    String thinking = response.getResult().getMetadata().get("thinking");
    String content = response.getResult().getOutput().getContent();

    if (thinking != null && !thinking.isEmpty()) {
        System.out.println("[Thinking] " + thinking);
    }
    if (content != null && !content.isEmpty()) {
        System.out.println("[Response] " + content);
    }
});
当思维被禁用或未设置时,思维元数据字段将为空或空。

模 态

多模态指的是模型能够同时理解和处理来自多种来源的信息,包括文本、图像、音频及其他数据格式。spring-doc.cadn.net.cn

支持多模态的 Ollama 模型包括 LLaVABakLLaVA(详见完整列表)。 更多详情请参阅LLaVA:大型语言与视觉助理spring-doc.cadn.net.cn

Ollama 消息 API 提供了一个“images”参数,用于将 base64 编码的图片列表与消息一同整合。spring-doc.cadn.net.cn

Spring AI 的 Message 界面通过引入媒体类型,促进了多模态 AI 模型的发展。 这种类型包含了关于消息中媒体附件的数据和详细信息,利用Spring的org.springframework.util.MimeType以及一个org.springframework.core.io.Resource对于原始媒体数据。spring-doc.cadn.net.cn

以下是摘自OllamaChatModelMultimodalIT.java的简明代码示例,展示了用户文本与图像的融合。spring-doc.cadn.net.cn

var imageResource = new ClassPathResource("/multimodal.test.png");

var userMessage = new UserMessage("Explain what do you see on this picture?",
        new Media(MimeTypeUtils.IMAGE_PNG, this.imageResource));

ChatResponse response = chatModel.call(new Prompt(this.userMessage,
        OllamaChatOptions.builder().model(OllamaModel.LLAVA)).build());

示例展示了一个以multimodal.test.png图像:spring-doc.cadn.net.cn

多模态测试图像

并附上短信“请解释你在这张图片上看到了什么?”,并生成如下回复:spring-doc.cadn.net.cn

The image shows a small metal basket filled with ripe bananas and red apples. The basket is placed on a surface,
which appears to be a table or countertop, as there's a hint of what seems like a kitchen cabinet or drawer in
the background. There's also a gold-colored ring visible behind the basket, which could indicate that this
photo was taken in an area with metallic decorations or fixtures. The overall setting suggests a home environment
where fruits are being displayed, possibly for convenience or aesthetic purposes.

结构化输出

Ollama 提供定制的结构化输出 API,确保你的模型生成的响应严格符合你提供的条件JSON 模式. 除了现有的Spring AI模型无关的结构化输出转换器外,这些API还提供了更强的控制和精度。spring-doc.cadn.net.cn

配置

Spring AI 允许你通过奥拉玛聊天选项架构工人。spring-doc.cadn.net.cn

使用聊天选项生成器

你可以用奥拉玛聊天选项架构师如下所示:spring-doc.cadn.net.cn

String jsonSchema = """
        {
            "type": "object",
            "properties": {
                "steps": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "explanation": { "type": "string" },
                            "output": { "type": "string" }
                        },
                        "required": ["explanation", "output"],
                        "additionalProperties": false
                    }
                },
                "final_answer": { "type": "string" }
            },
            "required": ["steps", "final_answer"],
            "additionalProperties": false
        }
        """;

Prompt prompt = new Prompt("how can I solve 8x + 7 = -23",
        OllamaChatOptions.builder()
            .model(OllamaModel.LLAMA3_2.getName())
            .format(new ObjectMapper().readValue(jsonSchema, Map.class))
            .build());

ChatResponse response = this.ollamaChatModel.call(this.prompt);

与 BeanOutputConverter 工具集成

你可以利用现有的 BeanOutputConverter 工具,自动从你的域对象生成 JSON 模式,然后将结构化响应转换为域特定的实例:spring-doc.cadn.net.cn

record MathReasoning(
    @JsonProperty(required = true, value = "steps") Steps steps,
    @JsonProperty(required = true, value = "final_answer") String finalAnswer) {

    record Steps(
        @JsonProperty(required = true, value = "items") Items[] items) {

        record Items(
            @JsonProperty(required = true, value = "explanation") String explanation,
            @JsonProperty(required = true, value = "output") String output) {
        }
    }
}

var outputConverter = new BeanOutputConverter<>(MathReasoning.class);

Prompt prompt = new Prompt("how can I solve 8x + 7 = -23",
        OllamaChatOptions.builder()
            .model(OllamaModel.LLAMA3_2.getName())
            .format(outputConverter.getJsonSchemaMap())
            .build());

ChatResponse response = this.ollamaChatModel.call(this.prompt);
String content = this.response.getResult().getOutput().getText();

MathReasoning mathReasoning = this.outputConverter.convert(this.content);
确保你使用以下条件@JsonProperty(必要=真,...)用于生成准确标记字段的模式的注释必填. 虽然 JSON Schema 是可选的,但建议这样结构化响应才能正常工作。

OpenAI API 兼容性

Ollama 兼容 OpenAI API,你可以使用 Spring AI OpenAI 客户端与 Ollama 通信并使用工具。 为此,你需要配置 OpenAI 为你的 Ollama 实例设置基础 URL:spring.ai.openai.chat.base-url=http://localhost:11434并选择提供的Ollama型号之一:spring.ai.openai.chat.options.model=mistral.spring-doc.cadn.net.cn

使用 OpenAI 客户端配合 Ollama 时,你可以传递 Ollama 特定的参数(例如top_k,repeat_penalty,num_predict) 使用额外内容选择. 这让你在使用 OpenAI 客户端时,能够充分发挥 Ollama 的全部功能。
Ollama OpenAI API 兼容性

通过OpenAI兼容性推理内容

Ollama 兼容 OpenAI 的端点支持reasoning_content用于思考能力模型的场(例如QWEN3:*-思考,深搜-R1,DeepSeek-v3.1). 当使用 Spring AI OpenAI 客户端配合 Ollama 时,模型的推理过程会自动被捕获并通过响应元数据提供。spring-doc.cadn.net.cn

这是使用 Ollama 原生思维模式 API(见上文“思考模式(推理)文档”)的替代方案。 这两种方法都适用于Ollama的思维模型,但兼容OpenAI的端点使用reasoning_content字段名称代替思维.

这里有一个通过OpenAI客户端访问Ollama推理内容的示例:spring-doc.cadn.net.cn

// Configure Spring AI OpenAI client to point to Ollama
@Configuration
class OllamaConfig {
    @Bean
    OpenAiChatModel ollamaChatModel() {
        var openAiApi = new OpenAiApi("http://localhost:11434", "ollama");
        return new OpenAiChatModel(openAiApi,
            OpenAiChatOptions.builder()
                .model("deepseek-r1")  // or qwen3, deepseek-v3.1, etc.
                .build());
    }
}

// Use the model with thinking-capable models
ChatResponse response = chatModel.call(
    new Prompt("How many letter 'r' are in the word 'strawberry'?"));

// Access the reasoning process from metadata
String reasoning = response.getResult().getMetadata().get("reasoningContent");
if (reasoning != null && !reasoning.isEmpty()) {
    System.out.println("Model's reasoning process:");
    System.out.println(reasoning);
}

// Get the final answer
String answer = response.getResult().getOutput().getContent();
System.out.println("Answer: " + answer);
Ollama(0.12+)中具备思考能力的模型在通过兼容OpenAI的端点访问时会自动启用思考模式。 推理内容会自动捕获,无需额外配置。

查看OllamaWithOpenAiChatModelIT.java测试,了解如何使用Ollama而非Spring AI OpenAI的示例。spring-doc.cadn.net.cn

拥抱面模特

Ollama 可以开箱即用地访问所有 GGUF 拥抱面部聊天模型。 你可以按名称抽取这些模型中的任意一个:ollama pull hf.co/<username>/<model-repository>或配置自动拉取策略:自动拉取模型spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.model=hf.co/bartowski/gemma-2-2b-it-GGUF
spring.ai.ollama.init.pull-model-strategy=always
  • spring.ai.ollama.chat.options.model: 指定了使用拥抱面GGUF模型spring-doc.cadn.net.cn

  • spring.ai.ollama.init.pull-model-strategy=always:(可选)启动时启用自动拉取模型。 制作时,建议提前下载模型以避免延误:奥拉玛拉 hf.co/bartowski/gemma-2-2b-it-GGUF.spring-doc.cadn.net.cn

采样控制器

创建一个新的 Spring Boot 项目并添加Spring-ai-starter-model-ollama对你的POM(或Gradle)依赖。spring-doc.cadn.net.cn

添加一个application.yaml文件,在src/主/资源目录,用于启用和配置 Ollama 聊天模型:spring-doc.cadn.net.cn

spring:
  ai:
    ollama:
      base-url: http://localhost:11434
      chat:
        options:
          model: mistral
          temperature: 0.7
替换base-url用你的 Ollama 服务器网址。

这将产生OllamaChatModel你可以把这些实现注入到你的类中。 这里有一个简单的例子@RestController使用聊天模式生成文本的课程。spring-doc.cadn.net.cn

@RestController
public class ChatController {

    private final OllamaChatModel chatModel;

    @Autowired
    public ChatController(OllamaChatModel chatModel) {
        this.chatModel = chatModel;
    }

    @GetMapping("/ai/generate")
    public Map<String,String> generate(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
        return Map.of("generation", this.chatModel.call(message));
    }

    @GetMapping("/ai/generateStream")
	public Flux<ChatResponse> generateStream(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
        Prompt prompt = new Prompt(new UserMessage(message));
        return this.chatModel.stream(prompt);
    }

}

手动配置

如果你不想用 Spring Boot 的自动配置,可以手动配置OllamaChatModel在你的申请中。 OllamaChatModel 实现了聊天模型StreamingChatModel并使用低级 OllamaApi 客户端连接 Ollama 服务。spring-doc.cadn.net.cn

使用时,添加春艾奥拉玛对你项目Maven的依赖pom.xml或者Gradlebuild.gradle构建文件:spring-doc.cadn.net.cn

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-ollama</artifactId>
</dependency>
dependencies {
    implementation 'org.springframework.ai:spring-ai-ollama'
}
请参考依赖管理部分,将Spring AI的物料清单添加到你的构建文件中。
春艾奥拉玛依赖还提供访问OllamaEmbeddingModel. 欲了解更多关于OllamaEmbeddingModel请参阅奥拉玛嵌入模型部分。

接下来,创建一个OllamaChatModel实例并使用它来发送文本生成请求:spring-doc.cadn.net.cn

var ollamaApi = OllamaApi.builder().build();

var chatModel = OllamaChatModel.builder()
                    .ollamaApi(ollamaApi)
                    .defaultOptions(
                        OllamaChatOptions.builder()
                            .model(OllamaModel.MISTRAL)
                            .temperature(0.9)
                            .build())
                    .build();

ChatResponse response = this.chatModel.call(
    new Prompt("Generate the names of 5 famous pirates."));

// Or with streaming responses
Flux<ChatResponse> response = this.chatModel.stream(
    new Prompt("Generate the names of 5 famous pirates."));

奥拉玛聊天选项提供所有聊天请求的配置信息。spring-doc.cadn.net.cn

低级 OllamaApi 客户端

OllamaApi 提供了一个轻量级的 Java 客户端,用于 Ollama 聊天补全 APIspring-doc.cadn.net.cn

下图展示了奥拉玛阿皮聊天界面与构建模块:spring-doc.cadn.net.cn

OllamaApi 聊天补全 API 图
奥拉玛阿皮是一个低级别API,不推荐直接使用。使用该OllamaChatModel相反。

这里有一个简单的片段,展示了如何以程序方式使用该 API:spring-doc.cadn.net.cn

OllamaApi ollamaApi = new OllamaApi("YOUR_HOST:YOUR_PORT");

// Sync request
var request = ChatRequest.builder("orca-mini")
    .stream(false) // not streaming
    .messages(List.of(
            Message.builder(Role.SYSTEM)
                .content("You are a geography teacher. You are talking to a student.")
                .build(),
            Message.builder(Role.USER)
                .content("What is the capital of Bulgaria and what is the size? "
                        + "What is the national anthem?")
                .build()))
    .options(OllamaChatOptions.builder().temperature(0.9).build())
    .build();

ChatResponse response = this.ollamaApi.chat(this.request);

// Streaming request
var request2 = ChatRequest.builder("orca-mini")
    .ttream(true) // streaming
    .messages(List.of(Message.builder(Role.USER)
        .content("What is the capital of Bulgaria and what is the size? " + "What is the national anthem?")
        .build()))
    .options(OllamaChatOptions.builder().temperature(0.9).build().toMap())
    .build();

Flux<ChatResponse> streamingResponse = this.ollamaApi.streamingChat(this.request2);