Skip to content
Spring AI 文档版本 2.1.0-SNAPSHOT 源快照 a82df6f9 更新于 2026-10-16

Ollama 聊天

借助 Ollama,你可以在本地运行各种大语言模型(LLM)并从中生成文本。 Spring AI 通过 OllamaChatModel API 支持 Ollama 的聊天补全能力。

TIP

Ollama 也提供一个与 OpenAI API 兼容的端点。

OpenAI API 兼容性 一节解释了如何用 Spring AI OpenAI 连接到 Ollama 服务器。

前置条件

你首先需要一个可访问的 Ollama 实例。有几种方式,包括以下这些:

你可以从 Ollama 模型库 拉取你想在应用中使用的模型:

shellscript
ollama pull <model-name>

你也可以拉取数以千计的免费 GGUF Hugging Face 模型:

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

或者,你可以启用自动下载任何所需模型的选项:自动拉取模型。

自动配置

NOTE

Spring AI 的自动配置、starter 模块的制品名称发生了重大变更。 更多信息请参阅 升级说明。

Spring AI 为 Ollama 聊天集成提供 Spring Boot 自动配置。 要启用它,请将以下依赖添加到你的项目的 Maven pom.xml 或 Gradle build.gradle 构建文件:

xml
<dependency>
   <groupId>org.springframework.ai</groupId>
   <artifactId>spring-ai-starter-model-ollama</artifactId>
</dependency>

TIP

参见 依赖管理 一节,把 Spring AI BOM 添加到你的构建文件。

基础属性

前缀 spring.ai.ollama 是配置到 Ollama 连接的属性前缀。

属性描述默认值
spring.ai.ollama.base-url运行 Ollama API 服务端的 Base URL。+http://localhost:11434+

以下是初始化 Ollama 集成并 自动拉取模型 的属性。

属性描述默认值
spring.ai.ollama.init.pull-model-strategy是否在启动时拉取模型以及如何拉取。never
spring.ai.ollama.init.timeout等待模型拉取的时长。5m
spring.ai.ollama.init.max-retries模型拉取操作的最大重试次数。0
spring.ai.ollama.init.chat.include把此类模型纳入初始化任务。true
spring.ai.ollama.init.chat.additional-models除通过默认属性配置的之外,要额外初始化的模型。[]

聊天属性

NOTE

聊天自动配置的启用与禁用,现通过以 spring.ai.model.chat 为前缀的顶层属性来配置。

要启用,spring.ai.model.chat=ollama(默认启用)

要禁用,spring.ai.model.chat=none(或任何不匹配 ollama 的值)

做出此变更是为了支持配置多个模型。

前缀 spring.ai.ollama.chat 是配置 Ollama 聊天模型的属性前缀。 它包含诸如 model、keep-alive 和 format 的 Ollama 请求(高级)参数,以及 Ollama 模型 options 属性。

以下是 Ollama 聊天模型的高级请求参数:

属性描述默认值
spring.ai.ollama.chat.enabled (Removed and no longer valid)启用 Ollama 聊天模型。true
spring.ai.model.chat启用 Ollama 聊天模型。ollama
spring.ai.ollama.chat.model要使用的受支持模型名。mistral
spring.ai.ollama.chat.format返回响应的格式。接受 "json"(任意 JSON 结构)或一个 JSON Schema 对象(强制结构)。细节参见结构化输出。-
spring.ai.ollama.chat.keep_alive控制请求之后模型在内存中保持加载多久5m
spring.ai.ollama.chat.think控制模型是否在最终答案前发出其推理轨迹。-

其余 options 属性基于 Ollama 有效参数与值 和 Ollama Types。默认值基于 Ollama Types Defaults。

