Running local Ollama models with Spring Boot and Spring AI
Connect Spring Boot to local Ollama models with Spring AI for text generation, vision image analysis, and JSON-schema structured outputs in Kotlin.
Running LLMs locally with Ollama lets you prototype chat, vision, and structured-output features in Spring Boot without paying per-token API fees or sending private data off your machine. This post walks through setting up Spring AI with Ollama in Kotlin across three working examples: basic chat, multimodal vision, and JSON-schema structured output.
Written against Spring AI
1.0.0-M7. For newer Spring AI 1.0 GA and 2.0.x patterns (includingChatClientand cloud model integrations), see my Spring AI series.
Why pair Spring AI with local Ollama
When building AI features in a Spring Boot backend, you don’t always want every integration test or local experiment hitting a hosted API. Ollama runs open-weight models like Llama 3.2 directly on your laptop or homelab GPU and exposes a local HTTP API on http://localhost:11434.
| Aspect | Local Ollama | Hosted LLM API (Gemini / OpenAI) |
|---|---|---|
| Cost | Free after local hardware | Pay per input/output token |
| Data privacy | Prompts never leave your machine | Sent to external provider |
| Latency & throughput | Bound by local GPU/VRAM | High concurrency, managed scaling |
| Model quality | Good for 3B–11B local tasks | Stronger reasoning and long context |
Local Ollama is great for offline prototyping, privacy-sensitive internal tools, and zero-cost local development. Don’t rely on a single local Ollama instance for high-concurrency production traffic or complex multi-step reasoning unless you have dedicated GPU capacity and proper queueing.
Project setup and prerequisites
Before running the Spring Boot app, install Ollama and pull the two models used in this post:
1
2
ollama pull llama3.2
ollama pull llama3.2-vision
Next, add the Spring AI BOM and the Ollama starter to build.gradle.kts. Spring AI auto-configures an OllamaChatModel bean pointing to http://localhost:11434 by default (you can override it with spring.ai.ollama.base-url if Ollama runs on another host).
1
2
3
4
5
6
7
8
9
10
11
extra["springAiVersion"] = "1.0.0-M7"
dependencies {
implementation("org.springframework.ai:spring-ai-starter-model-ollama")
}
dependencyManagement {
imports {
mavenBom("org.springframework.ai:spring-ai-bom:${property("springAiVersion")}")
}
}
Step 1: Basic text generation endpoint
Inject OllamaChatModel into a REST controller and pass a Prompt with OllamaOptions specifying the target model (OllamaModel.LLAMA3_2).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@RestController
class AiController(
private val ollamaChatModel: OllamaChatModel
) {
@PostMapping("/ollama")
fun ollama(
@RequestBody messageForm: MessageForm,
): ChatResponse {
return ollamaChatModel.call(
Prompt(
listOf(
AssistantMessage(messageForm.assistantMessage),
UserMessage(
messageForm.userMessage,
emptyList()
)
),
OllamaOptions.builder()
.model(OllamaModel.LLAMA3_2)
.build()
),
)
}
data class MessageForm(
val assistantMessage: String,
val userMessage: String,
)
}
In production prompts, use
SystemMessagerather thanAssistantMessagefor role instructions so the model treats them as system-level directives instead of prior assistant turns.
Testing with curl
Send a POST request to the endpoint:
1
2
3
4
5
6
curl -X POST http://localhost:8080/ollama \
-H "Content-Type: application/json" \
-d '{
"assistantMessage": "You are a helpful assistant with expertise in geography?",
"userMessage": "Can you tell me what the capital of France is?"
}'
Spring AI returns the full ChatResponse object, including the generated text, finish reason, model name, and token usage counts:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
{
"result": {
"output": {
"messageType": "ASSISTANT",
"metadata": {
"messageType": "ASSISTANT"
},
"toolCalls": [],
"media": [],
"text": "The capital of France is Paris."
},
"metadata": {
"finishReason": "stop",
"contentFilters": [],
"empty": true
}
},
"metadata": {
"id": "",
"model": "llama3.2",
"rateLimit": {
"requestsLimit": 0,
"requestsRemaining": 0,
"requestsReset": "PT0S",
"tokensRemaining": 0,
"tokensLimit": 0,
"tokensReset": "PT0S"
},
"usage": {
"promptTokens": 51,
"completionTokens": 8,
"totalTokens": 59
},
"promptMetadata": [],
"empty": false
},
"results": [
{
"output": {
"messageType": "ASSISTANT",
"metadata": {
"messageType": "ASSISTANT"
},
"toolCalls": [],
"media": [],
"text": "The capital of France is Paris."
},
"metadata": {
"finishReason": "stop",
"contentFilters": [],
"empty": true
}
}
]
}
Step 2: Multimodal vision with image input
Ollama’s vision models accept image attachments alongside text prompts. In Spring AI, wrap a Resource and MimeType in a Media instance and attach it to UserMessage. I tested this with the landscape image below (11-1600x900.jpg placed in src/main/resources):
Figure 1. Sample landscape photo passed to the Ollama
llama3.2-vision model.
Switch the model option to OllamaModel.LLAMA3_2_VISION_11b and pass the Media list into UserMessage:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
@Service
class AiService2(
private val ollamaChatModel: OllamaChatModel,
) {
fun generate(
assistantMessage: String,
userMessage: String,
medias: List<Media>,
): String {
val response: ChatResponse = ollamaChatModel.call(
Prompt(
listOf(
AssistantMessage(assistantMessage),
UserMessage(
userMessage,
medias
)
),
OllamaOptions.builder()
.model(OllamaModel.LLAMA3_2_VISION_11b)
.build()
),
)
return response.result.output.text!!
}
init {
val response = generate(
assistantMessage = "you are a helpful assistant",
userMessage = "Explain the following image",
medias = listOf(
Media(
MimeType.valueOf("image/jpg"),
ClassPathResource("11-1600x900.jpg"),
),
)
)
println("response: $response")
}
}
Model output
Running the service produced the following description directly from the local 11B vision model:
The image depicts a serene and picturesque landscape, likely situated in a rural or wilderness area. The dominant feature of the scene is a winding stream that flows through the center of the image, its gentle curves creating a sense of movement and life. The stream’s banks are lined with lush greenery, including trees and bushes, which add depth and texture to the image.
In the foreground, a field of tall grasses and wildflowers stretches out towards the viewer, punctuated by a few scattered pink flowers that add a pop of color to the otherwise muted palette. A small tree stands sentinel on the left side of the stream, its branches stretching up towards the sky like nature’s own cathedral.
Beyond the stream, the landscape opens up into a vast expanse of rolling hills and mountains, their peaks shrouded in mist or cloud cover. The overall effect is one of tranquility and peace, as if the very essence of the natural world has been distilled into this single, breathtaking image.
Step 3: Structured output with JSON Schema
Free-form text is hard to parse reliably in backend code. Spring AI’s BeanOutputConverter inspects a target Kotlin data class, generates a JSON Schema, and passes it into Ollama’s .format(outputConverter.jsonSchemaMap) option. Ollama constrains token decoding to match that schema, and outputConverter.convert(...) deserializes the JSON payload straight into a typed Person object.
Annotate each field with @field:JsonProperty(required = true, value = "...") so Jackson and the schema generator mark every property as required:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
@Service
class AiService(
private val ollamaChatModel: OllamaChatModel,
) {
fun generate(
assistantMessage: String,
userMessage: String,
medias: List<Media> = emptyList(),
outputConverter: BeanOutputConverter<Person> = BeanOutputConverter(Person::class.java),
): Person {
val response: ChatResponse = ollamaChatModel.call(
Prompt(
listOf(
AssistantMessage(assistantMessage),
UserMessage(
userMessage,
medias
)
),
OllamaOptions.builder()
.model(OllamaModel.LLAMA3_2)
.format(outputConverter.jsonSchemaMap)
.build()
),
)
return outputConverter.convert(response.result.output.text)
?: throw IllegalArgumentException("Failed to convert response to Person")
}
data class Person(
@field:JsonProperty(required = true, value = "name")
val name: String,
@field:JsonProperty(required = true, value = "age")
val age: Int,
@field:JsonProperty(required = true, value = "height")
val height: Double,
@field:JsonProperty(required = true, value = "weight")
val weight: Double,
@field:JsonProperty(required = true, value = "hobbies")
val hobbies: List<String>,
@field:JsonProperty(required = true, value = "address")
val address: String,
@field:JsonProperty(required = true, value = "phone")
val phone: String,
@field:JsonProperty(required = true, value = "email")
val email: String,
)
init {
val response = generate(
assistantMessage = "you are a helpful assistant",
userMessage = "Can you create Dummy data for me?",
)
println("response: $response")
}
}
Deserialized output
1
response: Person(name=John Doe, age=30, height=72.0, weight=190.5, hobbies=[Reading, Hiking], address=123 Main St, phone=+1-555-1234, email=john.doe@example.com)
Caveats and takeaways
Running Ollama through Spring AI gives you a fast, zero-cost loop for testing chat, vision, and schema-constrained JSON generation locally. Keep a few practical limits in mind before moving past prototypes:
- Avoid calling models inside
initblocks in real services: CallingollamaChatModel.call(...)inside a@Serviceinitblock blocks Spring application startup until the model finishes loading into memory. Use a controller,ApplicationRunner, or test instead. - Account for cold starts and VRAM: Loading
llama3.2-vision(11B) takes noticeable memory and startup time on the first request. Configure HTTP read timeouts accordingly if Ollama loads models on demand. - Prefer
ChatClienton newer Spring AI releases: WhileOllamaChatModel.call(...)works directly, newer Spring AI GA and 2.0.x versions favor the fluentChatClientAPI for chaining advisors, structured outputs, and tool calling.