Docker Model Runner Chat
Docker Model Runner 是一个 提供来自各种提供商的广泛模型的 AI 推理引擎。
Spring AI 通过重用现有的 OpenAI支持 与 Docker Model Runner 集成 ChatClient。为此,请将基本 URL 设置为 localhost:12434/engines
,然后选择提供的LLM 模型之一。
前提条件(Prerequisites)
- 下载适用于 Mac 4.40.0 的 Docker Desktop。
选择以下选项之一来启用模型运行器:
- 选项 1:
- 启用模型运行器
docker desktop enable model-runner --tcp 12434
。 - 将 base-url 设置为 localhost:12434/engines
- 启用模型运行器
- 选项 2:
- 启用模型运行器
docker desktop enable model-runner
。 - 使用 Testcontainers 并设置 base-url 如下:
`
java
@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();
}
### 自动配置(Auto-configuration)
Spring AI 为 OpenAI 聊天客户端提供了 Spring Boot 自动配置。
要启用它,添加 `spring-ai-starter-model-openai` 依赖到你的项目 Maven `pom.xml` 文件:
```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
}
聊天属性(Chat Properties)
Retry 属性(Retry Properties)
前缀 spring.ai.retry
用作属性前缀,允许您为 DeepSeek Chat 模型配置 retry 机制。
属性 | 描述 | 默认值 |
---|---|---|
spring.ai.retry.max-attempts |
最大重试次数。 | 10 |
spring.ai.retry.backoff.initial-interval |
指数退避策略的初始睡眠持续时间。 | 2 sec. |
spring.ai.retry.backoff.multiplier |
退避间隔乘数。 | 5 |
spring.ai.retry.backoff.max-interval |
最大退避持续时间。 | 3 min. |
spring.ai.retry.on-client-errors |
如果为false,抛出NonTransientAiException,并且不会对4xx 客户端错误码进行重试。 |
false |
spring.ai.retry.exclude-on-http-codes |
不应触发重试的HTTP状态码列表(例如抛出NonTransientAiException)。 | empty |
spring.ai.retry.on-http-codes |
应触发重试的HTTP状态码列表(例如抛出TransientAiException)。 | empty |
连接属性(Connection Properties)
前缀 spring.ai.openai
用作属性前缀,允许您连接到 OpenAI 。
配置属性(Configuration Properties)
运行时选项(Runtime Options )
** OpenAiChatOptions.java 提供模型配置,例如要使用的 temperature、maxToken、topP 等。**
启动时,可以使用 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()
));
工具 / 功能调用(Tool/Function Calling)
您可以使用 ChatModel 注册自定义 Java 函数,并让提供的模型智能地选择输出一个包含参数的 JSON 对象来调用一个或多个注册的函数。这是一种将 LLM 功能与外部工具和 API 连接起来的强大技术。
工具示例(Tool Example)
下面是一个简单的示例,说明如何使用 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 摄氏度。”
Sample Controller
这是一个简单的 @Controller 类的示例,它使用聊天模型来生成文本。
@RestController
public class ChatController {
private final OpenAiChatModel chatModel;
@Autowired
public ChatController(OpenAiChatModel chatModel) {
this.chatModel = chatModel;
}
/**
* 文本生成
* @param message 提示词
* @return 响应结果
*/
@GetMapping("/ai/generate")
@Operation(summary = "文本生成")
public Map<String, Object> generate(@RequestParam(value = "message", defaultValue = "你好!") String message) {
try {
String response = chatModel.call(message);
return Map.of(
"success", true,
"generation", response,
"message", "Generated successfully"
);
} catch (Exception e) {
return Map.of(
"success", false,
"error", e.getMessage(),
"message", "Generation failed"
);
}
}
@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);
}
}
最后编辑:Jeebiz 更新时间:2025-08-08 00:47