跳到主要内容

Docker 模型运行器聊天

Deepseek 3.2 中英对照 Docker Model Runner Docker Model Runner Chat

Docker Model Runner 是一个 AI 推理引擎,提供来自多个供应商的多种模型。

Spring AI 通过与现有的基于 OpenAIChatClient 集成,实现了与 Docker Model Runner 的对接。为此,需将基础 URL 设置为 [localhost:12434/engines](http://localhost:12434/engines),并选择 LLM 模型 中提供的任意一个。

请查看 DockerModelRunnerWithOpenAiChatModelIT.java 测试文件,以了解如何在 Spring AI 中使用 Docker Model Runner 的示例。

先决条件

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

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

选项 1:

  • 启用 Model Runner docker desktop enable model-runner --tcp 12434

  • 将 base-url 设置为 [localhost:12434/engines](http://localhost:12434/engines)

选项 2:

  • 启用 Model Runner docker desktop enable model-runner

  • 使用 Testcontainers 并设置 base-url 如下:

@Container
private static final DockerModelRunnerContainer DMR = new DockerModelRunnerContainer("alpine/socat:1.7.4.3-r0");

@Bean
public OpenAiApi chatCompletionApi() {
var baseUrl = DMR.getOpenAIEndpoint();
return OpenAiApi.builder().baseUrl(baseUrl).apiKey("test").build();
}

想要了解更多关于Docker Model Runner的信息,可以阅读这篇博客文章:使用Docker本地运行LLM

自动配置

备注

自版本 1.0.0.M7 起,Spring AI starter 模块的构件 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,则针对 4xx 客户端错误代码抛出 NonTransientAiException,且不进行重试。false
spring.ai.retry.exclude-on-http-codes不应触发重试(例如,为了抛出 NonTransientAiException)的 HTTP 状态代码列表。empty
spring.ai.retry.on-http-codes应触发重试(例如,为了抛出 TransientAiException)的 HTTP 状态代码列表。empty

连接属性

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

属性描述默认值
spring.ai.openai.base-url要连接的 URL。必须设置为 [hub.docker.com/u/ai](https://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 聊天模型。
spring.ai.model.chat启用 OpenAI 聊天模型。openai
spring.ai.openai.chat.base-url可选配置,用于覆盖 spring.ai.openai.base-url 以提供特定于聊天的URL。必须设置为 [localhost:12434/engines](http://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采样温度控制生成内容的表观创造力。较高值会使输出更随机,较低值则会使结果更集中和确定。不建议在同一补全请求中同时修改温度值和top_p参数,因为这两个设置的交互作用难以预测。0.8
spring.ai.openai.chat.options.frequencyPenalty介于-2.0到2.0之间的数值。正值将根据新词元在现有文本中的出现频率对其进行惩罚,从而降低模型逐字重复相同内容的可能性。0.0f
spring.ai.openai.chat.options.maxTokens聊天补全中生成的最大令牌数。输入令牌和生成令牌的总长度受到模型上下文长度的限制。-
spring.ai.openai.chat.options.n为每条输入消息生成多少个聊天补全选项。请注意,您将根据所有选项中生成的总令牌数量付费。将 n 设为 1 以最小化成本。1
spring.ai.openai.chat.options.presencePenalty数值介于 -2.0 到 2.0 之间。正值将根据新标记是否已出现在当前文本中对其进行惩罚,从而增加模型讨论新话题的可能性。-
spring.ai.openai.chat.options.responseFormat一个用于指定模型必须输出的格式的对象。设置为 { "type": "json_object" } 可启用 JSON 模式,该模式保证模型生成的消息是有效的 JSON。-
spring.ai.openai.chat.options.seed此功能目前处于测试阶段。如果指定了种子参数,我们的系统将尽最大努力进行确定性采样,以确保使用相同种子和参数的重复请求能够返回相同的结果。-
spring.ai.openai.chat.options.stop最多4个序列,当API生成到这些序列时便会停止生成更多标记。-
spring.ai.openai.chat.options.topP作为温度采样的替代方案,有一种称为核心采样的方法,模型会考虑概率质量达到 top_p 的标记结果。因此,0.1 意味着只考虑构成前 10% 概率质量的标记。我们通常建议调整此参数或温度参数,但不要同时调整两者。-
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.stream-usage(仅限流式传输)设置后,将为整个请求添加一个包含令牌使用统计数据的额外数据块。该数据块的 choices 字段为空数组,所有其他数据块也将包含一个 usage 字段,但其值为 null。false
spring.ai.openai.chat.options.tool-names单次提示请求中启用的工具列表,以工具名称标识。这些工具名称必须存在于ToolCallback注册表中。-
spring.ai.openai.chat.options.tool-callbacks注册到ChatModel的工具回调。-
spring.ai.openai.chat.options.internal-tool-execution-enabled若为 false,Spring AI 不会在内部处理工具调用,而是将其代理至客户端。此时客户端需负责处理工具调用、将其分派至相应函数并返回结果。若为 true(默认值),Spring AI 将在内部处理函数调用。仅适用于支持函数调用的聊天模型。true
提示

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

函数调用

Docker Model Runner 在选择支持工具/函数调用的模型时,支持工具/函数调用功能。

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

工具示例

以下是一个简单的示例,展示了如何在Spring AI中使用Docker Model Runner进行函数调用:

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,从而获取实时天气数据。预期的响应是:“阿姆斯特丹当前天气为 20 摄氏度,巴黎当前天气为 25 摄氏度。”

进一步了解 OpenAI 函数调用

示例控制器

创建一个新的 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);
}
}