此版本仍在开发中,尚不被认为是稳定的。对于最新的快照版本,请使用 Spring AI 1.0.1spring-doc.cadn.net.cn

奥拉玛聊天

使用 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 Hugging Face 模型中的任何一个:spring-doc.cadn.net.cn

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

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

自动配置

Spring AI 自动配置、入门模块的工件名称发生了重大变化。 有关更多信息,请参阅升级说明spring-doc.cadn.net.cn

Spring AI 为 Ollama 聊天集成提供 Spring Boot 自动配置。 要启用它,请将以下依赖项添加到项目的 Mavenpom.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 BOM 添加到构建文件中。

基本属性

前缀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 服务器的基本 URL。spring-doc.cadn.net.cn

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

neverspring-doc.cadn.net.cn

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

等待模型被拉动需要多长时间。spring-doc.cadn.net.cn

5mspring-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 请求(高级)参数,例如model,keep-aliveformat以及 Ollama 模型options性能。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.聊天spring-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

属性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-gpu 的spring-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-gpu 的spring-doc.cadn.net.cn

当使用多个 GPU 时,此选项控制哪个 GPU 用于小张量,对于这些张量,在所有 GPU 之间拆分计算的开销是不值得的。有问题的 GPU 将使用稍微多一点的 VRAM 来存储临时结果的暂存缓冲区。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

返回所有标记的日志,而不仅仅是最后一个标记。要使补全能够返回 logprobs,这必须为 true。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.vocabspring-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

默认情况下,模型映射到内存中,这允许系统根据需要仅加载模型的必要部分。但是,如果模型大于您的 RAM 总量,或者您的系统可用内存不足,则使用 mmap 可能会增加分页的风险,从而对性能产生负面影响。禁用 mmap 会导致加载时间变慢,但如果您不使用 mlock,可能会减少分页次数。请注意,如果模型大于 RAM 总量,则关闭 mmap 将阻止模型加载。spring-doc.cadn.net.cn

spring-doc.cadn.net.cn

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

将模型锁定在内存中,防止在内存映射时将其换出。这可以提高性能,但会因为需要更多 RAM 来运行,并且在模型加载到 RAM 时可能会减慢加载时间,从而牺牲了内存映射的一些优势。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-预测spring-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的概率,考虑Tokens的最小概率。例如,如果 p=0.05 且最可能的标记的概率为 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.温度spring-doc.cadn.net.cn

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

0.8spring-doc.cadn.net.cn

spring.ai.ollama.chat.options.repeat-penaltyspring-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.频率惩罚spring-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.stopspring-doc.cadn.net.cn

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

-spring-doc.cadn.net.cn

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

函数列表,由其名称标识,以便在单个提示请求中启用函数调用。具有这些名称的函数必须存在于 functionCallbacks 注册表中。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

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

如果为 true,则 Spring AI 不会在内部处理函数调用,而是将它们代理到客户端。然后,客户端负责处理函数调用,将它们分派到适当的函数,并返回结果。如果为 false(默认值),则 Spring AI 将在内部处理函数调用。仅适用于支持函数调用的聊天模型spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

所有以spring.ai.ollama.chat.options可以通过将特定于请求的运行时选项添加到Prompt叫。

运行时选项

OllamaOptions.java类提供模型配置,例如要使用的模型、温度等。spring-doc.cadn.net.cn

启动时,可以使用OllamaChatModel(api, options)构造函数或spring.ai.ollama.chat.options.*性能。spring-doc.cadn.net.cn

在运行时,您可以通过向Prompt叫。 例如,要覆盖特定请求的默认模型和温度,请执行以下作:spring-doc.cadn.net.cn

ChatResponse response = chatModel.call(
    new Prompt(
        "Generate the names of 5 famous pirates.",
        OllamaOptions.builder()
            .model(OllamaModel.LLAMA3_1)
            .temperature(0.4)
            .build()
    ));
除了特定于模型的 OllamaOptions 之外,您还可以使用使用 ChatOptions#builder() 创建的可移植 ChatOptions 实例。

自动拉动模型

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

您还可以按名称提取数千个免费的 GGUF Hugging Face 模型中的任何一个。

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

  • always(定义在PullModelStrategy.ALWAYS):始终拉动模型,即使它已经可用。有助于确保您使用的是最新版本的模型。spring-doc.cadn.net.cn

  • when_missing(定义在PullModelStrategy.WHEN_MISSING):仅在模型尚不可用时才拉取模型。这可能会导致使用旧版本的模型。spring-doc.cadn.net.cn

  • never(定义在PullModelStrategy.NEVER):切勿自动拉动模型。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 或更高版本才能在流式处理模式下使用它们。

模 态

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

Ollama 中提供的一些支持多模态的模型是 LLaVABakLLaVA(请参阅完整列表)。 有关更多详细信息,请参阅 LLaVA:大型语言和视觉助手spring-doc.cadn.net.cn

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

Spring AI 的消息界面通过引入媒体类型促进了多模态 AI 模型。 这种类型包含有关消息中媒体附件的数据和详细信息,利用 Spring 的org.springframework.util.MimeTypeorg.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,
        OllamaOptions.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 Schema. 除了现有的与模型无关的结构化输出转换器之外,这些 API 还提供增强的控制和精度。spring-doc.cadn.net.cn

配置

Spring AI 允许您使用OllamaOptions架构工人。spring-doc.cadn.net.cn

使用聊天选项生成器

您可以使用OllamaOptionsbuilder,如下图所示: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",
        OllamaOptions.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,然后将结构化响应转换为特定于域的实例: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",
        OllamaOptions.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 架构是可选的,但建议结构化响应正常运行。

OpenAI API 兼容性

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

Ollama OpenAI API 兼容性

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

HuggingFace 模型

Ollama 可以开箱即用地访问所有 GGUF Hugging Face Chat 模型。您可以按名称提取以下任何模型: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:(可选)在启动时启用自动拉取模型。对于生产环境,您应该预先下载模型以避免延迟:ollama pull hf.co/bartowski/gemma-2-2b-it-GGUF.spring-doc.cadn.net.cn

Samples控制器

创建一个新的 Spring Boot 项目,并将spring-ai-starter-model-ollama到你的 pom(或 gradle)依赖项。spring-doc.cadn.net.cn

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

spring:
  ai:
    ollama:
      base-url: http://localhost:11434
      chat:
        options:
          model: mistral
          temperature: 0.7
base-url替换为您的 Ollama 服务器 URL。

这将创建一个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 实现了ChatModelStreamingChatModel并使用低级 OllamaApi 客户端连接到 Ollama 服务。spring-doc.cadn.net.cn

要使用它,请添加spring-ai-ollama对项目 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 BOM 添加到构建文件中。
spring-ai-ollama依赖项还提供了对OllamaEmbeddingModel. 有关OllamaEmbeddingModel请参阅 Ollama 嵌入模型部分。

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

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

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

OllamaOptions提供所有聊天请求的配置信息。spring-doc.cadn.net.cn

低级 OllamaApi 客户端

OllamaApi 为 Ollama 聊天补全 API Ollama 聊天补全 API 提供了一个轻量级的 Java 客户端。spring-doc.cadn.net.cn

以下类图说明了OllamaApi聊天界面和构建块:spring-doc.cadn.net.cn

OllamaApi 聊天补全 API 图
OllamaApi是一个低级 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(OllamaOptions.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(OllamaOptions.builder().temperature(0.9).build().toMap())
    .build();

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