Ollama Chat

使用 Ollama,您可以在本地运行各种大型语言模型 (LLM) 并从中生成文本。Spring AI 通过 OllamaChatClient 支持 Ollama 文本生成。

Prerequisites

您首先需要在本地计算机上运行 Ollama。请参阅官方 Ollama 项目 README 以开始在本地计算机上运行模型。

安装 ollama run llama2 将下载一张 4GB 的 docker 镜像。

Add Repositories and BOM

Spring AI 工件发布在 Spring Milestone 和 Snapshot 存储库中。有关将这些存储库添加到你的构建系统的说明,请参阅 Repositories 部分。

为了帮助进行依赖项管理,Spring AI 提供了一个 BOM(物料清单)以确保在整个项目中使用一致版本的 Spring AI。有关将 Spring AI BOM 添加到你的构建系统的说明,请参阅 Dependency Management 部分。

Auto-configuration

Spring AI 为 Ollama 聊天客户端提供 Spring Boot 自动配置。如需启用,请将以下依赖项添加到项目的 Maven pom.xml 文件:

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

或添加到 Gradle build.gradle 构建文件中。

dependencies {
    implementation 'org.springframework.ai:spring-ai-ollama-spring-boot-starter'
}
  1. 参见 Dependency Management 部分,将 Spring AI BOM 添加到你的构建文件中。

Chat Properties

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

Property Description Default

spring.ai.ollama.base-url

Ollama API 服务器正在运行的基本 URL。

http://localhost:11434

前缀 spring.ai.ollama.chat.options 是用于为 Ollama 配置聊天客户端实现的属性前缀。

  1. options 属性基于 Ollama Valid Parameters and ValuesOllama Types。默认值基于: Ollama type defaults

Property Description Default

spring.ai.ollama.chat.enabled

Enable Ollama chat client.

true

spring.ai.ollama.chat.options.model

要使用的 supported models的名称。

mistral

spring.ai.ollama.chat.options.numa

Whether to use NUMA.

false

spring.ai.ollama.chat.options.num-ctx

设置用于生成下一个标记的上下文窗口的大小。

2048

spring.ai.ollama.chat.options.num-batch

???

512

spring.ai.ollama.chat.options.num-gqa

转换器层中 GQA 组的数量。某些模型需要此设置,例如,对于 llama2:70b,此设置是 8。

1

spring.ai.ollama.chat.options.num-gpu

发送到 GPU 的层数。在 macOS 上,默认为 1 以启用 Metal 支持,0 以禁用。这里的 1 表示应按动态方式设置 NumGPU。

-1

spring.ai.ollama.chat.options.main-gpu

???

-

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

???

true

spring.ai.ollama.chat.options.use-mlock

???

false

spring.ai.ollama.chat.options.embedding-only

???

false

spring.ai.ollama.chat.options.rope-frequency-base

???

10000.0

spring.ai.ollama.chat.options.rope-frequency-scale

???

1.0

spring.ai.ollama.chat.options.num-thread

设置在计算期间要使用的线程数。默认情况下,Ollama 将检测此值以获得最佳性能。建议将此值设置为系统中物理 CPU 内核数(而不是逻辑核心数)。0 = 让运行时决定

0

spring.ai.ollama.chat.options.num-keep

???

0

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.tfs-z

尾部自由采样用于减少输出中概率较低标记的影响。较高的值(例如 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 = num_ctx)

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

???

true

spring.ai.ollama.chat.options.stop

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

-

  1. 聊天选项列表将被审查。该 issue 将跟踪进度。

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

Chat Options

OllamaOptions.java 提供模型配置,例如要使用的模型、温度等。

在启动时,可以使用 OllamaChatClient(api, options) 构造函数或 spring.ai.ollama.chat.options.* 属性配置默认选项。

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

ChatResponse response = chatClient.call(
    new Prompt(
        "Generate the names of 5 famous pirates.",
        OllamaOptions.create()
            .withModel("llama2")
            .withTemperature(0.4)
    ));
  1. 除了模型特定的 OllamaOptions 之外,你还可以使用用 ChatOptionsBuilder#builder() 创建的便携式 ChatOptions 实例。

Sample Controller (Auto-configuration)

Create 一个新的 Spring Boot 项目,并将 spring-ai-openai-spring-boot-starter 添加到您的 pom(或 gradle)依赖项中。

src/main/resources 目录下添加一个 application.properties 文件,以启用和配置 OpenAI Chat 客户端:

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

base-url 替换为您的 Ollama 服务器 URL。

这将创建一个 OllamaChatClient 实现,你可以将其注入你的类。以下是一个使用聊天客户端进行文本生成的简单 @Controller 类的示例:

@RestController
public class ChatController {

    private final OllamaChatClient chatClient;

    @Autowired
    public ChatController(OllamaChatClient chatClient) {
        this.chatClient = chatClient;
    }

    @GetMapping("/ai/generate")
    public Map generate(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
        return Map.of("generation", chatClient.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 chatClient.stream(prompt);
    }

}

Manual Configuration

如果您不想使用 Spring Boot 自动配置,则可以在应用程序中手动配置 OllamaChatClientOllamaChatClient 实现 ChatClientStreamingChatClient 并使用 Low-level OpenAiApi Client 连接到 Ollama 服务。

要使用它,将 spring-ai-ollama 依赖项添加到项目的 Maven pom.xml 文件中:

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

或添加到 Gradle build.gradle 构建文件中。

dependencies {
    implementation 'org.springframework.ai:spring-ai-ollama'
}
  1. 参见 Dependency Management 部分,将 Spring AI BOM 添加到你的构建文件中。

  1. spring-ai-ollama 依赖还提供了对 OllamaEmbeddingClient 的访问。有关 OllamaEmbeddingClient 的更多信息,请参阅 Ollama Embedding Client 部分。

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

var ollamaApi = new OllamaApi();

var chatClient = new OllamaChatClient(ollamaApi).withModel(MODEL)
        .withDefaultOptions(OllamaOptions.create()
                .withModel(OllamaOptions.DEFAULT_MODEL)
                .withTemperature(0.9f));

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

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

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

Low-level OpenAiApi Client

OllamaApi 提供用于 Ollama Chat API 的轻量级 Java 客户端 Ollama Chat Completion API

以下类图说明了 OllamaApi 聊天界面和构建模块:

ollama chat completion api

下面是一个简单的片段,说明如何以编程方式使用 API:

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

// Sync request
var request = ChatRequest.builder("orca-mini")
    .withStream(false) // not streaming
    .withMessages(List.of(
            Message.builder(Role.SYSTEM)
                .withContent("You are geography teacher. You are talking to a student.")
                .build(),
            Message.builder(Role.USER)
                .withContent("What is the capital of Bulgaria and what is the size? "
                        + "What it the national anthem?")
                .build()))
    .withOptions(OllamaOptions.create().withTemperature(0.9f))
    .build();

ChatResponse response = ollamaApi.chat(request);

// Streaming request
var request2 = ChatRequest.builder("orca-mini")
    .withStream(true) // streaming
    .withMessages(List.of(Message.builder(Role.USER)
        .withContent("What is the capital of Bulgaria and what is the size? " + "What it the national anthem?")
        .build()))
    .withOptions(OllamaOptions.create().withTemperature(0.9f).toMap())
    .build();

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