属性描述默认值
spring.ai.ollama.chat.numa是否使用 NUMA。false
spring.ai.ollama.chat.num-ctx设置用于生成下一个令牌的上下文窗口大小。2048
spring.ai.ollama.chat.num-batch提示词处理的最大批大小。512
spring.ai.ollama.chat.num-gpu要发送到 GPU 的层数。在 macOS 上默认为 1 以启用 metal 支持,0 禁用。这里的 1 表示应动态设置 NumGPU-1
spring.ai.ollama.chat.main-gpu使用多个 GPU 时,此选项控制哪个 GPU 用于那些在所有 GPU 间拆分计算得不偿失的小张量。所指的 GPU 会多用一点 VRAM 来存一个用于临时结果的暂存缓冲区。0
spring.ai.ollama.chat.low-vram-false
spring.ai.ollama.chat.f16-kv-true
spring.ai.ollama.chat.logits-all返回所有令牌的 logits,而非仅最后一个。要启用补全返回 logprobs,此项必须为 true。-
spring.ai.ollama.chat.vocab-only只加载词表,不加载权重。-
spring.ai.ollama.chat.use-mmap默认情况下,模型被映射进内存,让系统能按需只加载模型必要的部分。然而,如果模型比你的总内存大,或系统可用内存偏低,使用 mmap 可能增加换页风险,负面影响性能。禁用 mmap 会导致加载变慢,但若你不使用 mlock,可能减少换页。注意:如果模型比总内存大,关闭 mmap 会使模型根本无法加载。null
spring.ai.ollama.chat.use-mlock把模型锁在内存中,防止其在内存映射时被换出。这能改善性能,但以牺牲内存映射的一些优势为代价——需要更多 RAM 运行,且随着模型加载进 RAM 可能拖慢加载时间。false
spring.ai.ollama.chat.num-thread设置计算期间使用的线程数。默认 Ollama 会自动检测以获得最佳性能。建议把此值设为你的系统的物理 CPU 核数(而非逻辑核数)。0 = 交由运行时决定0
spring.ai.ollama.chat.num-keep-4
spring.ai.ollama.chat.seed设置生成用的随机数种子。把它设为某个特定值会让模型对同一提示词生成相同文本。-1
spring.ai.ollama.chat.num-predict生成文本时要预测的最大令牌数。(-1 = 无限生成,-2 = 填满上下文)-1
spring.ai.ollama.chat.top-k降低生成无意义内容的概率。较高的值(例如 100)给出更多样的答案,而较低的值(例如 10)更保守。40
spring.ai.ollama.chat.top-p与 top-k 协同工作。较高的值(例如 0.95)会导向更多样的文本,而较低的值(例如 0.5)会生成更聚焦、更保守的文本。0.9
spring.ai.ollama.chat.min-ptop_p 的替代方案,旨在兼顾质量与多样性。参数 p 表示一个令牌被考虑时的最小概率,相对于最可能令牌的概率。例如,p=0.05 且最可能令牌概率为 0.9 时,值小于 0.045 的 logits 会被过滤掉。0.0
spring.ai.ollama.chat.tfs-z无尾采样用于减少低概率令牌对输出的影响。较高的值(例如 2.0)会更大地减少影响,而值 1.0 禁用此设置。1.0
spring.ai.ollama.chat.typical-p-1.0
spring.ai.ollama.chat.repeat-last-n设置模型回看多远以防止重复。(默认:64,0 = 禁用,-1 = num_ctx)64
spring.ai.ollama.chat.temperature模型的温度。提高温度会让模型更有创造性地回答。0.8
spring.ai.ollama.chat.repeat-penalty设置对重复施加惩罚的强度。较高的值(例如 1.5)更强烈地惩罚重复,而较低的值(例如 0.9)更宽松。1.1
spring.ai.ollama.chat.presence-penalty-0.0
spring.ai.ollama.chat.frequency-penalty-0.0
spring.ai.ollama.chat.mirostat启用 Mirostat 采样以控制困惑度。(默认:0,0 = 禁用,1 = Mirostat,2 = Mirostat 2.0)0
spring.ai.ollama.chat.mirostat-tau控制输出在连贯性与多样性之间的平衡。较低的值会带来更聚焦、更连贯的文本。5.0
spring.ai.ollama.chat.mirostat-eta影响算法对已生成文本反馈作出响应的速度。较低的学习率导致较慢的调整,而较高的学习率让算法更灵敏。0.1
spring.ai.ollama.chat.penalize-newline-true
spring.ai.ollama.chat.stop设置要使用的停止序列。遇到此模式时 LLM 会停止生成文本并返回。通过在 modelfile 中指定多个独立的 stop 参数可设多个停止模式。-
spring.ai.ollama.chat.tool-callbacks注册到 ChatModel 的工具回调。-

TIP

所有以 spring.ai.ollama.chat 为前缀的属性,都可通过在 Prompt 调用中添加请求专用的 chat-options 在运行时被覆盖。

运行时选项

OllamaChatOptions.java 类提供模型配置,例如要使用的模型、温度、思考模式等。

WARNING

OllamaOptions 类已被弃用。请改用 OllamaChatOptions(用于聊天模型)和 OllamaEmbeddingOptions(用于嵌入模型)。新类提供了类型安全、模型特定的配置选项。

