Spring AI tutorial illustration of a Spring Boot chatbot connected to a local Ollama model

Spring AI Tutorial: Build a Chatbot with Spring Boot and Ollama

I have been writing Spring Boot services at work for years, and for a long time the AI side of things lived in Python or Node land. Lately Spring AI keeps showing up in my feed and in team chats, so I decided to build something small with it. This post is that something: a chatbot backend with Spring Boot, a local model through Ollama, conversation memory and streaming. No API key and no cloud bill.

Everything here targets Spring AI 2.1.0 on Spring Boot 4.1, which is what the official release page lists as the latest stable release as I write this in December 2026. I built and ran the project below, and I checked the API details against the reference docs rather than trusting old blog posts. That matters more than usual with this library, and I will explain why in a moment.

Check Your Spring Boot Version First

This is the thing that trips people up most, so I will say it up front. Spring AI 2.x needs Spring Boot 4 (the docs say 4.0.x and 4.1.x) and the Spring Framework 7 line that comes with it. If your company app is still on Boot 3.x, you cannot just add the 2.x dependency. The Spring team keeps a 1.1.x line for Boot 3.5, and a lot of tutorials online were written for it.

So if you copy a snippet from an older article and it does not compile, or a property is silently ignored, the version is the first suspect. Two examples from the upgrade notes. Configuration keys lost their .options segment, so spring.ai.ollama.chat.options.model from older posts is now spring.ai.ollama.chat.model. And the ChatClient now wants an options builder rather than a pre-built options object.

What You Need Before Writing Code

  • Java 17 or newer. I used 21.
  • Maven or Gradle. I used Maven.
  • Ollama running locally. If you are choosing between local runtimes, my Ollama vs LM Studio comparison should help you pick.
  • A small model pulled on your machine. I went with Llama 3.2, which the Spring AI Ollama docs use in their own examples.
ollama pull llama3.2
ollama list

Ollama listens on http://localhost:11434 by default, and Spring AI expects exactly that unless you change it.

Create the Project

Go to start.spring.io, pick Maven, Java, Spring Boot 4.1.x, and add Spring Web and Ollama. Initializr currently generates 2.0.3 as the Spring AI version, so I changed the property in the generated pom to 2.1.0. I also added the session advisor module, which I use for memory further down.

