Docker Model Runner 聊天
Docker Model Runner 是一个 AI 推理引擎,提供来自各种提供商的各种模型。
Spring AI 通过重用现有的 OpenAI 支持与 Docker Model Runner 集成ChatClient
.
为此,请将基 URL 设置为localhost:12434/engines
,然后选择提供的 LLM 模型之一。
检查 DockerModelRunnerWithOpenAiChatModelIT.java 测试 有关如何将 Docker Model Runner 与 Spring AI 结合使用的示例。
前提条件
-
下载适用于 Mac 的 Docker Desktop 4.40.0。
选择以下选项之一以启用 Model Runner:
选项 1:
-
启用 Model Runner
docker desktop enable model-runner --tcp 12434
. -
将 base-url 设置为
localhost:12434/engines
选项 2:
-
启用 Model Runner
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 Model Runner 的更多信息。
自动配置
Spring AI 入门模块的工件 ID 从版本 1.0.0.M7 开始已重命名。依赖项名称现在应遵循模型、矢量存储和 MCP Starters的更新命名模式。 有关更多信息,请参阅升级说明。 |
Spring AI 为 OpenAI Chat 客户端提供 Spring Boot 自动配置。
要启用它,请将以下依赖项添加到项目的 Maven 中pom.xml
文件:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
或将以下内容添加到您的 Gradle 中build.gradle
build 文件。
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-model-openai'
}
请参阅 Dependency Management 部分,将 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 |
Backoff interval 乘数。 |
5 |
spring.ai.retry.backoff.max-interval |
最大回退持续时间。 |
3 分钟 |
spring.ai.retry.on-client-errors |
如果为 false,则抛出 NonTransientAiException,并且不要尝试重试 |
false |
spring.ai.retry.exclude-on-http-codes |
不应触发重试的 HTTP 状态代码列表(例如,引发 NonTransientAiException)。 |
empty |
spring.ai.retry.on-http-codes |
应触发重试的 HTTP 状态代码列表(例如,引发 TransientAiException)。 |
empty |
连接属性
前缀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 |
Optional 会覆盖 |
- |
spring.ai.openai.chat.api-key |
Optional 覆盖 spring.ai.openai.api-key 以提供特定于聊天的 api-key |
- |
spring.ai.openai.chat.options.model |
要使用的 LLM 模型 |
- |
spring.ai.openai.chat.options.temperature |
控制生成完成项的明显创造性的采样温度。较高的值将使输出更具随机性,而较低的值将使结果更加集中和确定。不建议为相同的 completions 请求修改 temperature 和 top_p,因为这两个设置的交互很难预测。 |
0.8 |
spring.ai.openai.chat.options.frequencyPenalty |
介于 -2.0 和 2.0 之间的数字。正值会根据新标记到目前为止在文本中的现有频率来惩罚新标记,从而降低模型逐字重复同一行的可能性。 |
0.0 英尺 |
spring.ai.openai.chat.options.max代币 |
在聊天完成中生成的最大令牌数。输入标记和生成的标记的总长度受模型的上下文长度限制。 |
- |
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 |
最多 4 个序列,API 将在其中停止生成更多令牌。 |
- |
spring.ai.openai.chat.options.topP |
使用温度进行采样的替代方法,称为核抽样,其中模型考虑具有top_p概率质量的标记的结果。所以 0.1 意味着只考虑包含前 10% 概率质量的 token。我们通常建议更改此温度或温度,但不能同时更改两者。 |
- |
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 |
函数列表,由其名称标识,用于在单个提示请求中启用函数调用。具有这些名称的函数必须存在于 functionCallbacks 注册表中。 |
- |
spring.ai.openai.chat.options.stream-usage |
(仅用于流媒体)设置为添加一个额外的数据块,其中包含整个请求的令牌使用情况统计信息。这 |
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)
constructor 或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 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 函数调用的更多信息。
Samples控制器
创建一个新的 Spring Boot 项目并添加spring-ai-starter-model-openai
添加到您的 POM(或 Gradle)依赖项中。
添加application.properties
文件中的src/main/resources
目录中,以启用和配置 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
使用 Chat 模型生成文本的类。
@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);
}
}