跳到主要内容
版本:1.1.0

Ollama 聊天

Deepseek 3.2 中英对照 Ollama Ollama Chat

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

:::提示
Ollama 同样提供了与 OpenAI API 兼容的端点。OpenAI API 兼容性 部分说明了如何使用 Spring AI OpenAI 来连接 Ollama 服务器。
:::

前提条件​

你首先需要访问一个 Ollama 实例。有几种选择,包括以下几种:

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

ollama pull <model-name>

您还可以拉取数千个免费的 GGUF Hugging Face 模型:

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

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

自动配置​

备注

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

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

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

请参阅依赖管理部分,将 Spring AI BOM 添加到您的构建文件中。

基础属性​

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

属性描述默认值
spring.ai.ollama.base-urlOllama API 服务器运行的基础 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除了通过默认属性配置的模型之外,需要初始化的额外模型。[]

聊天属性​

备注

聊天自动配置的启用和禁用现在通过前缀为 spring.ai.model.chat 的顶级属性进行配置。

若要启用:spring.ai.model.chat=ollama(默认已启用)

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

此项变更是为了支持多个模型的配置。

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

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

属性描述默认值
spring.ai.ollama.chat.enabled (已移除且不再有效)启用 Ollama 聊天模型。true
spring.ai.model.chat启用 Ollama 聊天模型。ollama
spring.ai.ollama.chat.options.model要使用的支持的模型的名称。mistral
spring.ai.ollama.chat.options.format返回响应的格式。目前,唯一接受的值是 json。-
spring.ai.ollama.chat.options.keep_alive控制请求结束后,模型在内存中保持加载的时长。5m

其余的 options 属性基于 Ollama 有效参数与值 和 Ollama 类型。默认值基于 Ollama 类型默认值。

