Docker 模型运行器聊天

Docker 模型运行器 是一个 AI 推理引擎,提供了来自 各种提供商 的广泛模型。

Spring AI 通过重用现有的基于 OpenAIChatClient 来与 Docker 模型运行器集成。为此,请将基本 URL 设置为 localhost:12434/engines 并选择一个提供的 LLM 模型

查看 DockerModelRunnerWithOpenAiChatModelIT.java 测试,了解如何在 Spring AI 中使用 Docker 模型运行器。

先决条件

  • 下载适用于 Mac 的 Docker Desktop 4.40.0。

选择以下选项之一来启用模型运行器

选项 1

  • 启用模型运行器 docker desktop enable model-runner --tcp 12434

  • 将 base-url 设置为 localhost:12434/engines

选项 2

  • 启用模型运行器 docker desktop enable model-runner

  • 使用 Testcontainers 并按如下方式设置 base-url

@Container
private static final SocatContainer socat = new SocatContainer().withTarget(80, "model-runner.docker.internal");

@Bean
public OpenAiApi chatCompletionApi() {
	var baseUrl = "http://%s:%d/engines".formatted(socat.getHost(), socat.getMappedPort(80));
	return OpenAiApi.builder().baseUrl(baseUrl).apiKey("test").build();
}

您可以阅读《使用 Docker 在本地运行 LLM》博客文章,了解有关 Docker 模型运行器的更多信息。

自动配置

自版本 1.0.0.M7 起,Spring AI starter 模块的 artifact ID 已更名。依赖名称现在应遵循模型、向量存储和 MCP starter 的更新命名模式。请参阅升级注意事项了解更多信息。

Spring AI 为 OpenAI Chat Client 提供了 Spring Boot 自动配置。要启用它,请将以下依赖项添加到项目的 Maven pom.xml 文件中

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

或将以下内容添加到您的 Gradle build.gradle 构建文件中。

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-model-openai'
}
请参阅依赖管理部分,将 Spring AI BOM 添加到您的构建文件中。

聊天属性

重试属性

前缀 spring.ai.retry 用作属性前缀,允许您配置 OpenAI 聊天模型的重试机制。

属性 描述 默认值

spring.ai.retry.max-attempts

最大重试次数。

10

spring.ai.retry.backoff.initial-interval

指数退避策略的初始等待时长。

2 秒。

spring.ai.retry.backoff.multiplier

退避间隔乘数。

5

spring.ai.retry.backoff.max-interval

最大退避时长。

3 分钟。

spring.ai.retry.on-client-errors

如果为 false,则抛出 NonTransientAiException,并且不对 4xx 客户端错误代码进行重试

false

spring.ai.retry.exclude-on-http-codes

不应触发重试的 HTTP 状态码列表(例如,抛出 NonTransientAiException)。

spring.ai.retry.on-http-codes

应触发重试的 HTTP 状态码列表(例如,抛出 TransientAiException)。

连接属性

前缀 spring.ai.openai 用作属性前缀,允许您连接到 OpenAI。

属性 描述 默认值

spring.ai.openai.base-url

要连接的 URL。必须设置为 hub.docker.com/u/ai

-

spring.ai.openai.api-key

任意字符串

-

配置属性

启用和禁用聊天自动配置现在通过带有前缀 spring.ai.model.chat 的顶级属性完成。

要启用,设置为 spring.ai.model.chat=openai(默认启用)

要禁用,设置为 spring.ai.model.chat=none(或任何与 openai 不匹配的值)

此更改允许在应用程序中配置多个模型。

前缀 spring.ai.openai.chat 是属性前缀,允许您配置 OpenAI 的聊天模型实现。

属性 描述 默认值

spring.ai.openai.chat.enabled(已移除且不再有效)

启用 OpenAI 聊天模型。

true

spring.ai.model.chat

启用 OpenAI 聊天模型。

openai

spring.ai.openai.chat.base-url

可选,覆盖 spring.ai.openai.base-url 以提供特定于聊天的 URL。必须设置为 localhost:12434/engines

-

spring.ai.openai.chat.api-key

可选,覆盖 spring.ai.openai.api-key 以提供特定于聊天的 API 密钥

-

spring.ai.openai.chat.options.model

要使用的 LLM 模型

-

spring.ai.openai.chat.options.temperature

控制生成补全文本表观创造性的采样温度。值越高,输出越随机;值越低,结果越聚焦和确定。不建议在同一补全请求中同时修改 temperature 和 top_p,因为这两个设置的相互作用难以预测。

0.8

spring.ai.openai.chat.options.frequencyPenalty

-2.0 到 2.0 之间的数值。正值根据新 token 在文本中出现的频率对其进行惩罚,从而降低模型重复相同文本的可能性。

0.0f

spring.ai.openai.chat.options.maxTokens

在聊天补全中生成的最大 token 数。输入 token 和生成 token 的总长度受模型的上下文长度限制。

-

spring.ai.openai.chat.options.n

为每个输入消息生成多少个聊天补全选项。请注意,您将根据所有选项中生成的 token 总数付费。将 n 保持为 1 以最小化成本。

1

spring.ai.openai.chat.options.presencePenalty

-2.0 到 2.0 之间的数值。正值根据新 token 是否已出现在文本中对其进行惩罚,从而增加模型讨论新主题的可能性。