<properties>
    <java.version>21</java.version>
    <spring-ai.version>2.1.0</spring-ai.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webmvc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-starter-model-ollama</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-session-advisor</artifactId>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-bom</artifactId>
            <version>${spring-ai.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Notice that the web starter is called spring-boot-starter-webmvc on Boot 4. The BOM import means I never put a version on any Spring AI artifact myself, which keeps them aligned.

Configure the Model

Here is my whole application.properties.

spring.application.name=chatbot
spring.ai.ollama.base-url=http://localhost:11434
spring.ai.ollama.chat.model=llama3.2
spring.ai.ollama.chat.temperature=0.4

Set the model name explicitly. If you leave it out, the starter falls back to its own default, which the docs list as mistral, and then you get an error about a model you never pulled. If you would rather not run ollama pull by hand, the docs describe spring.ai.ollama.init.pull-model-strategy with never, when_missing and always. I leave it on the default of never, because a surprise multi gigabyte download on a hotel wifi is not my idea of fun.

Your First ChatClient Call

ChatClient is the main API you will use. Spring Boot auto-configures a ChatClient.Builder for whichever model starter is on the classpath, and you inject that builder. The shortest possible controller looks like this.

@RestController
class QuickController {

    private final ChatClient chatClient;

    QuickController(ChatClient.Builder builder) {
        this.chatClient = builder.build();
    }

    @GetMapping("/ask")
    String ask(@RequestParam String question) {
        return chatClient.prompt()
                .user(question)
                .call()
                .content();
    }
}

Run the app, open /ask?question=What is a Java record in the browser and you get a plain text answer from the local model. The fluent chain reads nicely if you have used WebClient or RestClient, and call().content() simply returns the reply as a String.

Give It a System Prompt and a Proper Config Class

A bare model replies in whatever style it feels like. I want short answers aimed at developers, so I move the builder into a config class and set a default system prompt there. Every request through this client then carries it automatically.

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.session.DefaultSessionService;
import org.springframework.ai.session.InMemorySessionRepository;
import org.springframework.ai.session.SessionService;
import org.springframework.ai.session.advisor.SessionAdvisors;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
class ChatConfig {

    @Bean
    SessionService sessionService() {
        return DefaultSessionService.builder()
                .sessionRepository(InMemorySessionRepository.builder().build())
                .build();
    }

    @Bean
    ChatClient chatClient(ChatModel chatModel, SessionService sessionService) {
        return ChatClient.builder(chatModel)
                .defaultSystem("""
                        You are a helpful assistant for Java developers.
                        Keep answers short and use code only when it helps.
                        """)
                .defaultAdvisors(SessionAdvisors.builder(sessionService).build())
                .build();
    }
}

You will see the session pieces in there. They are the next section, and I will explain why I did not reach for the older chat memory classes.

Make the Chatbot Remember the Conversation

Language models are stateless. If you send two separate requests, the second one has no idea what the first one said. A chatbot that forgets your name after one message is not much of a chatbot, so something has to store the history and put it back into each prompt.

In Spring AI that job is done by advisors, which are interceptors wrapped around every ChatClient call. Most tutorials use MessageChatMemoryAdvisor for memory, and it still works. But the reference docs now mark the ChatMemory API and that advisor as deprecated since 2.1.0, to be removed in 3.0.0, and point to Session Memory instead. I did not want to teach something already on the way out, so I used the session advisors.

The idea is simple. A session is an append-only log of the conversation, identified by an id you choose. I use the in-memory repository here, which loses everything on restart, so it suits demos and tests. For production the docs ship a JDBC repository and a starter for it, spring-ai-starter-model-session-jdbc, which supports PostgreSQL, MySQL, MariaDB, SQL Server and H2.

The controller then passes a session id on each call. The id is mandatory, there is no default, because a shared default would quietly mix the history of different users.

@RestController
class ChatController {

    private final ChatClient chatClient;

    ChatController(ChatClient chatClient) {
        this.chatClient = chatClient;
    }

    record ChatRequest(String sessionId, String message) {}

    record ChatReply(String reply) {}

    @PostMapping("/chat")
    ChatReply chat(@RequestBody ChatRequest request) {
        String answer = chatClient.prompt()
                .user(request.message())
                .advisors(SessionAdvisors.session(request.sessionId()))
                .call()
                .content();
        return new ChatReply(answer);
    }
}

Try it with curl. Use the same session id twice and ask a follow up that only makes sense if the model saw the first message.

curl -X POST localhost:8080/chat \
  -H 'Content-Type: application/json' \
  -d '{"sessionId":"balvinder-1","message":"My name is Balvinder. Remember it."}'

curl -X POST localhost:8080/chat \
  -H 'Content-Type: application/json' \
  -d '{"sessionId":"balvinder-1","message":"What is my name?"}'

In production you should build that session id on the server from the logged in user, never take it from the request body like this demo does. Anyone who can guess an id could read that conversation.

Stream the Answer Token by Token

Waiting five seconds for a full answer feels slow, especially on a laptop CPU. Swapping call() for stream() gives you a Flux of text chunks, and Spring MVC can send that as server sent events.

@GetMapping(value = "/chat/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
Flux<String> stream(@RequestParam String sessionId, @RequestParam String message) {
    return chatClient.prompt()
            .user(message)
            .advisors(SessionAdvisors.session(sessionId))
            .stream()
            .content();
}

On the browser side you can read this with EventSource or fetch. I wrote about the React half of this pattern in my post on building a context-aware React AI chatbot, and the same idea works against this endpoint.

Get Typed Objects Back

Once the basics work, the feature I like most is structured output. Instead of parsing text, you hand ChatClient a Java record and it asks the model for matching JSON and maps it for you.

record BookSummary(String title, String author, List<String> keyPoints) {}

@GetMapping("/summary")
BookSummary summary(@RequestParam String book) {
    return chatClient.prompt()
            .user("Summarise the book " + book)
            .call()
            .entity(BookSummary.class);
}

Small local models sometimes break the format, so I would still wrap this in error handling for anything real. It is still much nicer than regex on free text.

Let the Model Call Your Java Code

Tool calling is where a chatbot starts to feel useful. You annotate ordinary methods with @Tool, describe them in plain English, and the model can decide to call them. Here are two small date helpers.

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;

@Component
class DateTools {

    @Tool(description = "Returns today's date in ISO format")
    String today() {
        return LocalDate.now().toString();
    }

    @Tool(description = "Returns how many days are left until the given date")
    long daysUntil(@ToolParam(description = "Target date in ISO format, e.g. 2027-01-31") String date) {
        return ChronoUnit.DAYS.between(LocalDate.now(), LocalDate.parse(date));
    }
}
@GetMapping("/days-left")
String daysLeft(@RequestParam String question) {
    return chatClient.prompt()
            .user(question)
            .tools(dateTools)
            .call()
            .content();
}

Two things to know. First, pick a model that supports tools, because not every small local model does. Second, in 2.x the tool loop runs through the ChatClient, so calling the lower level ChatModel directly will not execute your tools for you.

Mistakes I Would Watch For

  • Connection refused. Ollama is not running. Start the app or run ollama serve.
  • Model not found. The name in your properties does not match what ollama list shows.
  • Forgetful answers on long chats. The Ollama context window defaults to 2048 tokens in the Spring AI docs (spring.ai.ollama.chat.num-ctx), so long histories get cut. My guide to tokens and context windows explains why that happens.
  • Old tutorial code. Check the version at the top of any article before you paste from it.

Where I Would Go Next

This is only the start. The same ChatClient can sit in front of a vector store for retrieval augmented generation, using QuestionAnswerAdvisor from the vector store advisor module, and the docs list stores such as PgVector, Redis, Qdrant, Chroma and Pinecone. I wrote that path up in my Spring AI RAG tutorial, using PgVector and Ollama. Spring AI also has MCP client and server starters, so you can expose your own tools to other AI apps. If MCP is new to you, my Node.js MCP server walkthrough explains the protocol itself, and I later built a Java version in Build an MCP Server with Spring AI. And there is observability through Micrometer, with gen_ai metrics for token usage, which I plan to try before putting anything near production.

Those pieces now live in their own posts so each one stays readable. If you are still choosing a Java framework, my Spring AI vs LangChain4j comparison should help. If you only want one takeaway from this one, it is this. Check the version, start with ChatClient and a local model, and add memory, streaming and tools one step at a time.

Frequently Asked Questions

Do I need an OpenAI API key to use Spring AI?

No. Spring AI supports many providers, and Ollama is one of them, so you can run a model on your own machine and never create an API key. You swap providers by changing the starter and a few properties, not by rewriting your ChatClient code.

Which Spring Boot version does Spring AI 2.x need?

Spring AI 2.x works with Spring Boot 4.0.x and 4.1.x. It does not load on Boot 3. If you are still on Boot 3.5, the 1.1.x line is the one the Spring team maintains for you, but plan an upgrade to Boot 4 when you can.

Can I run this chatbot fully offline?

Yes, once the model is downloaded. Ollama serves it from your own machine at localhost, and the Spring Boot app talks only to that address. You still need internet for the first ollama pull and for Maven dependencies.

What is the difference between ChatClient and ChatModel?

ChatModel is the low level interface for a single provider. ChatClient is the fluent API on top of it, with system prompts, advisors, streaming, structured output and tool calling. The Spring AI 2.0 documentation treats ChatClient as the main API you work with, so I start there.

Does the chat memory survive an application restart?

Not with the in-memory repository used in this post. For persistence, the session memory module has a JDBC repository that works with databases such as PostgreSQL and MySQL, so conversations stay after a restart and can be shared between instances.

Content Protection by DMCA.com
Spread the love
Scroll to Top
×