Docker Model Runner 聊天
Docker Model Runner 是一个 AI 推理引擎,提供来自 各种提供商 的广泛模型。
Spring AI 通过重用现有的 OpenAI 支持的 ChatClient
与 Docker Model Runner 集成。
为此,请将基本 URL 设置为 http://localhost:12434/engines
并选择一个提供的 LLM 模型。
查看 DockerModelRunnerWithOpenAiChatModelIT.java 测试
以获取如何将 Docker Model Runner 与 Spring AI 一起使用的示例。
先决条件
-
下载适用于 Mac 4.40.0 的 Docker Desktop。
选择以下选项之一来启用模型运行器:
选项 1:
-
启用模型运行器
docker desktop enable model-runner --tcp 12434
。 -
将基本 URL 设置为
http://localhost:12434/engines
选项 2:
-
启用模型运行器
docker desktop enable model-runner
。 -
使用 Testcontainers 并按如下方式设置基本 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 本地运行 LLM 博客文章来了解有关 Docker Model Runner 的更多信息。
自动配置
自 1.0.0.M7 版本以来,Spring AI 启动器模块的 artifact ID 已重命名。依赖项名称现在应遵循模型、向量存储和 MCP 启动器的更新命名模式。 请参阅 升级说明 以获取更多信息。 |
Spring AI 为 OpenAI 聊天客户端提供 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,并且不尝试对 |
false |
spring.ai.retry.exclude-on-http-codes |
不应触发重试(例如抛出 NonTransientAiException)的 HTTP 状态代码列表。 |
空 |
spring.ai.retry.on-http-codes |
应触发重试(例如抛出 TransientAiException)的 HTTP 状态代码列表。 |
空 |
连接属性
前缀 spring.ai.openai
用作属性前缀,允许您连接到 OpenAI。
属性 | 描述 | 默认值 |
---|---|---|
spring.ai.openai.base-url |
要连接的 URL。必须设置为 |
- |
spring.ai.openai.api-key |
任何字符串 |
- |
配置属性
现在通过前缀为 |
前缀 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.chat.api-key |
可选地覆盖 spring.ai.openai.api-key 以提供聊天特定的 api-key |
- |
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 |
指定模型必须输出的格式的对象。设置为 |
- |
spring.ai.openai.chat.options.seed |
此功能处于 Beta 阶段。如果指定,我们的系统将尽最大努力确定性地采样,以便具有相同种子和参数的重复请求应返回相同的结果。 |
- |
spring.ai.openai.chat.options.stop |
API 将停止生成更多令牌的最多 4 个序列。 |
- |
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 表示模型可以在生成消息或调用函数之间进行选择。通过 |
- |
spring.ai.openai.chat.options.user |
代表您的最终用户的唯一标识符,可以帮助 OpenAI 监控和检测滥用。 |
- |
spring.ai.openai.chat.options.functions |
函数列表,按其名称标识,用于在单个提示请求中启用函数调用。具有这些名称的函数必须存在于 functionCallbacks 注册表中。 |
- |
spring.ai.openai.chat.options.stream-usage |
(仅用于流式传输)设置为添加一个额外的块,其中包含整个请求的令牌使用统计信息。此块的 |
false |
spring.ai.openai.chat.options.proxy-tool-calls |
如果为 true,则 Spring AI 不会在内部处理函数调用,而是将其代理到客户端。然后,客户端负责处理函数调用,将其分派给适当的函数,并返回结果。如果为 false(默认值),则 Spring AI 将在内部处理函数调用。仅适用于支持函数调用的聊天模型 |
false |
所有带有 |
运行时选项
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 连接的强大技术。
工具示例
以下是使用 Docker Model Runner 函数调用与 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 函数调用 的更多信息。
示例控制器
创建 一个新的 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);
}
}