属性描述默认
spring.ai.ollama.chat.options.numa是否使用 NUMA。假
spring.ai.ollama.chat.options.num-ctx设置用于生成下一个令牌的上下文窗口大小。2048
spring.ai.ollama.chat.options.num-batch提示处理最大批量大小。512
spring.ai.ollama.chat.options.num-gpu发送到GPU的层数。在macOS系统上,默认值为1以启用Metal支持,0则禁用。此处设置为1表示NumGPU应动态配置。-1
spring.ai.ollama.chat.options.main-gpu在使用多 GPU 时,该选项控制用于存储小张量的 GPU,这些张量太小,不值得在所有 GPU 上分割计算。相关的 GPU 将使用稍多的 VRAM 来存储临时结果的暂存缓冲区。0
spring.ai.ollama.chat.options.low-vram-false
spring.ai.ollama.chat.options.f16-kv-true
spring.ai.ollama.chat.options.logits-all返回所有标记的对数几率,而不仅仅是最后一个。若要使补全返回对数概率,此设置必须为真。-
spring.ai.ollama.chat.options.vocab-only仅加载词汇表,不加载权重。-
spring.ai.ollama.chat.options.use-mmap默认情况下,模型会通过内存映射(mmap)方式加载到内存中,这使得系统能够按需仅加载模型所需部分。然而,如果模型尺寸大于系统总内存容量,或系统可用内存较低,使用mmap可能会增加页面换出(pageouts)风险,从而对性能产生负面影响。禁用mmap会导致加载时间变慢,但若不使用mlock,可能减少页面换出。请注意,如果模型尺寸超过系统总内存容量,关闭mmap将导致模型完全无法加载。空值
spring.ai.ollama.chat.options.use-mlock锁定模型在内存中,防止其在内存映射时被交换出去。这可以提高性能,但需要更多 RAM 来运行,并且模型加载到 RAM 时可能会减慢加载速度,从而牺牲了内存映射的一些优势。false
spring.ai.ollama.chat.options.num-thread设置计算时使用的线程数。默认情况下,Ollama 会自动检测以获得最佳性能。建议将此值设置为系统拥有的物理 CPU 核心数(而非逻辑核心数)。0 = 由运行时决定0
spring.ai.ollama.chat.options.num-keep-4
spring.ai.ollama.chat.options.seed设置用于生成的随机数种子。将此值设为特定数字将使模型在相同的提示下生成相同的文本。-1
spring.ai.ollama.chat.options.num-predict生成文本时要预测的最大标记数。(-1 = 无限生成,-2 = 填充上下文)-1
spring.ai.ollama.chat.options.top-k降低生成无意义内容的概率。较高的值(例如 100)会产生更多样化的答案,而较低的值(例如 10)则会更加保守。40
spring.ai.ollama.chat.options.top-p与top-k共同作用。较高的值(例如0.95)会生成更多样化的文本,而较低的值(例如0.5)则会产生更集中和保守的文本。0.9
spring.ai.ollama.chat.options.min-p作为 top_p 的替代方案,旨在确保质量与多样性之间的平衡。参数 p 表示一个 token 被考虑的最小概率,该概率是相对于最可能 token 的概率而言的。例如,当 p=0.05 且最可能 token 的概率为 0.9 时,值小于 0.045 的 logits 将被过滤掉。0.0
spring.ai.ollama.chat.options.tfs-zTail-free sampling 用于减少输出中概率较低词汇的影响。较高的数值(例如 2.0)会更大程度地减弱其影响,而数值为 1.0 时则会禁用此设置。1.0
spring.ai.ollama.chat.options.typical-p-1.0
spring.ai.ollama.chat.options.repeat-last-n设置模型回溯历史以防止重复生成的长度。(默认值:64,0 = 禁用,-1 = 使用上下文长度)64
spring.ai.ollama.chat.options.temperature模型的温度值。提高温度会使模型的回答更具创造性。0.8
spring.ai.ollama.chat.options.repeat-penalty设置对重复内容的惩罚强度。较高的值(例如1.5)会更强力地惩罚重复内容,而较低的值(例如0.9)则更为宽松。1.1
spring.ai.ollama.chat.options.presence-penalty-0.0
spring.ai.ollama.chat.options.frequency-penalty-0.0
spring.ai.ollama.chat.options.mirostat启用 Mirostat 采样以控制困惑度。(默认值:0,0 = 禁用,1 = Mirostat,2 = Mirostat 2.0)0
spring.ai.ollama.chat.options.mirostat-tau控制输出中连贯性与多样性之间的平衡。较低的值会使文本更加聚焦和连贯。5.0
spring.ai.ollama.chat.options.mirostat-eta影响算法对生成文本反馈的响应速度。较低的学习率会导致调整较慢,而较高的学习率会使算法响应更灵敏。0.1
spring.ai.ollama.chat.options.penalize-newline-真
spring.ai.ollama.chat.options.stop设置要使用的停止序列。当遇到此模式时,LLM 将停止生成文本并返回。可以通过在 modelfile 中指定多个独立的 stop 参数来设置多个停止模式。-
spring.ai.ollama.chat.options.tool-names在单个提示请求中启用的工具列表,以工具名称标识。这些名称对应的工具必须存在于 ToolCallback 注册表中。-
spring.ai.ollama.chat.options.tool-callbacks要注册到ChatModel的工具回调函数。-
spring.ai.ollama.chat.options.internal-tool-execution-enabled若为 false,Spring AI 将不会在内部处理工具调用,而是将其代理至客户端。此时客户端需负责处理工具调用、将其分派至相应函数并返回结果。若为 true(默认值),Spring AI 将在内部处理函数调用。仅适用于支持函数调用的聊天模型。真
提示

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

运行时选项​

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

important

OllamaOptions 类已被弃用。对于聊天模型,请使用 OllamaChatOptions;对于嵌入模型,请使用 OllamaEmbeddingOptions。新的类提供了类型安全、模型特定的配置选项。

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

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

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 实例,该实例可通过 ChatOptions#builder() 创建。

自动拉取模型​

Spring AI Ollama 能够在你的 Ollama 实例中缺少模型时自动拉取模型。这一特性对于开发和测试,以及将应用程序部署到新环境都特别有用。

:::提示
你也可以按名称拉取数千个免费的 GGUF Hugging Face 模型。
:::

拉取模型有三种策略:

  • always (定义于 PullModelStrategy.ALWAYS): 始终拉取模型,即使模型已经存在。这有助于确保你使用的是模型的最新版本。

  • when_missing (定义于 PullModelStrategy.WHEN_MISSING): 仅当模型不存在时才拉取。这可能导致使用的是模型的旧版本。

  • never (定义于 PullModelStrategy.NEVER): 永不自动拉取模型。

警告

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

所有通过配置属性及默认选项定义的模型,均可在启动时自动拉取。您可通过以下配置属性设置拉取策略、超时时间及最大重试次数:

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

应用在所有指定模型于Ollama中可用之前,将无法完成初始化。根据模型大小和网络连接速度,这可能会显著延长您应用的启动时间。

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

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

如果你想仅对特定类型的模型应用拉取策略,可以在初始化任务中排除聊天模型:

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

此配置将对除聊天模型之外的所有模型应用拉取策略。