-

spring.ai.openai.chat.options.responseFormat

指定模型必须输出的格式的对象。设置为 { "type": "json_object" } 可启用 JSON 模式,确保模型生成的消息是有效的 JSON。

-

spring.ai.openai.chat.options.seed

此功能处于 Beta 阶段。如果指定,我们的系统将尽最大努力进行确定性采样,以便使用相同的 seed 和参数的重复请求应返回相同的结果。

-

spring.ai.openai.chat.options.stop

API 将停止生成更多 token 的最多 4 个序列。

-

spring.ai.openai.chat.options.topP

一种替代温度采样的核采样方法,模型在该方法中考虑 top_p 概率质量的 token 结果。因此,0.1 表示仅考虑构成前 10% 概率质量的 token。我们通常建议修改 top_p 或 temperature,但不要同时修改两者。

-

spring.ai.openai.chat.options.tools

模型可能调用的工具列表。目前,只支持将函数作为工具。使用此项提供模型可能生成 JSON 输入的函数列表。

-

spring.ai.openai.chat.options.toolChoice

控制模型调用哪个(如果存在)函数。none 表示模型将不会调用函数,而是生成消息。auto 表示模型可以在生成消息或调用函数之间选择。通过 {"type: "function", "function": {"name": "my_function"}} 指定特定函数会强制模型调用该函数。当不存在函数时,none 是默认值。如果存在函数,auto 是默认值。

-

spring.ai.openai.chat.options.user

表示您的最终用户的唯一标识符,可以帮助 OpenAI 监控和检测滥用行为。

-

spring.ai.openai.chat.options.functions

函数列表,按名称标识,用于在单个 prompt 请求中启用函数调用。名称与此列表匹配的函数必须存在于 functionCallbacks 注册表中。

-

spring.ai.openai.chat.options.stream-usage

(仅适用于流式传输)设置为添加一个包含整个请求 token 使用统计信息的附加块。此块的 choices 字段是一个空数组,所有其他块也将包含一个 usage 字段,但值为 null。

false

spring.ai.openai.chat.options.proxy-tool-calls

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

false

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

运行时选项

OpenAiChatOptions.java 提供了模型配置,例如要使用的模型、温度、频率惩罚等。

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

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

ChatResponse response = chatModel.call(
    new Prompt(
        "Generate the names of 5 famous pirates.",
        OpenAiChatOptions.builder()
            .model("ai/gemma3:4B-F16")
        .build()
    ));
除了特定于模型的 OpenAiChatOptions 外,您还可以使用通过 ChatOptions#builder() 创建的可移植 ChatOptions 实例。

函数调用

Docker 模型运行器在选择支持工具/函数调用的模型时支持此功能。

您可以在 ChatModel 中注册自定义 Java 函数,并让提供的模型智能选择输出包含参数的 JSON 对象,以调用一个或多个已注册函数。这是将 LLM 能力与外部工具和 API 连接起来的强大技术。

工具示例

以下是一个使用 Docker 模型运行器函数调用与 Spring AI 的简单示例

spring.ai.openai.api-key=test
spring.ai.openai.base-url=http://localhost:12434/engines
spring.ai.openai.chat.options.model=ai/gemma3:4B-F16
@SpringBootApplication
public class DockerModelRunnerLlmApplication {

    public static void main(String[] args) {
        SpringApplication.run(DockerModelRunnerLlmApplication.class, args);
    }

    @Bean
    CommandLineRunner runner(ChatClient.Builder chatClientBuilder) {
        return args -> {
            var chatClient = chatClientBuilder.build();

            var response = chatClient.prompt()
                .user("What is the weather in Amsterdam and Paris?")
                .functions("weatherFunction") // reference by bean name.
                .call()
                .content();

            System.out.println(response);
        };
    }

    @Bean
    @Description("Get the weather in location")
    public Function<WeatherRequest, WeatherResponse> weatherFunction() {
        return new MockWeatherService();
    }

    public static class MockWeatherService implements Function<WeatherRequest, WeatherResponse> {

        public record WeatherRequest(String location, String unit) {}
        public record WeatherResponse(double temp, String unit) {}

        @Override
        public WeatherResponse apply(WeatherRequest request) {
            double temperature = request.location().contains("Amsterdam") ? 20 : 25;
            return new WeatherResponse(temperature, request.unit);
        }
    }
}

在此示例中,当模型需要天气信息时,它将自动调用 weatherFunction bean,该 bean 可以获取实时天气数据。预期响应为:“阿姆斯特丹目前的气温是 20 摄氏度,巴黎目前的气温是 25 摄氏度。”

了解更多关于 OpenAI 函数调用的信息。

示例 Controller

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

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

spring.ai.openai.api-key=test
spring.ai.openai.base-url=http://localhost:12434/engines
spring.ai.openai.chat.options.model=ai/gemma3:4B-F16

# Docker Model Runner doesn't support embeddings, so we need to disable them.
spring.ai.openai.embedding.enabled=false

这是一个简单的 @Controller 类示例,它使用聊天模型进行文本生成。

@RestController
public class ChatController {

    private final OpenAiChatModel chatModel;

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

    @GetMapping("/ai/generate")
    public Map 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);
    }
}