在启动时,可通过 OllamaChatModel(api, options) 构造器或 spring.ai.ollama.chat.* 属性配置默认选项。

在运行时,你可以通过向 Prompt 调用添加新的、请求特定的选项来覆盖默认选项。 例如,要为某个特定请求覆盖默认的模型和温度:

java
ChatResponse response = chatModel.call(
    new Prompt(
        "Generate the names of 5 famous pirates.",
        OllamaChatOptions.builder()
            .model(OllamaModel.LLAMA3_1)
            .temperature(0.4)
            .build()
    ));

TIP

除模型特定的 OllamaChatOptions 外,你还可以使用一个可移植的 ChatOptions 实例,通过 ChatOptions#builder() 创建。

自动拉取模型

当模型在你的 Ollama 实例中不可用时,Spring AI Ollama 可以自动拉取它们。 此功能对开发和测试、以及把应用部署到新环境尤其有用。

TIP

你也可以按名称拉取数以千计的免费 GGUF Hugging Face 模型 之一。

拉取模型有三种策略:

  • always(定义于 PullModelStrategy.ALWAYS):始终拉取模型,即便它已可用。用于确保你使用的是模型的最新版本。
  • when_missing(定义于 PullModelStrategy.WHEN_MISSING):仅当模型尚未可用时才拉取。这可能导致使用较旧版本的模型。
  • never(定义于 PullModelStrategy.NEVER):从不自动拉取模型。

WARNING

由于下载模型可能耗时较长,不建议在生产环境使用自动拉取。取而代之,请考虑预先评估并预下载所需的模型。

所有通过配置属性和默认选项定义的模型,都可在启动时自动拉取。 你可以使用配置属性来配置拉取策略、超时和最大重试次数:

yaml
spring:
  ai:
    ollama:
      init:
        pull-model-strategy: always
        timeout: 60s
        max-retries: 1

WARNING

在所有指定模型都可在 Ollama 中获得之前,应用不会完成其初始化。取决于模型大小和网速,这可能会显著拖慢应用的启动时间。

你可以在启动时初始化额外的模型,这对在运行时动态使用的模型很有用:

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

若你只想把拉取策略应用到特定类型的模型,你可以把聊天模型从初始化任务中排除:

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

此配置会把拉取策略应用到除聊天模型以外的所有模型。

工具调用

OllamaChatModel 支持工具调用。模型可以请求执行工具,但它自己并不运行工具——由 Spring AI 处理执行。

TIP

你需要 Ollama 0.2.8 或更新版本来使用工具调用,且需要 Ollama 0.4.6 或更新版本来在流式模式下使用它。

对于大多数应用,请搭配自动注册的 ToolCallingAdvisor 使用 ChatClient —— 参见工具调用。若需要由你自己驱动该循环的底层控制,参见 ChatModel 工具调用。

思考模式(推理)

Ollama 为推理模型支持思考模式,这类模型能在给出最终答案前发出其内部推理过程。此特性对像 Qwen3、DeepSeek-v3.1、DeepSeek R1 和 GPT-OSS 这样的模型可用。

TIP

思考模式帮你理解模型的推理过程,并能为复杂问题改善响应质量。

WARNING

默认行为(Ollama 0.12+):具备思考能力的模型(如 qwen3:*-thinking、deepseek-r1、deepseek-v3.1)在未显式设置 think 选项时会默认自动启用思考。标准模型(如 qwen2.5:*、llama3.2)默认不启用思考。要显式控制这一行为,使用 .enableThinking() 或 .disableThinking()。

启用思考模式

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

java
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().getText();

你也可以显式禁用思考:

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

思考级别(仅 GPT-OSS)

GPT-OSS 模型需要显式的思考级别而非布尔值:

java
// 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()
    ));

访问思考内容

思考内容可在响应元数据中获得:

java
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().getText();
System.out.println("Answer: " + answer);
// Output: "The answer is 391"

带思考的流式

思考模式也能配合流式响应工作:

java
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().getText();

    if (thinking != null && !thinking.isEmpty()) {
        System.out.println("[Thinking] " + thinking);
    }
    if (content != null && !content.isEmpty()) {
        System.out.println("[Response] " + content);
    }
});

NOTE

当禁用思考或未设置时,thinking 元数据字段会为 null 或空。

多模态

多模态指的是模型同时理解和处理来自各种来源信息的能力,包括文本、图像、音频及其他数据格式。

