AI Engineering · Build lab 10 of 14
Spring AI tutorial: chat, streaming, structured output, tools, RAG and memory in one Spring Boot app
Build one Spring Boot 3.5 app with Spring AI 1.1: a ChatClient REST endpoint, streaming over SSE with Flux, structured output into a Java record, a @Tool method, RAG with a vector store and QuestionAnswerAdvisor, chat memory, clear errors, and tests against a fake server.
⏱ 75 minIntermediate💸 Free (local model)9 stepsJava · Spring Boot
Java 21Spring Boot 3.5.15Spring AI 1.1.8Maven wrapperOllamallama3.2:3bnomic-embed-textJUnit 5
Overview video
What you will build
A small assistant API in Spring Boot. One app, five endpoints, each one a piece you already built in Python, now done the Spring way:
| Endpoint | What it does | Spring AI piece | You built it in Python in |
|---|---|---|---|
POST /chat |
answers a question, remembers the conversation | ChatClient, MessageChatMemoryAdvisor |
lab 1 (ask()) and lab 2 (the chat loop that remembers) |
GET /chat/stream |
streams the answer token by token | .stream().content() returns a Flux<String>, sent as Server-Sent Events |
lab 2 (FastAPI + SSE) |
POST /extract |
turns invoice text into a typed Invoice record |
.entity(Invoice.class) |
lab 3 (Pydantic + JSON Schema) |
POST /agent |
answers weather questions by calling your Java method | @Tool and .defaultTools(...) |
lab 4 (the tool loop by hand) |
POST /ask |
answers from a company handbook, not from memory | EmbeddingModel, SimpleVectorStore, QuestionAnswerAdvisor |
lab 5 (embeddings) and lab 6 (RAG) |
Settings live in application.properties (your .env and config.py from lab 1). It talks to the free local model in Ollama through the same OpenAI-compatible API the Python labs used, so switching to a hosted API is a change of properties, not code. Every endpoint is tested with @SpringBootTest against a small fake OpenAI-compatible server written in plain Java, so ./mvnw test needs no model at all.
This lab is all Java. Python labs 1 to 6 are not required, but each step says which one it mirrors, so you can compare what the framework does for you with the code you wrote by hand.
Before you start
- Java and Spring Boot basics: a
@RestController, constructor injection,application.properties. You do not need Spring AI or WebFlux experience; each new piece is explained. - Know what a chat call, a token and an embedding are. Fastest path: Your first LLM call (40 minutes, has a Spring AI version) and Embeddings and search from scratch.
- The idea behind RAG (10 minutes): RAG from scratch, steps 1 to 6.
- About 3 GB of disk for the two models, and about 300 MB for Maven downloads the first time you build.
curlin a terminal. On Windows, run thecurlcommands in Git Bash or WSL: PowerShell quotes JSON differently.
Setup
S1Install JDK 21
Spring Boot 3.5 runs on Java 17 or newer; this lab uses Java 21, the current long-term-support release most teams run. On macOS, Homebrew installs it "keg-only" (not on your PATH), so the two export lines tell this terminal where it is. Add them to ~/.zshrc to keep them for new terminals.
brew install openjdk@21
export JAVA_HOME="$(brew --prefix openjdk@21)/libexec/openjdk.jdk/Contents/Home"
export PATH="$JAVA_HOME/bin:$PATH"
java -versionsudo apt install openjdk-21-jdk
java -versionwinget install Microsoft.OpenJDK.21
java -version openjdk version "21.0.x" ...
S2Install Maven (only to create the wrapper once)
You need Maven one time, to generate the Maven wrapper (./mvnw) in step 1. After that every command uses ./mvnw, which downloads and pins the exact Maven version for this project, the way uv pins Python for a Python project. Teammates then need only a JDK.
brew install maven
mvn -versionsudo apt install maven
mvn -versionwinget install Apache.Maven
mvn -version Apache Maven 3.x.y ... Java version: 21.0.x
S3Install Ollama (runs models on your machine)
Same as lab 1. Download it from ollama.com/download and open it once. It runs a server on port 11434 that speaks the OpenAI chat and embeddings API, which is what Spring AI will call.
ollama --version ollama version is 0.x.y
S4Pull the chat model and the embedding model
llama3.2:3b (about 2 GB) writes the answers and can call tools. nomic-embed-text (about 270 MB) turns text into vectors for the RAG step. If you did labs 1 and 5, you have both already.
ollama pull llama3.2:3b
ollama pull nomic-embed-text pulling manifest ... success pulling manifest ... success
S5Check both models answer
The first command asks the chat model through the same /v1/chat/completions URL Spring AI will use. The second asks for an embedding and prints only the start of the vector.
curl -s http://localhost:11434/v1/chat/completions -H "Content-Type: application/json" -d '{"model": "llama3.2:3b", "messages": [{"role": "user", "content": "Say hello in five words."}]}'
curl -s http://localhost:11434/v1/embeddings -H "Content-Type: application/json" -d '{"model": "nomic-embed-text", "input": "hello"}' | head -c 120 {"id":"chatcmpl-123","object":"chat.completion",...,"choices":[{"index":0,"message":{"role":"assistant","content":"Hello there, how are you?"},"finish_reason":"stop"}],...}
{"object":"list","data":[{"object":"embedding","embedding":[0.0123,-0.0456,... Create the project and the Maven wrapper
A Spring Boot 3.5 project with Spring AI 1.1 and its own pinned Maven, that compiles.
Make a folder called assistant and create the four files below in it (keep the folder layout exactly: Maven finds Java code under src/main/java and settings under src/main/resources).
The pom.xml is the whole build. Three dependencies do all the AI work: the OpenAI starter (a chat model, an embedding model and ChatClient, configured from properties), the vector store advisors (RAG, step 6) and Spring Web (the REST endpoints).
Why the OpenAI starter for a local model? Ollama speaks the OpenAI API, exactly like the Python labs used it through the openai SDK. One starter then works for Ollama, OpenAI and every other OpenAI-compatible server (vLLM, LM Studio, many hosted APIs), and for the fake server in the tests. Spring AI also has a native Ollama starter; step 8 shows when to pick it.
Then run the commands. mvn -N wrapper:wrapper creates mvnw, mvnw.cmd and .mvn/wrapper/maven-wrapper.properties (commit all three). ./mvnw compile downloads the dependencies (a few hundred MB the first time) and compiles.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.5.15</version>
</parent>
<groupId>dev.algorung</groupId>
<artifactId>assistant</artifactId>
<version>0.1.0</version>
<properties>
<java.version>21</java.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>1.1.8</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-advisors-vector-store</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project> - The Spring Boot parent pins the versions of Spring, Jackson, Tomcat, JUnit and the plugins, and turns on the
-parameterscompiler flag (step 5 needs it).line 7 - Spring Boot 3.5.15. Spring AI 1.1.8 is built and tested on exactly this version. (Lab 1 used Spring AI 1.0 on Boot 3.4; the code in this lab works the same on 1.0 except where a note says so.)line 8
- Java 21: you can use records, text blocks,
varand switch expressions.line 14 - The Spring AI **BOM** (bill of materials) sets one version for every Spring AI module, so the dependencies below need no
<version>. 1.1.8 is the newest 1.x release. Spring AI 2.0 also exists, but it needs Spring Boot 4.line 20 - The OpenAI starter:
OpenAiChatModel,OpenAiEmbeddingModel, aChatClient.Builderbean and an in-memoryChatMemorybean, all configured fromspring.ai.openai.*properties.line 34 QuestionAnswerAdvisorandSimpleVectorStorefor RAG. Without it, step 6 does not compile.line 38- JUnit 5, AssertJ and Spring's test support, for step 9.
testscope: not in the app you ship.line 42
package dev.algorung.assistant;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AssistantApplication {
public static void main(String[] args) {
SpringApplication.run(AssistantApplication.class, args);
}
} @SpringBootApplicationturns on auto-configuration and component scanning of this package and everything below it. Every controller in this lab lives indev.algorung.assistant, so it is found automatically.line 6
target/
.idea/
*.iml
.vscode/ target/is Maven's build output, like.venv/and__pycache__/in Python. Never commit it.line 1
# Spring AI end to end
AlgoRung Build lab 10: one Spring Boot app with chat, streaming, structured output, a tool, RAG and chat memory.
ollama pull llama3.2:3b
ollama pull nomic-embed-text
mvn -N wrapper:wrapper -Dmaven=3.9.11 # once, creates ./mvnw
./mvnw spring-boot:run # the app on http://localhost:8080
./mvnw test # tests against a fake server, no model needed
Endpoints: POST /chat, GET /chat/stream, POST /extract, POST /agent, POST /ask. cd assistant
mvn -N wrapper:wrapper -Dmaven=3.9.11
./mvnw compile [INFO] Unpacked only-script type wrapper distribution org.apache.maven.wrapper:maven-wrapper-distribution:zip:only-script:3.3.4 [INFO] Configuring .mvn/wrapper/maven-wrapper.properties to use Maven 3.9.11 ... [INFO] BUILD SUCCESS ... [INFO] Building assistant 0.1.0 ... [INFO] BUILD SUCCESS
./mvnw, and nobody has to install Maven to build the project. It plays the same role as uv plus uv.lock in the Python labs.Stuck on this step?
./mvnw: Permission denied- Run
chmod +x mvnwonce. On Windows usemvnw.cmdinstead of./mvnwin every command. release version 21 not supportedorinvalid target release: 21- Maven is running on an older JDK. Run
java -versionandecho $JAVA_HOME: both must say 21. On macOS, run the twoexportlines from setup step S1 again in this terminal. Could not resolve dependenciesorCould not transfer artifact- Maven cannot reach Maven Central (repo.maven.apache.org). Check your network, proxy or company mirror settings in
~/.m2/settings.xml, then run the command again.
Settings and your first ChatClient endpoint
`POST /chat` answers a question through the local model.
Settings first. application.properties is the Spring version of lab 1's .env plus config.py: where the API is, the key and the model. Spring Boot reads it at startup and builds the chat model from it.
One trap if you come from the Python labs: there the base URL ended in /v1. Spring AI adds /v1/chat/completions and /v1/embeddings itself, so the base URL here is just http://localhost:11434.
Then the endpoint. ChatClient is Spring AI's fluent API for a model call, like the ask() function you wrote in lab 1: build the prompt, .call() it, take the .content(). The two records are the JSON request and reply bodies; Jackson maps them for you.
# Local model through Ollama's OpenAI-compatible API (free). Spring AI adds /v1/... itself.
spring.ai.openai.base-url=http://localhost:11434
spring.ai.openai.api-key=ollama
spring.ai.openai.chat.options.model=llama3.2:3b
spring.ai.openai.chat.options.temperature=0.2
spring.ai.openai.embedding.options.model=nomic-embed-text
# Fail fast while learning: 3 tries instead of the default 10.
spring.ai.retry.max-attempts=3
# A hosted API instead: change these four lines. Each one can also come from an environment
# variable, for example SPRING_AI_OPENAI_API_KEY for spring.ai.openai.api-key.
# spring.ai.openai.base-url=https://api.your-provider.com
# spring.ai.openai.api-key=${LLM_API_KEY}
# spring.ai.openai.chat.options.model=the-model-name
# spring.ai.openai.embedding.options.model=the-embedding-model - Ollama's server. No
/v1at the end: Spring AI adds it. (spring.ai.openai.base-urldefaults tohttps://api.openai.com.)line 2 - Ollama ignores the key, but Spring AI refuses to start without one, like the Python SDK. A real key never goes in this file (line 14).line 3
- The chat model, sent as
"model"in every request. The name must matchollama listexactly.line 4 - Default options for every chat call. Any call can override them.line 5
- The embedding model for RAG in step 6. Without this line Spring AI asks for OpenAI's default embedding model, which Ollama does not have.line 6
- Spring AI retries temporary failures (5xx, timeouts, connection errors) with growing pauses, by default 10 times starting at 2 seconds. That is minutes of waiting when Ollama is simply not running. 3 is plenty while you learn.line 9
${LLM_API_KEY}is a Spring placeholder: the value comes from the environment variableLLM_API_KEY(the name lab 1 used). Keys stay out of git.line 14
package dev.algorung.assistant;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ChatController {
record ChatRequest(String message) {}
record ChatReply(String answer) {}
private final ChatClient chat;
ChatController(ChatClient.Builder builder) {
this.chat = builder
.defaultSystem("You are a concise assistant. Answer in at most three sentences.")
.build();
}
@PostMapping("/chat")
ChatReply chat(@RequestBody ChatRequest request) {
String answer = chat.prompt()
.user(request.message())
.call()
.content();
return new ChatReply(answer);
}
} - A record for the request body:
{"message": "..."}becomesnew ChatRequest("..."). Records are perfect for JSON bodies: immutable, no getters to write.line 10 - One
ChatClientper controller, built once and reused. It is thread-safe.line 13 - Spring AI's auto-configuration provides a
ChatClient.Builder, already wired to the model from the properties. It is a prototype bean: every class that asks for one gets a fresh builder, so the settings below stay in this controller.line 15 defaultSystemis the system message for every call made with this client, like thesystemargument ofask()in lab 1.line 17prompt()starts one request,.user(...)adds the user message.line 23.call()sends the request and waits for the whole answer..content()returns just the text, likeresp.choices[0].message.contentin Python.line 25
# terminal 1: start the app (leave it running; Ctrl+C stops it)
./mvnw spring-boot:run
# terminal 2: ask a question
curl -s localhost:8080/chat -H "Content-Type: application/json" -d '{"message": "What is a hash map?"}' Started AssistantApplication in 1.8 seconds (process running for 2.1)
...
{"answer":"A hash map is a data structure that stores key-value pairs and uses a hash function to find the value for a key in constant time on average."} call() sends: one POST /v1/chat/completions with the system and user messages.Stuck on this step?
Connection refusedin the app log, and curl gets a 500- Ollama is not running. Open the Ollama app (or run
ollama serve) and call again. Step 8 turns this into a clear error message. - curl says
Failed to connect to localhost port 8080 - The app is not running yet, or it failed to start. Look at terminal 1: the last lines say why.
Web server failed to start. Port 8080 was already in use.- Another app uses port 8080. Stop it, or add
server.port=8081toapplication.propertiesand use 8081 in the curl commands. - The first answer takes 20 seconds or more
- Normal: Ollama is loading the model into memory. Later calls are much faster.
Stream the answer with Flux and Server-Sent Events
`GET /chat/stream` sends the answer to the client token by token, as it is generated.
In lab 2 you streamed with stream=True, wrapped the chunks in a generator and sent them from FastAPI as Server-Sent Events (SSE). Spring AI does the same with one method: .stream().content() returns a Flux<String>, a stream of text pieces that arrive over time (Reactor's type; think of it as an async Iterator, or a JavaScript async generator).
Return that Flux from a controller method that produces = text/event-stream, and Spring MVC writes every piece to the client as one SSE event (data:... followed by a blank line) as soon as it arrives. No WebFlux app needed: Spring MVC handles Flux return values.
package dev.algorung.assistant;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
@RestController
public class ChatController {
record ChatRequest(String message) {}
record ChatReply(String answer) {}
private final ChatClient chat;
ChatController(ChatClient.Builder builder) {
this.chat = builder
.defaultSystem("You are a concise assistant. Answer in at most three sentences.")
.build();
}
@PostMapping("/chat")
ChatReply chat(@RequestBody ChatRequest request) {
String answer = chat.prompt()
.user(request.message())
.call()
.content();
return new ChatReply(answer);
}
@GetMapping(path = "/chat/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
Flux<String> stream(@RequestParam String message) {
return chat.prompt()
.user(message)
.stream()
.content();
}
} Fluxcomes from Project Reactor, which Spring AI uses for streaming. It is already on the classpath through the OpenAI starter.line 10TEXT_EVENT_STREAM_VALUEistext/event-stream, the SSE content type. Spring writes each element asdata:<text>plus a blank line, and flushes it right away.line 34- A GET with
?message=..., so you can try it from a browser too.@RequestParam String messagefinds the parameter by the Java name, thanks to the-parametersflag the Boot parent turns on.line 35 .stream()instead of.call(): Spring AI sends"stream": trueand reads the provider's SSE chunks, like the raw stream you watched in lab 2.line 38.content()turns each chunk into its text and skips empty ones. Nothing is sent to the model until someone subscribes to theFlux, here Spring MVC when the request arrives.line 39
# restart the app in terminal 1 (Ctrl+C, then again):
./mvnw spring-boot:run
# terminal 2: -N turns off curl's buffering so you see the tokens arrive
curl -N "localhost:8080/chat/stream?message=Count%20from%201%20to%205" data:1 data:, data: 2 data:, data: 3 data:, data: 4 data:, data: 5
data: line is one chunk as the model produced it, so you see the tokenizer at work: , and 2 are separate tokens, and the space belongs to the next word. A browser reads this with EventSource, exactly like the page you built in lab 2. The %20 in the URL is a space, URL-encoded.Stuck on this step?
- Everything arrives at once at the end
- You left out
-N, so curl buffered the output. A proxy (nginx) in front of the app can also buffer; in production turn buffering off for this path. - The browser shows a download instead of text
- Browsers do not render
text/event-streamas a page. Use curl, or anEventSourcein JavaScript as in lab 2.
Structured output into a Java record
`POST /extract` turns messy invoice text into a typed `Invoice` object.
In lab 3 you described an invoice with Pydantic, generated a JSON Schema from it and validated the reply. In Spring AI the description is a Java record, and .entity(Invoice.class) does the rest: it generates the JSON Schema from the record, adds instructions with that schema to your prompt, calls the model, and maps the JSON reply back into the record with Jackson.
The endpoint returns the record, so Spring turns it into JSON again for the client. You get a typed object in the middle, where your business code works with it.
package dev.algorung.assistant;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
public record Invoice(
String vendor,
@JsonPropertyDescription("the invoice date as YYYY-MM-DD") LocalDate invoiceDate,
@JsonPropertyDescription("ISO 4217 code, like USD or EUR") String currency,
List<LineItem> lineItems,
BigDecimal total) {
public record LineItem(String description, BigDecimal quantity, BigDecimal amount) {}
} - The Java twin of lab 3's Pydantic
Invoice(a smaller version). The field names become the JSON keys in the schema:invoiceDate,lineItems.line 9 LocalDate: Jackson parses"2025-03-03"into a real date (Spring Boot adds Jackson's Java time module).@JsonPropertyDescriptionputs the hint into the schema, likeField(description=...)did.line 11BigDecimalfor money: exact decimals.doublewould turn 0.1 + 0.2 into 0.30000000000000004.line 14- A nested record: the schema gets an array of objects with these three fields.line 16
package dev.algorung.assistant;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ExtractController {
record ExtractRequest(String text) {}
private final ChatClient chat;
ExtractController(ChatClient.Builder builder) {
this.chat = builder
.defaultSystem("You extract invoices. Use only facts from the text. "
+ "Write numbers without currency symbols or thousands separators.")
.build();
}
@PostMapping("/extract")
Invoice extract(@RequestBody ExtractRequest request) {
return chat.prompt()
.user(request.text())
.call()
.entity(Invoice.class);
}
} - The same kind of instructions as lab 3's
SYSTEMprompt. Two Java strings joined with+.line 16 - The key line. Spring AI appends "Your response should be in JSON format... Here is the JSON Schema..." to the user message, then parses the reply into an
Invoice. If the reply is not valid JSON for the record, it throws, and the client gets a 500.line 26
curl -s localhost:8080/extract -H "Content-Type: application/json" -d '{"text": "ACME TOOLS LTD, invoice of 3 March 2025. 2 x Claw hammer at $12.50 = $25.00. 1 x Cordless drill = $899.00. TOTAL $924.00 USD"}' {"vendor":"ACME TOOLS LTD","invoiceDate":"2025-03-03","currency":"USD","lineItems":[{"description":"Claw hammer","quantity":2,"amount":25.00},{"description":"Cordless drill","quantity":1,"amount":899.00}],"total":924.00} @NotNull, @Positive) and retry with the error, exactly the loop you built in lab 3. For Ollama's constrained decoding (the reply is forced into the schema), see lab 3's Java version, which passes the schema as Ollama's format option.Stuck on this step?
- A 500 error and
Cannot deserialize value of type java.time.LocalDatein the log - The model wrote the date in another format, like
3 March 2025. Run again (small models vary), or tryllama3.1:8b. This is the "validate and retry" case from lab 3. Unrecognized tokenorJsonParseExceptionin the log- The model wrapped the JSON in prose. The format instructions usually prevent it; retrying, or a bigger model, fixes the rest.
- Remove the
$signs? My shell turns$12into nothing - The JSON is inside single quotes, so the shell leaves
$alone. If you switched to double quotes, go back to single quotes.
A @Tool method the model can call
`POST /agent` answers weather questions by calling your Java method.
In lab 4 you wrote the whole tool loop: send JSON Schemas for the tools, read the tool call, run the function, send the result back as a tool message, repeat. In Spring AI you annotate a method with @Tool, hand the object to the ChatClient, and call() runs that loop for you.
The weather data is fake on purpose, as in lab 4: you can see whether the answer really came from your method.
package dev.algorung.assistant;
import java.util.Locale;
import java.util.Map;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
public class WeatherTools {
public record Weather(String city, int temperature, String unit, String conditions) {}
private static final Map<String, Weather> WEATHER = Map.of(
"paris", new Weather("Paris", 18, "celsius", "light rain"),
"tokyo", new Weather("Tokyo", 24, "celsius", "sunny"),
"london", new Weather("London", 14, "celsius", "cloudy"));
@Tool(description = "Current weather for a city.")
public Weather getWeather(@ToolParam(description = "City name, like Paris") String city) {
System.out.println("[tool] getWeather(" + city + ")");
Weather w = WEATHER.get(city.strip().toLowerCase(Locale.ROOT));
if (w == null) {
throw new IllegalArgumentException("no weather data for '" + city + "'; known cities: Paris, Tokyo, London");
}
return w;
}
} - The tool's return type. Spring AI turns the record into JSON with Jackson before sending it to the model as the tool result.line 10
@Toolmakes this method a tool. The description is what the model reads to decide when to call it, like the docstring in lab 4.line 17@ToolParamadds a description to the parameter in the generated JSON Schema. The parameter namecitycomes from the compiled code, which is why the-parametersflag matters.line 18- A log line in terminal 1, so you can see the model called your code.line 19
- An error the model can act on. Spring AI catches the exception and, by default, sends its message back to the model as the tool result, so it can fix the city and try again.line 22
package dev.algorung.assistant;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AgentController {
record AgentRequest(String message) {}
record AgentReply(String answer) {}
private final ChatClient chat;
AgentController(ChatClient.Builder builder) {
this.chat = builder
.defaultSystem("You are a helpful assistant. Use the weather tool for any question about the weather. "
+ "Answer in one or two sentences.")
.defaultTools(new WeatherTools())
.build();
}
@PostMapping("/agent")
AgentReply agent(@RequestBody AgentRequest request) {
String answer = chat.prompt()
.user(request.message())
.call()
.content();
return new AgentReply(answer);
}
} - Tell the model when to use the tool. Small models need this push.line 17
- The key line.
defaultToolsreads every@Toolmethod of the object and sends their schemas with each request. When the model replies with a tool call, Spring AI runs the method, adds the result as atoolmessage and calls the model again, until it answers in text.line 19 - One
call()here can be several HTTP requests to the model: one per tool round.line 27
curl -s localhost:8080/agent -H "Content-Type: application/json" -d '{"message": "Do I need an umbrella in Paris today?"}' # terminal 1 (the app log):
[tool] getWeather(Paris)
# terminal 2:
{"answer":"Yes, take an umbrella: it is 18°C with light rain in Paris."} Stuck on this step?
- The answer is made up and terminal 1 shows no
[tool]line - The model answered without the tool. Ask more directly ("What is the weather in Paris?"), or use a model that is better at tools, like
llama3.1:8b(about 5 GB): set it inspring.ai.openai.chat.options.model. - The model sends
arg0instead ofcity - The code was compiled without
-parameters. Keep thespring-boot-starter-parentparent, or add<parameters>true</parameters>to themaven-compiler-pluginconfiguration. registry.ollama.ai/library/... does not support tools- That model has no tool support.
llama3.2:3bdoes; check the model name inapplication.properties.
RAG: a vector store and QuestionAnswerAdvisor
`POST /ask` answers from the company handbook, using retrieval instead of the model's memory.
This is lab 6 in two Spring beans. At startup, RagConfig reads the handbook, splits it into one document per ## section (lab 6 chunked by heading too), embeds every section with the embedding model (lab 5) and keeps the vectors in a SimpleVectorStore, an in-memory store that searches by cosine similarity, like the NumPy store you wrote.
Then an advisor does the RAG. Advisors are Spring AI's middleware: code that runs before and after every model call, like a servlet filter around the request. QuestionAnswerAdvisor embeds the question, takes the 2 closest sections from the store, and rewrites the user message into "question + context + only answer from the context" before the call.
The handbook is the made-up Larkspur company from lab 6, so the model cannot know the answers from training.
## Hotels
Hotels are covered up to 180 euros a night. In London, Paris and New York the limit is 250 euros a night. If a conference hotel costs more, ask your manager before booking.
## Meals
On a work trip, meals are covered up to 60 euros a day. Alcohol is not covered.
## Vacation
Everyone gets 25 vacation days a year, plus public holidays. You can carry up to 5 unused days into the next year; they expire on 31 March.
## Sick leave
There is no fixed number of sick days. Tell your manager before 10:00 on the first day. From the fourth day in a row, send a doctor's note to the People team.
## Home office budget
New joiners get a one-time budget of 1,000 euros for a desk, a chair and a screen. Internet at home is paid with 40 euros a month. - The answer to the question you ask below: 250 euros a night in London.line 2
package dev.algorung.assistant;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
@Configuration
public class RagConfig {
@Bean
VectorStore vectorStore(EmbeddingModel embeddingModel,
@Value("classpath:handbook.md") Resource handbook) throws IOException {
String text = handbook.getContentAsString(StandardCharsets.UTF_8);
List<Document> docs = Arrays.stream(text.split("\n(?=## )"))
.map(String::strip)
.filter(section -> !section.isEmpty())
.map(section -> new Document(section, Map.of("section", section.lines().findFirst().orElse(""))))
.toList();
SimpleVectorStore store = SimpleVectorStore.builder(embeddingModel).build();
store.add(docs);
System.out.println("[rag] indexed " + docs.size() + " handbook sections");
return store;
}
} - A
@Beanmethod: Spring calls it once at startup and gives every class that needs aVectorStorethis object.EmbeddingModelis the Ollama embedding model from the properties.line 22 @Value("classpath:handbook.md")loads the file fromsrc/main/resources, which ends up inside the jar.line 23- Split before every line that starts with
##.(?=## )is a lookahead: it matches the position without eating the heading, so each piece keeps its title.line 25 - A
Documentis text plus metadata, like the chunk dicts in lab 6. The metadata (here the section title) is stored next to the vector and can be used for filtering.line 28 SimpleVectorStorekeeps everything in memory: perfect for learning and tests, gone on restart. Production uses PGVector, Redis, Qdrant and others through the sameVectorStoreinterface (lab 6 did the same swap by hand).line 30addcalls the embedding model for every document, then stores text, metadata and vector. With Ollama off, startup fails right here.line 31
package dev.algorung.assistant;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RagController {
record AskRequest(String question) {}
record AskReply(String answer) {}
private final ChatClient chat;
RagController(ChatClient.Builder builder, VectorStore vectorStore) {
this.chat = builder
.defaultAdvisors(QuestionAnswerAdvisor.builder(vectorStore)
.searchRequest(SearchRequest.builder().topK(2).build())
.build())
.build();
}
@PostMapping("/ask")
AskReply ask(@RequestBody AskRequest request) {
String answer = chat.prompt()
.user(request.question())
.call()
.content();
return new AskReply(answer);
}
} - The advisor lives in the
spring-ai-advisors-vector-storemodule you added topom.xmlin step 1.line 4 defaultAdvisorsruns the advisor on every call of this client.line 20topK(2): the 2 most similar sections become the context, likekin lab 6. The default is 4..similarityThreshold(0.5)would also drop weak matches.line 21
# restart the app in terminal 1; look for the [rag] line
./mvnw spring-boot:run
# terminal 2
curl -s localhost:8080/ask -H "Content-Type: application/json" -d '{"question": "How much can I spend on a hotel in London?"}'
curl -s localhost:8080/ask -H "Content-Type: application/json" -d '{"question": "What is the dress code?"}' [rag] indexed 5 handbook sections
...
{"answer":"In London, hotels are covered up to 250 euros a night."}
{"answer":"I'm sorry, but the context does not say anything about a dress code, so I can't answer that question."} .call().chatResponse() instead of .content() and read the documents from response.getMetadata().get(QuestionAnswerAdvisor.RETRIEVED_DOCUMENTS).Stuck on this step?
- Startup fails with
model "nomic-embed-text" not found - Pull it:
ollama pull nomic-embed-text, then start the app again. - Startup fails with
Connection refused - Ollama is not running. The vector store embeds the handbook at startup, so the app now needs Ollama to start.
- The answer ignores the handbook
- Check terminal 1 says
indexed 5 handbook sections. If it says 1, the split did not work: the headings must start with##at the beginning of a line.
Chat memory with MessageChatMemoryAdvisor
`POST /chat` remembers earlier turns, separately for each conversation.
A model remembers nothing between calls. In lab 2 your chat loop kept a messages list and sent the whole history every turn. MessageChatMemoryAdvisor does exactly that around each call: before the call it adds the stored messages of this conversation to the prompt, after the call it stores the new user message and the answer.
The starter already provides a ChatMemory bean: a MessageWindowChatMemory that keeps the last 20 messages per conversation, in memory. The client sends a conversationId; each id gets its own history.
package dev.algorung.assistant;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
@RestController
public class ChatController {
record ChatRequest(String conversationId, String message) {}
record ChatReply(String answer) {}
private final ChatClient chat;
ChatController(ChatClient.Builder builder, ChatMemory memory) {
this.chat = builder
.defaultSystem("You are a concise assistant. Answer in at most three sentences.")
.defaultAdvisors(MessageChatMemoryAdvisor.builder(memory).build())
.build();
}
@PostMapping("/chat")
ChatReply chat(@RequestBody ChatRequest request) {
String id = request.conversationId() == null ? "default" : request.conversationId();
String answer = chat.prompt()
.user(request.message())
.advisors(a -> a.param(ChatMemory.CONVERSATION_ID, id))
.call()
.content();
return new ChatReply(answer);
}
@GetMapping(path = "/chat/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
Flux<String> stream(@RequestParam String message, @RequestParam(defaultValue = "stream") String conversationId) {
return chat.prompt()
.user(message)
.advisors(a -> a.param(ChatMemory.CONVERSATION_ID, conversationId))
.stream()
.content();
}
} - The request now has a
conversationId. A missing JSON field arrives asnull.line 16 - Ask Spring for the auto-configured
ChatMemory.line 21 - The memory advisor runs on every call of this client, streaming ones too.line 24
- No id: everyone shares one
defaultconversation. Fine for curl, never for real users (see the trap in Troubleshooting).line 30 - Advisor parameters are set per call.
ChatMemory.CONVERSATION_IDtells the memory advisor which history to load and save.line 33 - Streaming calls get their own id parameter,
streamby default, so they do not mix into the/chathistories.line 40
# restart the app in terminal 1, then:
curl -s localhost:8080/chat -H "Content-Type: application/json" -d '{"conversationId": "sam", "message": "Hi, my name is Sam."}'
curl -s localhost:8080/chat -H "Content-Type: application/json" -d '{"conversationId": "sam", "message": "What is my name?"}'
curl -s localhost:8080/chat -H "Content-Type: application/json" -d '{"conversationId": "alex", "message": "What is my name?"}' {"answer":"Nice to meet you, Sam! How can I help you today?"}
{"answer":"Your name is Sam."}
{"answer":"I don't know your name yet. What would you like me to call you?"} spring-ai-starter-model-chat-memory-repository-jdbc); the advisor code stays the same.Stuck on this step?
- The second call does not know the name
- Both calls must send the same
conversationId. Also check you restarted the app: memory lives in the running app, so a restart forgets everything.
Clear errors, and switching to a hosted API
Readable JSON errors when the model server is down or rejects a request, and the same app on a hosted provider without code changes.
Lab 1 caught each SDK exception and printed a clear message. Spring's version is a @RestControllerAdvice: one class whose @ExceptionHandler methods turn exceptions from any controller into a response. Spring AI throws NonTransientAiException for 4xx replies (wrong model name, bad key: retrying will not help) and TransientAiException for 5xx replies after its retries. A refused connection is Spring's ResourceAccessException.
Switching providers is configuration. Every property can come from an environment variable: upper case, dots and dashes become underscores (spring.ai.openai.api-key is SPRING_AI_OPENAI_API_KEY), and the environment wins over the file. The run command below uses that to start the app with a model name that does not exist, to see the error handling work. For a hosted OpenAI-compatible provider, set the base URL, key, chat model and embedding model the same way, or edit the commented lines in application.properties.
The Ollama starter instead? Spring AI also has spring-ai-starter-model-ollama, which talks to Ollama's native API: it can pull missing models for you and has Ollama-only options like format and keep_alive. Swap the dependency and the properties (the two fragments below); the Java code does not change, because it only uses ChatClient, EmbeddingModel and VectorStore. This lab keeps the OpenAI starter so one setup covers Ollama, hosted APIs and the fake test server.
package dev.algorung.assistant;
import java.util.Map;
import org.springframework.ai.retry.NonTransientAiException;
import org.springframework.ai.retry.TransientAiException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.client.ResourceAccessException;
@RestControllerAdvice
public class ApiErrors {
@ExceptionHandler(ResourceAccessException.class)
ResponseEntity<Map<String, String>> unreachable(ResourceAccessException e) {
return error(HttpStatus.SERVICE_UNAVAILABLE, "Cannot reach the model server. Is Ollama running?");
}
@ExceptionHandler(NonTransientAiException.class)
ResponseEntity<Map<String, String>> rejected(NonTransientAiException e) {
return error(HttpStatus.BAD_GATEWAY, "The model server rejected the request: " + e.getMessage());
}
@ExceptionHandler(TransientAiException.class)
ResponseEntity<Map<String, String>> busy(TransientAiException e) {
return error(HttpStatus.SERVICE_UNAVAILABLE, "The model server failed after retries. Try again soon.");
}
private static ResponseEntity<Map<String, String>> error(HttpStatus status, String message) {
return ResponseEntity.status(status).body(Map.of("error", message));
}
} @RestControllerAdviceapplies these handlers to every controller, and writes the return value as JSON.line 13- Connection refused or timed out, after Spring AI's retries: Ollama stopped while the app was running. (If it is off at startup, step 6's indexing already stops the app.)line 16
- A 4xx from the model server. The message includes the status and the server's error body, for example
HTTP 404 - {"error":{"message":"model ... not found"}}.line 21 - 502 Bad Gateway: the server behind us failed, not the client. Keep these messages for your logs and show users something shorter in a real product.line 23
- A 5xx from the model server, still failing after the retries from
spring.ai.retry.max-attempts.line 26
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-ollama</artifactId>
</dependency> - Replaces
spring-ai-starter-model-openai. Keep only one of the two, or Spring AI finds two chat models.line 3
spring.ai.ollama.base-url=http://localhost:11434
spring.ai.ollama.chat.options.model=llama3.2:3b
spring.ai.ollama.chat.options.temperature=0.2
spring.ai.ollama.embedding.options.model=nomic-embed-text
spring.ai.ollama.init.pull-model-strategy=when_missing - The same server; Spring AI then calls
/api/chatand/api/embed(Ollama's own API) instead of/v1/....line 1 - Pull the models at startup if they are missing. Handy on a new machine; the first start then takes minutes.line 5
# terminal 1: start with a wrong model name (the environment variable beats the file)
SPRING_AI_OPENAI_CHAT_OPTIONS_MODEL=no-such-model ./mvnw spring-boot:run
# terminal 2
curl -s localhost:8080/chat -H "Content-Type: application/json" -d '{"message": "hi"}' {"error":"The model server rejected the request: HTTP 404 - {\"error\":{\"message\":\"model \\\"no-such-model\\\" not found, try pulling it first\",\"type\":\"api_error\",\"param\":null,\"code\":null}}"} application.properties in git.Stuck on this step?
- Windows:
SPRING_AI_OPENAI_CHAT_OPTIONS_MODEL=... ./mvnwis not recognised - In PowerShell run
$env:SPRING_AI_OPENAI_CHAT_OPTIONS_MODEL="no-such-model"; .\mvnw.cmd spring-boot:run, thenRemove-Item Env:SPRING_AI_OPENAI_CHAT_OPTIONS_MODELafterwards. - A hosted API answers 401
- The key is wrong or not set. Check
echo $SPRING_AI_OPENAI_API_KEYis not empty in the terminal that starts the app (never paste the key into logs or chats). - A hosted API answers 404 on
/v1/v1/chat/completions - The base URL ends in
/v1. Remove it: Spring AI adds/v1/...itself.
Test every endpoint against a fake OpenAI server
`./mvnw test` starts the whole app against a fake model server and checks all five endpoints, in seconds, with no model.
Tests should not call a real model: slow, different words every time, and in CI there is no Ollama. In Python you used httpx.MockTransport and fake clients. Here you start a fake OpenAI-compatible server inside the test, with the JDK's built-in HttpServer, and point Spring AI at it with one property. Everything else is real: Spring AI builds real requests, parses real responses, runs the tool loop, the RAG advisor and the memory advisor.
The fake answers from simple rules: a streaming request gets four chunks, a request with tools gets a tool call, a request with a tool result gets "The tool says: ...", a request asking for JSON gets an invoice, and anything else gets echo: plus the last message. That echo is the trick for RAG and memory: the answer shows what Spring AI put in the prompt.
Create both files under src/test/java (not src/main): test code is never part of the app.
package dev.algorung.assistant;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
/** A tiny OpenAI-compatible server for tests: fixed, predictable answers, no model. */
public class FakeLlmServer {
private static final ObjectMapper JSON = new ObjectMapper();
private static final List<String> WORDS = List.of("hotel", "meal", "vacation", "sick", "office");
private final HttpServer server;
private final List<JsonNode> requests = new ArrayList<>();
private FakeLlmServer(HttpServer server) {
this.server = server;
}
public static FakeLlmServer start() {
try {
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
FakeLlmServer fake = new FakeLlmServer(server);
server.createContext("/v1/chat/completions", fake::chat);
server.createContext("/v1/embeddings", fake::embeddings);
server.start();
return fake;
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
public String baseUrl() {
return "http://127.0.0.1:" + server.getAddress().getPort();
}
/** The last chat request Spring AI sent, as JSON. */
public synchronized JsonNode lastChatRequest() {
return requests.get(requests.size() - 1);
}
private void chat(HttpExchange ex) throws IOException {
JsonNode body = JSON.readTree(ex.getRequestBody());
synchronized (this) {
requests.add(body);
}
JsonNode messages = body.path("messages");
JsonNode last = messages.get(messages.size() - 1);
String lastText = last.path("content").asText();
if (body.path("stream").asBoolean()) {
ex.getResponseHeaders().set("Content-Type", "text/event-stream");
ex.sendResponseHeaders(200, 0);
try (OutputStream out = ex.getResponseBody()) {
for (String piece : List.of("Hello", " from", " a", " stream")) {
out.write(sse(Map.of("content", piece), null));
}
out.write(sse(Map.of(), "stop"));
out.write("data: [DONE]\n\n".getBytes(StandardCharsets.UTF_8));
}
return;
}
Map<String, Object> message;
String finish = "stop";
if (body.has("tools") && !last.path("role").asText().equals("tool")) {
message = Map.of("role", "assistant", "tool_calls", List.of(Map.of(
"id", "call_1", "type", "function",
"function", Map.of("name", "getWeather", "arguments", "{\"city\":\"Paris\"}"))));
finish = "tool_calls";
} else if (last.path("role").asText().equals("tool")) {
message = Map.of("role", "assistant", "content", "The tool says: " + lastText);
} else if (lastText.contains("Your response should be in JSON format")) {
message = Map.of("role", "assistant", "content", """
{"vendor":"ACME TOOLS LTD","invoiceDate":"2025-03-03","currency":"USD",\
"lineItems":[{"description":"Claw hammer","quantity":2,"amount":25.00}],"total":25.00}""");
} else {
message = Map.of("role", "assistant", "content", "echo: " + lastText);
}
send(ex, Map.of(
"id", "chatcmpl-fake", "object", "chat.completion", "created", 0, "model", "fake",
"choices", List.of(Map.of("index", 0, "message", message, "finish_reason", finish)),
"usage", Map.of("prompt_tokens", 10, "completion_tokens", 5, "total_tokens", 15)));
}
private void embeddings(HttpExchange ex) throws IOException {
JsonNode input = JSON.readTree(ex.getRequestBody()).path("input");
List<String> texts = new ArrayList<>();
if (input.isArray()) {
input.forEach(t -> texts.add(t.asText()));
} else {
texts.add(input.asText());
}
List<Map<String, Object>> data = new ArrayList<>();
for (int i = 0; i < texts.size(); i++) {
data.add(Map.of("object", "embedding", "index", i, "embedding", embed(texts.get(i))));
}
send(ex, Map.of("object", "list", "model", "fake", "data", data,
"usage", Map.of("prompt_tokens", 1, "total_tokens", 1)));
}
/** One number per topic word: how often it appears. Same text, same vector. */
private static float[] embed(String text) {
String lower = text.toLowerCase();
float[] v = new float[WORDS.size() + 1];
for (int i = 0; i < WORDS.size(); i++) {
v[i] = lower.split(WORDS.get(i), -1).length - 1;
}
v[WORDS.size()] = 0.1f;
return v;
}
private static byte[] sse(Map<String, Object> delta, String finish) throws IOException {
Map<String, Object> choice = new HashMap<>(Map.of("index", 0, "delta", delta));
choice.put("finish_reason", finish);
String chunk = JSON.writeValueAsString(Map.of(
"id", "chatcmpl-fake", "object", "chat.completion.chunk", "created", 0, "model", "fake",
"choices", List.of(choice)));
return ("data: " + chunk + "\n\n").getBytes(StandardCharsets.UTF_8);
}
private static void send(HttpExchange ex, Object reply) throws IOException {
byte[] bytes = JSON.writeValueAsBytes(reply);
ex.getResponseHeaders().set("Content-Type", "application/json");
ex.sendResponseHeaders(200, bytes.length);
try (OutputStream out = ex.getResponseBody()) {
out.write(bytes);
}
}
} com.sun.net.httpserver.HttpServerships with every JDK: a small HTTP server, no dependency needed.line 15- The fake "embedding model": one number per topic word. Texts about hotels get similar vectors, so retrieval in the test is predictable.line 20
- Port
0means "any free port". Tests never clash with a running app or Ollama on 11434.line 31 - Every request is kept, so a test can check what Spring AI sent (the memory test does).line 54
- Streaming: SSE chunks in the OpenAI format,
data: {...}and a blank line each, thendata: [DONE]. Same shape you watched with curl in lab 2.line 60 - Length
0means "chunked": the length is unknown up front, as with any stream.line 62 - A request that offers tools gets a tool call for
getWeatherwith{"city":"Paris"}: the reply shape you parsed by hand in lab 4.line 75 - Spring AI ran the tool and sent its result as a
toolmessage. Echo it, so the test can see the tool's data in the answer.line 80 - The format instructions from
.entity()start with this sentence. Reply with valid JSON for theInvoicerecord.line 82 - A text block (Java 15+). The
\at the line end joins the two lines without a newline.line 84 - Everything else: echo the last message. For
/askthat message is the question plus the retrieved handbook sections.line 87 - Counts how often the word appears: splitting
"hotel, hotels"onhotelgives 3 pieces, so 2 matches.line 116 - A small constant in every vector, so no vector is all zeros (cosine similarity divides by the length).line 118
package dev.algorung.assistant;
import static org.assertj.core.api.Assertions.assertThat;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class AssistantApplicationTests {
static final FakeLlmServer FAKE = FakeLlmServer.start();
@DynamicPropertySource
static void pointSpringAiAtTheFake(DynamicPropertyRegistry registry) {
registry.add("spring.ai.openai.base-url", FAKE::baseUrl);
registry.add("spring.ai.retry.max-attempts", () -> "1");
}
@Autowired
TestRestTemplate http;
@Test
void chatReturnsTheAnswer() {
Map<?, ?> reply = http.postForObject("/chat", Map.of("message", "Hello"), Map.class);
assertThat(reply.get("answer")).isEqualTo("echo: Hello");
}
@Test
void streamSendsServerSentEvents() {
String body = http.getForObject("/chat/stream?message=Hi", String.class);
assertThat(body).contains("data:Hello", "data: from", "data: a", "data: stream");
}
@Test
void extractMapsJsonToARecord() {
Invoice invoice = http.postForObject("/extract", Map.of("text", "ACME TOOLS LTD ..."), Invoice.class);
assertThat(invoice.vendor()).isEqualTo("ACME TOOLS LTD");
assertThat(invoice.invoiceDate()).isEqualTo(LocalDate.of(2025, 3, 3));
assertThat(invoice.total()).isEqualByComparingTo(new BigDecimal("25.00"));
}
@Test
void agentCallsTheTool() {
Map<?, ?> reply = http.postForObject("/agent", Map.of("message", "Weather in Paris?"), Map.class);
assertThat((String) reply.get("answer")).contains("light rain");
}
@Test
void askPutsTheRightHandbookSectionInThePrompt() {
Map<?, ?> reply = http.postForObject("/ask", Map.of("question", "How much can I spend on a hotel in London?"), Map.class);
assertThat((String) reply.get("answer")).contains("250 euros a night");
}
@Test
void chatRemembersEarlierTurns() {
http.postForObject("/chat", Map.of("conversationId", "sam", "message", "My name is Sam."), Map.class);
http.postForObject("/chat", Map.of("conversationId", "sam", "message", "What is my name?"), Map.class);
assertThat(FAKE.lastChatRequest().path("messages").toString()).contains("My name is Sam.");
}
} - Starts the whole app on a random port, with all real beans.
TestRestTemplatebelow sends real HTTP requests to it.line 16 - A
staticfield starts the fake before Spring builds the app. It must: the vector store embeds the handbook while the app starts.line 18 - The one line that matters: Spring AI's base URL becomes the fake.
@DynamicPropertySourcesets properties whose values are only known at runtime, like a random port.line 22 - No retries in tests: a mistake fails at once instead of after a long backoff.line 23
- The SSE body as Spring MVC wrote it:
data:Hello,data: from, ...line 38 - Compare
BigDecimalwithisEqualByComparingTo:equalswould say25.0is not25.00.line 46 - Proves the loop ran: the answer can only contain "light rain" if Spring AI executed
getWeatherand sent its result back.line 52 - Proves retrieval: "250 euros a night" is only in the Hotels section, so it reached the prompt through the vector store and the advisor.line 58
- Proves memory: the second request to the model still contains the first message.line 65
./mvnw test [rag] indexed 5 handbook sections ... [tool] getWeather(Paris) ... [INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] BUILD SUCCESS
Stuck on this step?
- Warnings like
Mockito is currently self-attachingorA Java agent has been loaded dynamically - Harmless on Java 21: they come from the test libraries Spring Boot includes, not from your code. The line that matters is
Tests run: 6, Failures: 0. Connection refusedduring the tests- The test talks to Ollama instead of the fake: check the
@DynamicPropertySourcemethod setsspring.ai.openai.base-url, and that the class is insrc/test/java/dev/algorung/assistant. - Only some tests fail, with a 500 from the app
- Read the first
Caused by:in the output. Usually the fake's reply has a typo; compare it with the file above.
Check it works
Two checks. The tests pass without any model. Then, with Ollama running and the app started (./mvnw spring-boot:run in terminal 1), one question goes through RAG and one through the tool.
./mvnw test
curl -s localhost:8080/ask -H "Content-Type: application/json" -d '{"question": "How many vacation days do I get?"}'
curl -s localhost:8080/agent -H "Content-Type: application/json" -d '{"message": "What is the weather in Tokyo?"}' [INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
{"answer":"You get 25 vacation days per year, plus public holidays."}
{"answer":"The current weather in Tokyo is sunny with a temperature of 24 degrees Celsius."} Troubleshooting
Everyone sees the same chat history
The client sent no conversationId, so every request used default. In a real app, take the id from the logged-in user or session (for example userId + ":" + chatId), never from a value anyone can guess.
No qualifying bean of type ChatModel or "two beans of type ChatModel found"
No model starter or two of them are on the classpath. Keep exactly one of spring-ai-starter-model-openai and spring-ai-starter-model-ollama. (With several on purpose, set spring.ai.model.chat=openai to pick one.)
Answers are very slow (more than 30 seconds)
The model runs on your CPU. Use llama3.2:1b (ollama pull llama3.2:1b, then set it in spring.ai.openai.chat.options.model), close heavy apps, and keep questions short. RAG prompts are longer, so /ask is the slowest endpoint.
It worked, then after an idle pause the first call is slow again
Ollama unloads a model after about 5 minutes without use. The next call loads it again. Normal.
java.lang.UnsupportedClassVersionError ... class file version 65.0
The app was compiled for Java 21 but runs on an older Java. java -version must say 21 in the terminal where you run ./mvnw.
What changes in production
- Keep the key out of the code and the repo. Set
SPRING_AI_OPENAI_API_KEYfrom your platform's secret store. Calls go from your server to the provider; the browser only talks to your app. - Put limits on every request. A tool round or a slow provider can hold a request thread for a long time. Set HTTP client timeouts, cap the input size, and rate-limit
/chatper user, because each call costs money on a hosted API. - Replace the in-memory parts.
SimpleVectorStoreand the in-memory chat memory vanish on restart and do not scale past one instance. Use a real vector store (PGVector, Redis, Qdrant: sameVectorStoreinterface) with ingestion as a separate job, not at startup, and a JDBC or Redis chat memory repository. - Observe it. Spring AI reports model calls, token usage and tool calls through Micrometer. Add
spring-boot-starter-actuatorand send the metrics and traces to your monitoring, so you can see cost per endpoint (the tracing lab goes deeper). - Validate model output before you trust it.
.entity()gives you a typed object, not a correct one. Check business rules (totals add up, dates are plausible) as in lab 3, and treat tool arguments as untrusted input.
Interview angle
“How would you add an LLM feature with RAG to an existing Spring Boot service?”
I would add Spring AI with one model starter, so the chat model, embedding model and a ChatClient.Builder come from configuration, and the provider can change by properties. Endpoints use ChatClient: .call() for normal answers, .stream() returning a Flux as Server-Sent Events for chat UIs, and .entity() with a record when I need typed data, plus validation and a retry. For RAG I ingest documents in a separate job: split them, embed them and store them in a VectorStore such as PGVector; at request time a QuestionAnswerAdvisor retrieves the top matches and adds them to the prompt with an instruction to answer only from them. Chat memory is an advisor keyed by a conversation id from the user's session. Tools are @Tool methods with tight descriptions and validated arguments. I test the wiring with @SpringBootTest against a fake OpenAI-compatible server, measure quality with an eval set, and watch token usage and latency through Micrometer.
Clean up
Stop the app with Ctrl+C. Keep the project: later labs build on the same ideas. To free disk space, remove the models and the Maven downloads (they are shared by all your Maven projects, so only do this if you do not use Maven otherwise).
ollama rm llama3.2:3b
ollama rm nomic-embed-text
rm -rf ~/.m2/repository/org/springframework/ai Practice
No model needed: these run in your browser and check your answer.
A message window, like MessageWindowChatMemory
Spring AI's default chat memory keeps a window of the latest messages. Write window(messages, max_messages): messages is a list of (role, text) tuples, oldest first. Return a new list that keeps every "system" message, plus the most recent other messages, so the result has at most max_messages items in total. Keep the original order. (Assume there are fewer system messages than max_messages.)
def window(messages, max_messages):
# keep all system messages, then the newest others, in the original order
return messages
history = [("system", "Be brief."), ("user", "Hi"), ("assistant", "Hello!"), ("user", "My name is Sam."), ("assistant", "Hi Sam!")]
print(window(history, 3))
Hint
Count how many non-system messages you can keep: `max_messages` minus the number of system messages. Then walk the list and keep a message if it is a system message or one of the last that many others.
Similarity search, like SimpleVectorStore
SimpleVectorStore scores every stored vector against the query with cosine similarity, drops scores below a threshold, sorts best first and keeps the top k. Write search(query, store, top_k, threshold): query is a list of floats, store is a dict from document id to vector. Return the list of (id, score) pairs, best first, with scores rounded to 3 decimals.
import math
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
return dot / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)))
def search(query, store, top_k, threshold):
results = []
# your code here
return results
store = {"hotels": [2, 0, 0.1], "meals": [0, 1, 0.1], "vacation": [0, 0, 0.1]}
print(search([1, 0, 0.1], store, 2, 0.0))
Hint
Build a list of `(id, round(cosine(query, vec), 3))`, keep the ones with a score of at least the threshold, sort by score with `reverse=True`, then slice `[:top_k]`.
The full project
Every file from this lab, as it is after the last step.