> ## Documentation Index
> Fetch the complete documentation index at: https://javaai.pig4cloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Docker Model Runner 聊天

[Docker Model Runner](https://docs.docker.com/desktop/features/model-runner/) 是一个 AI 推理引擎，提供来自[各种提供商](https://hub.docker.com/u/ai)的各种模型。

Spring AI 通过复用现有的 [OpenAI](/spring4ai/api/chat/openai-chat) 支持的 `ChatClient` 与 Docker Model Runner 集成。为此，请将基本 URL 设置为 `http://localhost:12434/engines` 并选择提供的 [LLM 模型](https://hub.docker.com/u/ai)之一。

请查看 [DockerModelRunnerWithOpenAiChatModelIT.java](https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-openai/src/test/java/org/springframework/ai/openai/chat/proxy/DockerModelRunnerWithOpenAiChatModelIT.java) 测试，获取如何将 Docker Model Runner 与 Spring AI 结合使用的示例。

## 前提条件

* 下载 Docker Desktop for Mac 4.40.0。

选择以下选项之一来启用 Model Runner：

### 选项 1：直接连接

* 启用 Model Runner：`docker desktop enable model-runner --tcp 12434`
* 将 base-url 设置为 `http://localhost:12434/engines`

### 选项 2：使用 Testcontainers

* 启用 Model Runner：`docker desktop enable model-runner`
* 使用 Testcontainers 并按如下方式设置 base-url：

```java theme={"system"}
@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();
}
```

<Tip>
  你可以通过阅读 [使用 Docker 在本地运行 LLM](https://www.docker.com/blog/run-llms-locally/) 博文来了解有关 Docker Model Runner 的更多信息。
</Tip>

## 自动配置

<Note>
  自 1.0.0.M7 版本以来，Spring AI 启动器模块的工件 ID 已重命名。依赖项名称现在应遵循模型、向量存储和 MCP 启动器的更新命名模式。
  有关更多信息，请参阅[升级说明](https://docs.spring.io/spring-ai/reference/upgrade-notes.html)。
</Note>

Spring AI 为 OpenAI 聊天客户端提供 Spring Boot 自动配置。
要启用它，请将以下依赖项添加到项目的构建文件中：

<Tabs>
  <Tab title="Maven">
    ```xml theme={"system"}
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-starter-model-openai</artifactId>
    </dependency>
    ```
  </Tab>

  <Tab title="Gradle">
    ```gradle theme={"system"}
    dependencies {
        implementation 'org.springframework.ai:spring-ai-starter-model-openai'
    }
    ```
  </Tab>
</Tabs>

<Tip>
  请参阅[依赖管理](/spring4ai/getting-started#dependency-management)部分，将 Spring AI BOM 添加到你的构建文件中。
</Tip>

### 聊天属性

#### 重试属性

前缀 `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，并且不尝试对 `4xx` 客户端错误代码进行重试 | false |
| 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。必须设置为 `https://hub.docker.com/u/ai` | -   |
| spring.ai.openai.api-key  | 任何字符串                                        | -   |

#### 配置属性

<Note>
  聊天自动配置的启用和禁用现在通过前缀为 `spring.ai.model.chat` 的顶级属性进行配置。

  要启用，`spring.ai.model.chat=openai` (默认启用)

  要禁用，`spring.ai.model.chat=none` (或任何与 openai 不匹配的值)

  此更改允许在你的应用程序中配置多个模型。
</Note>

前缀 `spring.ai.openai.chat` 是属性前缀，允许你配置 OpenAI 的聊天模型实现。

| 属性                                             | 描述                                                                                     | 默认值    |
| :--------------------------------------------- | :------------------------------------------------------------------------------------- | :----- |
| spring.ai.model.chat                           | 启用 OpenAI 聊天模型。                                                                        | openai |
| spring.ai.openai.chat.base-url                 | 可选地覆盖 `spring.ai.openai.base-url` 以提供特定于聊天的 url。必须设置为 `http://localhost:12434/engines` | -      |
| spring.ai.openai.chat.api-key                  | 可选地覆盖 spring.ai.openai.api-key 以提供特定于聊天的 api-key                                       | -      |
| spring.ai.openai.chat.options.model            | 要使用的 [LLM 模型](https://hub.docker.com/u/ai)                                             | -      |
| spring.ai.openai.chat.options.temperature      | 控制生成补全的明显创造性的采样温度。较高的值会使输出更随机，而较低的值会使结果更集中和确定。                                         | 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                | 为每个输入消息生成多少个聊天补全选项。                                                                    | 1      |
| spring.ai.openai.chat.options.presencePenalty  | -2.0 到 2.0 之间的数字。正值会根据新标记是否已出现在文本中对其进行惩罚。                                              | -      |
| spring.ai.openai.chat.options.responseFormat   | 指定模型必须输出的格式的对象。设置为 `{ "type": "json_object" }` 可启用 JSON 模式。                            | -      |
| spring.ai.openai.chat.options.seed             | 此功能处于测试阶段。如果指定，我们的系统将尽最大努力进行确定性采样。                                                     | -      |
| spring.ai.openai.chat.options.stop             | API 将停止生成更多标记的最多 4 个序列。                                                                | -      |
| spring.ai.openai.chat.options.topP             | 温度采样的替代方法，称为核采样。                                                                       | -      |
| spring.ai.openai.chat.options.tools            | 模型可能调用的工具列表。目前，仅支持函数作为工具。                                                              | -      |
| spring.ai.openai.chat.options.toolChoice       | 控制模型调用哪个（如果有）函数。                                                                       | -      |
| spring.ai.openai.chat.options.user             | 代表你的最终用户的唯一标识符。                                                                        | -      |
| spring.ai.openai.chat.options.functions        | 按名称标识的函数列表，用于启用函数调用。                                                                   | -      |
| spring.ai.openai.chat.options.stream-usage     | （仅限流式传输）设置为添加一个包含标记使用情况统计信息的附加块。                                                       | false  |
| spring.ai.openai.chat.options.proxy-tool-calls | 如果为 true，Spring AI 将不会在内部处理函数调用，而是将它们代理到客户端。                                           | false  |

<Tip>
  所有以 `spring.ai.openai.chat.options` 为前缀的属性都可以在运行时通过向 `Prompt` 调用添加特定于请求的运行时选项来覆盖。
</Tip>

## 运行时选项

[OpenAiChatOptions.java](https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-openai/src/main/java/org/springframework/ai/openai/OpenAiChatOptions.java) 提供模型配置，例如要使用的模型、温度、频率惩罚等。

在启动时，可以使用 `OpenAiChatModel(api, options)` 构造函数或 `spring.ai.openai.chat.options.*` 属性配置默认选项。

在运行时，你可以通过向 `Prompt` 调用添加新的、特定于请求的选项来覆盖默认选项。
例如，要为特定请求覆盖默认模型和温度：

```java theme={"system"}
ChatResponse response = chatModel.call(
    new Prompt(
        "生成 5 个著名海盗的名字。",
        OpenAiChatOptions.builder()
            .model("ai/gemma3:4B-F16")
        .build()
    ));
```

<Tip>
  除了特定于模型的 [OpenAiChatOptions](https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-openai/src/main/java/org/springframework/ai/openai/OpenAiChatOptions.java)之外，你还可以使用通过 [ChatOptions#builder()](https://github.com/spring-projects/spring-ai/blob/main/spring-ai-client-chat/src/main/java/org/springframework/ai/chat/prompt/ChatOptions.java) 创建的可移植 [ChatOptions](https://github.com/spring-projects/spring-ai/blob/main/spring-ai-client-chat/src/main/java/org/springframework/ai/chat/prompt/ChatOptions.java) 实例。
</Tip>

## 函数调用

当选择支持它的模型时，Docker Model Runner 支持工具/函数调用。

你可以使用 ChatModel 注册自定义 Java 函数，并让提供的模型智能地选择输出一个 JSON 对象，其中包含调用一个或多个已注册函数的参数。
这是将 LLM 功能与外部工具和 API 连接起来的强大技术。

### 工具示例

以下是如何将 Docker Model Runner 函数调用与 Spring AI 结合使用的简单示例：

```properties theme={"system"}
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
```

```java theme={"system"}
@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("阿姆斯特丹和巴黎的天气怎么样？")
                .functions("weatherFunction") // 按 bean 名称引用。
                .call()
                .content();

            System.out.println(response);
        };
    }

    @Bean
    @Description("获取某个位置的天气")
    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 摄氏度。"

<Tip>
  阅读有关 OpenAI [函数调用](/spring4ai/api/chat/functions/openai-chat-functions)的更多信息。
</Tip>

## 示例控制器

[创建](https://start.spring.io/)一个新的 Spring Boot 项目，并将 `spring-ai-starter-model-openai` 添加到你的 pom (或 gradle) 依赖项中。

在 `src/main/resources` 目录下添加一个 `application.properties` 文件，以启用和配置 OpenAi 聊天模型：

```properties theme={"system"}
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 不支持嵌入，因此我们需要禁用它们。
spring.ai.openai.embedding.enabled=false
```

<Card title="文档有误？请协助编辑" icon="pencil" href="https://github.com/javaai-pig4cloud-com/javaai-docs/edit/main/spring-ai/api/chat/dmr-chat.mdx">
  发现文档问题？点击此处直接在 GitHub 上编辑并提交 PR，帮助我们改进文档！
</Card>