Ollama 中具备多模态支持的模型有 LLaVA 和 BakLLaVA(见完整列表)。更多细节参阅 LLaVA: Large Language and Vision Assistant。

Ollama Message API 提供一个 "images" 参数,在消息中纳入一个 base64 编码图像的列表。

Spring AI 的 Message 接口通过引入 Media 类型来便利多模态 AI 模型。该类型涵盖消息中媒体附件的数据与详情,使用 Spring 的 org.springframework.util.MimeType 和一个 org.springframework.core.io.Resource 表示原始媒体数据。

下面是一个摘自 OllamaChatModelMultimodalIT.java 的直接了当代码示例,演示把用户文本与一张图像融合。

java
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 图像作为输入:

连同文本消息 "Explain what do you see on this picture?",并生成一个像这样的响应:

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 Schema。 除现有的、Spring AI 与模型无关的结构化输出之外,这些 API 提供了更强的控制与精确度。

结构化输出的两种模式

Ollama 通过 format 参数支持两种不同的结构化输出模式:

  1. 简单 "json" 格式:指示 Ollama 返回任意合法的 JSON 结构(模式不可预测)
  2. JSON Schema 格式:指示 Ollama 返回符合某个特定模式的 JSON(结构可预测)

简单 "json" 格式

当你想要 JSON 输出但不需要特定结构时使用它:

java
ChatResponse response = chatModel.call(
    new Prompt(
        "List 3 countries in Europe",
        OllamaChatOptions.builder()
            .model("llama3.2")
            .format("json")  // Any valid JSON
            .build()
    ));

模型可以返回它自选的任意 JSON 结构:

json
["France", "Germany", "Italy"]
// or
{"countries": ["France", "Germany", "Italy"]}
// or
{"data": {"european_countries": ["France", "Germany", "Italy"]}}

JSON Schema 格式(生产环境推荐)

当你需要一个有保证、可预测的结构时使用它:

java
String jsonSchema = """
{
    "type": "object",
    "properties": {
        "countries": {
            "type": "array",
            "items": { "type": "string" }
        }
    },
    "required": ["countries"]
}
""";

ChatResponse response = chatModel.call(
    new Prompt(
        "List 3 countries in Europe",
        OllamaChatOptions.builder()
            .model("llama3.2")
            .outputSchema(jsonSchema)  // Enforced schema
            .build()
    ));

模型必须返回这个确切结构:

json
{"countries": ["France", "Germany", "Italy"]}

配置

Spring AI 让你能通过 OllamaChatOptions 构建器以编程方式配置你的响应格式。

用聊天选项构建器配合 JSON Schema

你可以用 OllamaChatOptions 构建器以编程方式设置响应格式:

java
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())
            .outputSchema(jsonSchema)  // Pass JSON Schema as string
            .build());

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

与 BeanOutputConverter 工具集成

你可以借助现有的 BeanOutputConverter 工具,自动从你的领域对象生成 JSON Schema,并在稍后把结构化响应转换为领域实例:

java
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())
            .outputSchema(outputConverter.getJsonSchema())  // Get JSON Schema as string
            .build());

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

MathReasoning mathReasoning = this.outputConverter.convert(this.content);

NOTE

务必使用 @JsonProperty(required = true,...) 注解来生成一个准确地把字段标记为 required 的模式。

尽管这对 JSON Schema 是可选的,但为使结构化响应正确工作,建议使用它。

API 方法:.format() 与 .outputSchema()

Spring AI 提供两个方法来配置结构化输出:

方法用例示例
.format("json")简单 JSON 模式 - 任意结构.format("json")
.outputSchema(jsonSchemaString)JSON Schema 模式 - 强制结构.outputSchema("{\"type\":\"object\",...}")
.format(mapObject)JSON Schema 模式 - 替代 API.format(new JsonMapper().readValue(schema, Map.class))

TIP

对多数用例,用 .outputSchema(jsonSchemaString) 做 JSON Schema 校验,或用 .format("json") 做简单 JSON 输出。

.format(Map) 方式也受支持,但需要手工解析 JSON。

OpenAI API 兼容性

Ollama 与 OpenAI API 兼容,你可以用 Spring AI OpenAI 客户端与 Ollama 对话并使用工具。 为此,你需要把 OpenAI base URL 配置到你的 Ollama 实例:spring.ai.openai.chat.base-url=http://localhost:11434/v1,并选择一个所提供的 Ollama 模型:spring.ai.openai.chat.model=mistral。

TIP

