Docker 模型執行器聊天
Docker 模型執行器是一個 AI 推理引擎,提供來自各種提供商的廣泛模型。
Spring AI 透過重用現有OpenAI支援的ChatClient來與 Docker 模型執行器整合。為此,將基本 URL 設定為localhost:12434/engines,並選擇其中一個提供的LLM 模型。
請查閱DockerModelRunnerWithOpenAiChatModelIT.java測試,瞭解如何將 Docker 模型執行器與 Spring AI 結合使用的示例。
前提條件
-
下載 Docker Desktop for Mac 4.40.0。
選擇以下選項之一啟用模型執行器
選項 1
-
啟用模型執行器
docker desktop enable model-runner --tcp 12434。 -
將基本 URL 設定為
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 模型執行器的更多資訊。
自動配置
|
自 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,並且不嘗試重試 |
假 |
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。必須設定為 |
- |
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 表示模型可以在生成訊息或呼叫函式之間進行選擇。透過 {"type: "function", "function": {"name": "my_function"}} 指定特定函式會強制模型呼叫該函式。當沒有函式存在時,none 是預設值。如果存在函式,auto 是預設值。 |
- |
spring.ai.openai.chat.options.user |
代表您的終端使用者的唯一識別符號,可以幫助 OpenAI 監控和檢測濫用。 |
- |
spring.ai.openai.chat.options.stream-usage |
(僅限流式傳輸)設定為新增一個額外的塊,其中包含整個請求的令牌使用統計資訊。此塊的 |
假 |
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 模型執行器在選擇支援工具/函式呼叫的模型時支援此功能。
您可以使用 ChatModel 註冊自定義 Java 函式,並讓提供的模型智慧地選擇輸出一個 JSON 物件,其中包含呼叫一個或多個已註冊函式的引數。這是一種將 LLM 功能與外部工具和 API 連線起來的強大技術。
工具示例
下面是使用 Spring AI 呼叫 Docker 模型執行器函式的一個簡單示例
spring.ai.openai.api-key=test
spring.ai.openai.base-url=https://: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=https://: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);
}
}