|
| 1 | += Docker Model Runner Chat |
| 2 | + |
| 3 | +https://docs.docker.com/desktop/features/model-runner/[Docker Model Runner] is an AI Inference Engine offering a wide range of models from link:https://hub.docker.com/u/ai[various providers]. |
| 4 | + |
| 5 | +Spring AI integrates with the Docker Model Runner by reusing the existing xref::api/chat/openai-chat.adoc[OpenAI] client. |
| 6 | +For this you need to set the base-url to `http://localhost:12434/engines` and select one of the provided https://hub.docker.com/u/ai[LLM models]. |
| 7 | + |
| 8 | +Check the https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-openai/src/test/java/org/springframework/ai/openai/chat/proxy/DockerModelRunnerWithOpenAiChatModelIT.java[DockerModelRunnerWithOpenAiChatModelIT.java] tests |
| 9 | +for examples of using Docker Model Runner with Spring AI. |
| 10 | + |
| 11 | +== Prerequisite |
| 12 | + |
| 13 | +* Download Docker Desktop for Mac 4.40.0. |
| 14 | + |
| 15 | +Choose one of the following options to enable the Model Runner: |
| 16 | + |
| 17 | +Option 1: |
| 18 | + |
| 19 | +* Enable Model Runner `docker desktop enable model-runner --tcp 12434`. |
| 20 | +* Set the base-url to `http://localhost:12434/engines` |
| 21 | + |
| 22 | +Option 2: |
| 23 | + |
| 24 | +* Enable Model Runner `docker desktop enable model-runner`. |
| 25 | +* Use Testcontainers and set the base-url as follows: |
| 26 | + |
| 27 | +[source,java] |
| 28 | +---- |
| 29 | +@Container |
| 30 | +private static final SocatContainer socat = new SocatContainer().withTarget(80, "model-runner.docker.internal"); |
| 31 | +
|
| 32 | +@Bean |
| 33 | +public OpenAiApi chatCompletionApi() { |
| 34 | + var baseUrl = "http://%s:%d/engines".formatted(socat.getHost(), socat.getMappedPort(80)); |
| 35 | + return OpenAiApi.builder().baseUrl(baseUrl).apiKey("test").build(); |
| 36 | +} |
| 37 | +---- |
| 38 | + |
| 39 | +You can learn more about the Docker Model Runner by reading the https://www.docker.com/blog/run-llms-locally/[Run LLMs Locally with Docker] blog post. |
| 40 | + |
| 41 | +== Auto-configuration |
| 42 | + |
| 43 | +[NOTE] |
| 44 | +==== |
| 45 | +There has been a significant change in the Spring AI auto-configuration, starter modules' artifact names. |
| 46 | +Please refer to the https://docs.spring.io/spring-ai/reference/upgrade-notes.html[upgrade notes] for more information. |
| 47 | +==== |
| 48 | + |
| 49 | +Spring AI provides Spring Boot auto-configuration for the OpenAI Chat Client. |
| 50 | +To enable it add the following dependency to your project's Maven `pom.xml` file: |
| 51 | + |
| 52 | +[source, xml] |
| 53 | +---- |
| 54 | +<dependency> |
| 55 | + <groupId>org.springframework.ai</groupId> |
| 56 | + <artifactId>spring-ai-starter-model-openai</artifactId> |
| 57 | +</dependency> |
| 58 | +---- |
| 59 | + |
| 60 | +or to your Gradle `build.gradle` build file. |
| 61 | + |
| 62 | +[source,groovy] |
| 63 | +---- |
| 64 | +dependencies { |
| 65 | + implementation 'org.springframework.ai:spring-ai-starter-model-openai' |
| 66 | +} |
| 67 | +---- |
| 68 | + |
| 69 | +TIP: Refer to the xref:getting-started.adoc#dependency-management[Dependency Management] section to add the Spring AI BOM to your build file. |
| 70 | + |
| 71 | +=== Chat Properties |
| 72 | + |
| 73 | +==== Retry Properties |
| 74 | + |
| 75 | +The prefix `spring.ai.retry` is used as the property prefix that lets you configure the retry mechanism for the OpenAI chat model. |
| 76 | + |
| 77 | +[cols="3,5,1", stripes=even] |
| 78 | +|==== |
| 79 | +| Property | Description | Default |
| 80 | + |
| 81 | +| spring.ai.retry.max-attempts | Maximum number of retry attempts. | 10 |
| 82 | +| spring.ai.retry.backoff.initial-interval | Initial sleep duration for the exponential backoff policy. | 2 sec. |
| 83 | +| spring.ai.retry.backoff.multiplier | Backoff interval multiplier. | 5 |
| 84 | +| spring.ai.retry.backoff.max-interval | Maximum backoff duration. | 3 min. |
| 85 | +| spring.ai.retry.on-client-errors | If false, throw a NonTransientAiException, and do not attempt retry for `4xx` client error codes | false |
| 86 | +| spring.ai.retry.exclude-on-http-codes | List of HTTP status codes that should not trigger a retry (e.g. to throw NonTransientAiException). | empty |
| 87 | +| spring.ai.retry.on-http-codes | List of HTTP status codes that should trigger a retry (e.g. to throw TransientAiException). | empty |
| 88 | +|==== |
| 89 | + |
| 90 | +==== Connection Properties |
| 91 | + |
| 92 | +The prefix `spring.ai.openai` is used as the property prefix that lets you connect to OpenAI. |
| 93 | + |
| 94 | +[cols="3,5,1", stripes=even] |
| 95 | +|==== |
| 96 | +| Property | Description | Default |
| 97 | + |
| 98 | +| spring.ai.openai.base-url | The URL to connect to. Must be set to `https://hub.docker.com/u/ai` | - |
| 99 | +| spring.ai.openai.api-key | Any string | - |
| 100 | +|==== |
| 101 | + |
| 102 | +==== Configuration Properties |
| 103 | + |
| 104 | +[NOTE] |
| 105 | +==== |
| 106 | +Enabling and disabling of the chat auto-configurations are now configured via top level properties with the prefix `spring.ai.model.chat`. |
| 107 | +
|
| 108 | +To enable, spring.ai.model.chat=openai (It is enabled by default) |
| 109 | +
|
| 110 | +To disable, spring.ai.model.chat=none (or any value which doesn't match openai) |
| 111 | +
|
| 112 | +This change is done to allow configuration of multiple models. |
| 113 | +==== |
| 114 | + |
| 115 | +The prefix `spring.ai.openai.chat` is the property prefix that lets you configure the chat model implementation for OpenAI. |
| 116 | + |
| 117 | +[cols="3,5,1", stripes=even] |
| 118 | +|==== |
| 119 | +| Property | Description | Default |
| 120 | + |
| 121 | +| spring.ai.openai.chat.enabled (Removed and no longer valid) | Enable OpenAI chat model. | true |
| 122 | +| spring.ai.model.chat | Enable OpenAI chat model. | openai |
| 123 | +| spring.ai.openai.chat.base-url | Optional overrides the spring.ai.openai.base-url to provide chat specific url. Must be set to `http://localhost:12434/engines` | - |
| 124 | +| spring.ai.openai.chat.api-key | Optional overrides the spring.ai.openai.api-key to provide chat specific api-key | - |
| 125 | +| spring.ai.openai.chat.options.model | The link:https://hub.docker.com/u/ai[LLM model] to use | - |
| 126 | +| spring.ai.openai.chat.options.temperature | The sampling temperature to use that controls the apparent creativity of generated completions. Higher values will make output more random while lower values will make results more focused and deterministic. It is not recommended to modify temperature and top_p for the same completions request as the interaction of these two settings is difficult to predict. | 0.8 |
| 127 | +| spring.ai.openai.chat.options.frequencyPenalty | Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. | 0.0f |
| 128 | +| spring.ai.openai.chat.options.maxTokens | The maximum number of tokens to generate in the chat completion. The total length of input tokens and generated tokens is limited by the model's context length. | - |
| 129 | +| spring.ai.openai.chat.options.n | How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep n as 1 to minimize costs. | 1 |
| 130 | +| spring.ai.openai.chat.options.presencePenalty | Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. | - |
| 131 | +| spring.ai.openai.chat.options.responseFormat | An object specifying the format that the model must output. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON.| - |
| 132 | +| spring.ai.openai.chat.options.seed | This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same seed and parameters should return the same result. | - |
| 133 | +| spring.ai.openai.chat.options.stop | Up to 4 sequences where the API will stop generating further tokens. | - |
| 134 | +| spring.ai.openai.chat.options.topP | An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both. | - |
| 135 | +| spring.ai.openai.chat.options.tools | A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs for. | - |
| 136 | +| spring.ai.openai.chat.options.toolChoice | Controls which (if any) function is called by the model. none means the model will not call a function and instead generates a message. auto means the model can pick between generating a message or calling a function. Specifying a particular function via {"type: "function", "function": {"name": "my_function"}} forces the model to call that function. none is the default when no functions are present. auto is the default if functions are present. | - |
| 137 | +| spring.ai.openai.chat.options.user | A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. | - |
| 138 | +| spring.ai.openai.chat.options.functions | List of functions, identified by their names, to enable for function calling in a single prompt requests. Functions with those names must exist in the functionCallbacks registry. | - |
| 139 | +| spring.ai.openai.chat.options.stream-usage | (For streaming only) Set to add an additional chunk with token usage statistics for the entire request. The `choices` field for this chunk is an empty array and all other chunks will also include a usage field, but with a null value. | false |
| 140 | +| spring.ai.openai.chat.options.proxy-tool-calls | If true, the Spring AI will not handle the function calls internally, but will proxy them to the client. Then is the client's responsibility to handle the function calls, dispatch them to the appropriate function, and return the results. If false (the default), the Spring AI will handle the function calls internally. Applicable only for chat models with function calling support | false |
| 141 | +|==== |
| 142 | + |
| 143 | +TIP: All properties prefixed with `spring.ai.openai.chat.options` can be overridden at runtime by adding a request specific <<chat-options>> to the `Prompt` call. |
| 144 | + |
| 145 | +== Runtime Options [[chat-options]] |
| 146 | + |
| 147 | +The https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-openai/src/main/java/org/springframework/ai/openai/OpenAiChatOptions.java[OpenAiChatOptions.java] provides model configurations, such as the model to use, the temperature, the frequency penalty, etc. |
| 148 | + |
| 149 | +On start-up, the default options can be configured with the `OpenAiChatModel(api, options)` constructor or the `spring.ai.openai.chat.options.*` properties. |
| 150 | + |
| 151 | +At run-time you can override the default options by adding new, request specific, options to the `Prompt` call. |
| 152 | +For example to override the default model and temperature for a specific request: |
| 153 | + |
| 154 | +[source,java] |
| 155 | +---- |
| 156 | +ChatResponse response = chatModel.call( |
| 157 | + new Prompt( |
| 158 | + "Generate the names of 5 famous pirates.", |
| 159 | + OpenAiChatOptions.builder() |
| 160 | + .model("ai/gemma3:4B-F16") |
| 161 | + .build() |
| 162 | + )); |
| 163 | +---- |
| 164 | + |
| 165 | +TIP: In addition to the model specific https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-openai/src/main/java/org/springframework/ai/openai/OpenAiChatOptions.java[OpenAiChatOptions] you can use a portable https://github.com/spring-projects/spring-ai/blob/main/spring-ai-client-chat/src/main/java/org/springframework/ai/chat/prompt/ChatOptions.java[ChatOptions] instance, created with the https://github.com/spring-projects/spring-ai/blob/main/spring-ai-client-chat/src/main/java/org/springframework/ai/chat/prompt/ChatOptions.java[ChatOptions#builder()]. |
| 166 | + |
| 167 | +== Function Calling |
| 168 | + |
| 169 | +Docker Model Runner supports Tool/Function calling when selecting a model that supports it. |
| 170 | + |
| 171 | +You can register custom Java functions with your ChatModel and have the provided model intelligently choose to output a JSON object containing arguments to call one or many of the registered functions. |
| 172 | +This is a powerful technique to connect the LLM capabilities with external tools and APIs. |
| 173 | + |
| 174 | +=== Tool Example |
| 175 | + |
| 176 | +Here's a simple example of how to use Docker Model Runner function calling with Spring AI: |
| 177 | + |
| 178 | +[source,application.properties] |
| 179 | +---- |
| 180 | +spring.ai.openai.api-key=test |
| 181 | +spring.ai.openai.base-url=http://localhost:12434/engines |
| 182 | +spring.ai.openai.chat.options.model=ai/gemma3:4B-F16 |
| 183 | +---- |
| 184 | + |
| 185 | +[source,java] |
| 186 | +---- |
| 187 | +@SpringBootApplication |
| 188 | +public class DockerModelRunnerLlmApplication { |
| 189 | +
|
| 190 | + public static void main(String[] args) { |
| 191 | + SpringApplication.run(DockerModelRunnerLlmApplication.class, args); |
| 192 | + } |
| 193 | +
|
| 194 | + @Bean |
| 195 | + CommandLineRunner runner(ChatClient.Builder chatClientBuilder) { |
| 196 | + return args -> { |
| 197 | + var chatClient = chatClientBuilder.build(); |
| 198 | +
|
| 199 | + var response = chatClient.prompt() |
| 200 | + .user("What is the weather in Amsterdam and Paris?") |
| 201 | + .functions("weatherFunction") // reference by bean name. |
| 202 | + .call() |
| 203 | + .content(); |
| 204 | +
|
| 205 | + System.out.println(response); |
| 206 | + }; |
| 207 | + } |
| 208 | +
|
| 209 | + @Bean |
| 210 | + @Description("Get the weather in location") |
| 211 | + public Function<WeatherRequest, WeatherResponse> weatherFunction() { |
| 212 | + return new MockWeatherService(); |
| 213 | + } |
| 214 | +
|
| 215 | + public static class MockWeatherService implements Function<WeatherRequest, WeatherResponse> { |
| 216 | +
|
| 217 | + public record WeatherRequest(String location, String unit) {} |
| 218 | + public record WeatherResponse(double temp, String unit) {} |
| 219 | +
|
| 220 | + @Override |
| 221 | + public WeatherResponse apply(WeatherRequest request) { |
| 222 | + double temperature = request.location().contains("Amsterdam") ? 20 : 25; |
| 223 | + return new WeatherResponse(temperature, request.unit); |
| 224 | + } |
| 225 | + } |
| 226 | +} |
| 227 | +---- |
| 228 | + |
| 229 | +In this example, when the model needs weather information, it will automatically call the `weatherFunction` bean, which can then fetch real-time weather data. |
| 230 | +The expected response looks like this: "The weather in Amsterdam is currently 20 degrees Celsius, and the weather in Paris is currently 25 degrees Celsius." |
| 231 | + |
| 232 | +Read more about OpenAI link:https://docs.spring.io/spring-ai/reference/api/chat/functions/openai-chat-functions.html[Function Calling]. |
| 233 | + |
| 234 | + |
| 235 | +== Sample Controller |
| 236 | + |
| 237 | +https://start.spring.io/[Create] a new Spring Boot project and add the `spring-ai-starter-model-openai` to your pom (or gradle) dependencies. |
| 238 | + |
| 239 | +Add a `application.properties` file, under the `src/main/resources` directory, to enable and configure the OpenAi chat model: |
| 240 | + |
| 241 | +[source,application.properties] |
| 242 | +---- |
| 243 | +spring.ai.openai.api-key=test |
| 244 | +spring.ai.openai.base-url=http://localhost:12434/engines |
| 245 | +spring.ai.openai.chat.options.model=ai/gemma3:4B-F16 |
| 246 | +
|
| 247 | +# The Docker Model Runner doesn't support embeddings, so we need to disable it. |
| 248 | +spring.ai.openai.embedding.enabled=false |
| 249 | +---- |
| 250 | + |
| 251 | + |
| 252 | +Here is an example of a simple `@Controller` class that uses the chat model for text generations. |
| 253 | + |
| 254 | +[source,java] |
| 255 | +---- |
| 256 | +@RestController |
| 257 | +public class ChatController { |
| 258 | +
|
| 259 | + private final OpenAiChatModel chatModel; |
| 260 | +
|
| 261 | + @Autowired |
| 262 | + public ChatController(OpenAiChatModel chatModel) { |
| 263 | + this.chatModel = chatModel; |
| 264 | + } |
| 265 | +
|
| 266 | + @GetMapping("/ai/generate") |
| 267 | + public Map generate(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) { |
| 268 | + return Map.of("generation", this.chatModel.call(message)); |
| 269 | + } |
| 270 | +
|
| 271 | + @GetMapping("/ai/generateStream") |
| 272 | + public Flux<ChatResponse> generateStream(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) { |
| 273 | + Prompt prompt = new Prompt(new UserMessage(message)); |
| 274 | + return this.chatModel.stream(prompt); |
| 275 | + } |
| 276 | +} |
| 277 | +---- |
0 commit comments