当把 OpenAI 客户端与 Ollama 一起用时,你可以用 extraBody 选项 传入 Ollama 特定的参数(如 top_k、repeat_penalty、num_predict)。

这让你在使用 OpenAI 客户端的同时得以利用 Ollama 的全部能力。

经 OpenAI 兼容性获取推理内容

Ollama 的 OpenAI 兼容端点为具备思考能力的模型(如 qwen3:*-thinking、deepseek-r1、deepseek-v3.1)支持 reasoning_content 字段。 当把 Spring AI OpenAI 客户端与 Ollama 一起用时,模型的推理过程会被自动捕获并通过响应元数据提供。

NOTE

这是使用 Ollama 原生思考模式 API(在上文“思考模式(推理)”中记录)的一种替代方案。

两种方式都能在 Ollama 的思考模型上工作,但 OpenAI 兼容端点用 reasoning_content 字段名而非 thinking。

下面是一个通过 OpenAI 客户端从 Ollama 访问推理内容的示例:

java
// Configure Spring AI OpenAI client to point to Ollama
@Configuration
class OllamaConfig {
    @Bean
    OpenAiChatModel ollamaChatModel() {
        return OpenAiChatModel.builder()
            .options(OpenAiChatOptions.builder()
                .baseUrl("http://localhost:11434/v1")
                .apiKey("ollama")
                .model("deepseek-r1")  // or qwen3, deepseek-v3.1, etc.
                .build())
            .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().getText();
System.out.println("Answer: " + answer);

TIP

Ollama 中具备思考能力的模型(0.12+)在通过 OpenAI 兼容端点访问时会自动启用思考模式。

推理内容会被自动捕获,无需额外配置。

查看 OllamaWithOpenAiChatModelIT.java 测试,其中有在 Spring AI OpenAI 之上使用 Ollama 的示例。

HuggingFace 模型

Ollama 可开箱即用地访问所有 GGUF Hugging Face 聊天模型。 你可以按名拉取其中任何模型:ollama pull hf.co/<username>/<model-repository>,或配置自动拉取策略:自动拉取模型:

spring.ai.ollama.chat.model=hf.co/bartowski/gemma-2-2b-it-GGUF
spring.ai.ollama.init.pull-model-strategy=always
  • spring.ai.ollama.chat.model:指定要使用的 Hugging Face GGUF 模型。
  • spring.ai.ollama.init.pull-model-strategy=always:(可选)在启动时启用自动模型拉取。 对于生产环境,你应当预下载模型以避免延迟:ollama pull hf.co/bartowski/gemma-2-2b-it-GGUF。

示例控制器

创建 一个新的 Spring Boot 项目,并把 spring-ai-starter-model-ollama 添加到你的 pom(或 gradle)依赖。

在 src/main/resources 目录下添加一个 application.yaml 文件,以启用并配置 Ollama 聊天模型:

yaml
spring:
  ai:
    ollama:
      base-url: http://localhost:11434
      chat:
        options:
          model: mistral
          temperature: 0.7

TIP

用你的 Ollama 服务器 URL 替换 base-url。

这会创建一个可注入到你类中的 OllamaChatModel 实现。 下面是一个简单 @RestController 类的示例,它使用聊天模型进行文本生成。

java
@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 实现了 ChatModel 和 StreamingChatModel,并使用底层 api 连接到 Ollama 服务。

要使用它,把 spring-ai-ollama 依赖添加到你的项目的 Maven pom.xml 或 Gradle build.gradle 构建文件:

xml
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-ollama</artifactId>
</dependency>

TIP

参见 依赖管理 一节,把 Spring AI BOM 添加到你的构建文件。

TIP

spring-ai-ollama 依赖也提供对 OllamaEmbeddingModel 的访问。

关于 OllamaEmbeddingModel 的更多信息,参见 Ollama 嵌入模型 一节。

接下来,创建一个 OllamaChatModel 实例并用它发送请求以生成文本:

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

var chatModel = OllamaChatModel.builder()
                    .ollamaApi(ollamaApi)
                    .options(
                        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."));

OllamaChatOptions 为所有聊天请求提供配置信息。

底层 OllamaApi 客户端

OllamaApi 为 Ollama 聊天补全 API Ollama 聊天补全 API 提供一个轻量级 Java 客户端。

下面的类图展示了 OllamaApi 聊天接口与构建块:

NOTE

OllamaApi 是一个底层 API,不建议直接使用。请改用 OllamaChatModel。

下面是一个演示如何以编程方式使用该 API 的简单片段:

java
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);

BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。