函数调用​

您可以在 OllamaChatModel 中注册自定义 Java 函数,并让 Ollama 模型智能地选择输出一个 JSON 对象,其中包含调用一个或多个已注册函数所需的参数。这是一种强大的技术,可以将大型语言模型(LLM)的能力与外部工具及 API 连接起来。了解更多关于工具调用的信息。

提示

你需要 Ollama 0.2.8 或更高版本才能使用函数调用功能,需要 Ollama 0.4.6 或更高版本才能在流式模式下使用它们。

思维模式(推理)​

Ollama 支持推理模型的思考模式,能够在提供最终答案前输出其内部推理过程。该功能适用于 Qwen3、DeepSeek-v3.1、DeepSeek R1 和 GPT-OSS 等模型。

提示

思考模式能帮助您理解模型的推理过程,并可提升复杂问题的响应质量。

important

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

启用思考模式​

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

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

你也可以显式禁用思考功能:

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

思维层级 (仅限 GPT-OSS)​

GPT-OSS模型要求明确的思维层级,而非布尔值:

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

访问思考内容​

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

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"

流式思考​

思维模式同样支持流式响应:

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);
}
});
备注

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

多模态​

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

Ollama 中支持多模态的一些模型包括 LLaVA 和 BakLLaVA(详见完整列表)。更多详细信息,请参阅 LLaVA:大型语言与视觉助手。

Ollama 消息 API 提供了一个 "images" 参数,用于将一组 base64 编码的图像与消息结合。

Spring AI 的 Message 接口通过引入 Media 类型来支持多模态 AI 模型。该类型包含了消息中媒体附件的数据和详细信息,并使用 Spring 的 org.springframework.util.MimeType 和一个 org.springframework.core.io.Resource 来表示原始媒体数据。

以下是从 OllamaChatModelMultimodalIT.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 图像作为输入:

多模态测试图片

附带文本消息“解释一下你在这张图片上看到了什么?”,并生成如下回复:

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 还提供了更强的控制和精确性。

配置​

Spring AI 允许你使用 OllamaChatOptions 构建器以编程方式配置你的响应格式。

使用聊天选项构建器​

你可以通过 OllamaChatOptions 构建器以编程方式设置响应格式,如下所示:

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 Schema,随后将结构化响应转换为特定领域的实例:

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(required = true,…​) 注解来生成模式,以准确地将字段标记为 required。尽管这对于 JSON Schema 是可选的,但为了确保结构化响应正常工作,建议这样做。

OpenAI API 兼容性​

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

:::提示
在使用 Ollama 的 OpenAI 客户端时,你可以通过 extraBody 选项 传递 Ollama 特有的参数(例如 top_k、repeat_penalty、num_predict)。这让你能够在利用 OpenAI 客户端的同时,充分运用 Ollama 的全部功能。
:::

Ollama OpenAI API 兼容性

通过 OpenAI 兼容性实现推理内容​

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

备注

这是使用 Ollama 原生思维模式 API 的替代方案(上述思维模式(推理)部分已有文档说明)。两种方法都适用于 Ollama 的思维模型,但 OpenAI 兼容端点使用的是 reasoning_content 字段名称,而非 thinking。

以下是通过 OpenAI 客户端访问 Ollama 推理内容的示例:

// 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 测试文件,其中包含了在 Spring AI OpenAI 中使用 Ollama 的示例。

HuggingFace 模型​

Ollama 可以开箱即用地访问所有 GGUF Hugging Face 聊天模型。你可以通过名称拉取这些模型中的任何一个:ollama pull hf.co/<用户名>/<模型仓库> 或配置自动拉取策略:自动拉取模型:

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:指定要使用的 Hugging Face GGUF 模型。

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

示例控制器​

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

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

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

:::提示
将 base-url 替换为你的 Ollama 服务器 URL。
:::

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

@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,并使用底层 OllamaApi 客户端来连接 Ollama 服务。

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

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

请参考依赖管理部分,将 Spring AI BOM 添加到您的构建文件中。

提示

spring-ai-ollama 依赖项也提供了对 OllamaEmbeddingModel 的访问权限。有关 OllamaEmbeddingModel 的更多信息,请参阅 Ollama 嵌入模型 部分。

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

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."));

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

底层 OllamaApi 客户端​

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

以下类图展示了 OllamaApi 的聊天接口和构建模块:

OllamaApi 聊天补全 API 图示

备注

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

以下是一个简单的代码片段,展示了如何通过编程方式使用该API:

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