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

1 / 7

0 of 9 steps done

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.
  • curl in a terminal. On Windows, run the curl commands 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.

Run
brew install openjdk@21
export JAVA_HOME="$(brew --prefix openjdk@21)/libexec/openjdk.jdk/Contents/Home"
export PATH="$JAVA_HOME/bin:$PATH"
java -version
You should see
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.

Run
brew install maven
mvn -version
You should seeyour text will differ: the model writes it
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.

Run
ollama --version
You should see
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.

Run
ollama pull llama3.2:3b
ollama pull nomic-embed-text
You should see
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.

Run
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
You should seeyour text will differ: the model writes it
{"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,...
1

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.

pom.xml
<?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>
  1. The Spring Boot parent pins the versions of Spring, Jackson, Tomcat, JUnit and the plugins, and turns on the -parameters compiler flag (step 5 needs it).line 7
  2. 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
  3. Java 21: you can use records, text blocks, var and switch expressions.line 14
  4. 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
  5. The OpenAI starter: OpenAiChatModel, OpenAiEmbeddingModel, a ChatClient.Builder bean and an in-memory ChatMemory bean, all configured from spring.ai.openai.* properties.line 34
  6. QuestionAnswerAdvisor and SimpleVectorStore for RAG. Without it, step 6 does not compile.line 38
  7. JUnit 5, AssertJ and Spring's test support, for step 9. test scope: not in the app you ship.line 42
src/main/java/dev/algorung/assistant/AssistantApplication.java
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);
    }
}
  1. @SpringBootApplication turns on auto-configuration and component scanning of this package and everything below it. Every controller in this lab lives in dev.algorung.assistant, so it is found automatically.line 6
.gitignore
target/
.idea/
*.iml
.vscode/
  1. target/ is Maven's build output, like .venv/ and __pycache__/ in Python. Never commit it.line 1
README.md
# 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.
Run
cd assistant
mvn -N wrapper:wrapper -Dmaven=3.9.11
./mvnw compile
You should seeyour text will differ: the model writes it
[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
Why this way? The wrapper makes the build reproducible: everyone, and your CI, runs the same Maven version with ./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 mvnw once. On Windows use mvnw.cmd instead of ./mvnw in every command.
release version 21 not supported or invalid target release: 21
Maven is running on an older JDK. Run java -version and echo $JAVA_HOME: both must say 21. On macOS, run the two export lines from setup step S1 again in this terminal.
Could not resolve dependencies or Could 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.
2

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.

src/main/resources/application.properties
# 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
  1. Ollama's server. No /v1 at the end: Spring AI adds it. (spring.ai.openai.base-url defaults to https://api.openai.com.)line 2
  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
  3. The chat model, sent as "model" in every request. The name must match ollama list exactly.line 4
  4. Default options for every chat call. Any call can override them.line 5
  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
  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
  7. ${LLM_API_KEY} is a Spring placeholder: the value comes from the environment variable LLM_API_KEY (the name lab 1 used). Keys stay out of git.line 14
src/main/java/dev/algorung/assistant/ChatController.java
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);
    }
}
  1. A record for the request body: {"message": "..."} becomes new ChatRequest("..."). Records are perfect for JSON bodies: immutable, no getters to write.line 10
  2. One ChatClient per controller, built once and reused. It is thread-safe.line 13
  3. 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
  4. defaultSystem is the system message for every call made with this client, like the system argument of ask() in lab 1.line 17
  5. prompt() starts one request, .user(...) adds the user message.line 23
  6. .call() sends the request and waits for the whole answer. .content() returns just the text, like resp.choices[0].message.content in Python.line 25
Run
# 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?"}'
You should seeyour text will differ: the model writes it
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."}
Why this way? Notice what you did not write: no HTTP client, no JSON parsing, no retry loop. That is what the framework buys you. Because you wrote the raw call in lab 1, you know exactly what call() sends: one POST /v1/chat/completions with the system and user messages.
Stuck on this step?
Connection refused in 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=8081 to application.properties and 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.
3

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.

src/main/java/dev/algorung/assistant/ChatController.java 11 new or changed lines
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();
    }
}
  1. Flux comes from Project Reactor, which Spring AI uses for streaming. It is already on the classpath through the OpenAI starter.line 10
  2. TEXT_EVENT_STREAM_VALUE is text/event-stream, the SSE content type. Spring writes each element as data:<text> plus a blank line, and flushes it right away.line 34
  3. A GET with ?message=..., so you can try it from a browser too. @RequestParam String message finds the parameter by the Java name, thanks to the -parameters flag the Boot parent turns on.line 35
  4. .stream() instead of .call(): Spring AI sends "stream": true and reads the provider's SSE chunks, like the raw stream you watched in lab 2.line 38
  5. .content() turns each chunk into its text and skips empty ones. Nothing is sent to the model until someone subscribes to the Flux, here Spring MVC when the request arrives.line 39
Run
# 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"
You should seeyour text will differ: the model writes it
data:1

data:,

data: 2

data:,

data: 3

data:,

data: 4

data:,

data: 5
Why this way? Each 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-stream as a page. Use curl, or an EventSource in JavaScript as in lab 2.
4

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.

src/main/java/dev/algorung/assistant/Invoice.java
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) {}
}
  1. 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
  2. LocalDate: Jackson parses "2025-03-03" into a real date (Spring Boot adds Jackson's Java time module). @JsonPropertyDescription puts the hint into the schema, like Field(description=...) did.line 11
  3. BigDecimal for money: exact decimals. double would turn 0.1 + 0.2 into 0.30000000000000004.line 14
  4. A nested record: the schema gets an array of objects with these three fields.line 16
src/main/java/dev/algorung/assistant/ExtractController.java
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);
    }
}
  1. The same kind of instructions as lab 3's SYSTEM prompt. Two Java strings joined with +.line 16
  2. 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
Run
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"}'
You should seeyour text will differ: the model writes it
{"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}
Why this way? The schema goes in the prompt here, which works with every model and server. A small model still gets it wrong sometimes, so in real code you validate the record (Bean Validation @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.LocalDate in the log
The model wrote the date in another format, like 3 March 2025. Run again (small models vary), or try llama3.1:8b. This is the "validate and retry" case from lab 3.
Unrecognized token or JsonParseException in 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 $12 into nothing
The JSON is inside single quotes, so the shell leaves $ alone. If you switched to double quotes, go back to single quotes.
5

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.

src/main/java/dev/algorung/assistant/WeatherTools.java
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;
    }
}
  1. 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
  2. @Tool makes 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
  3. @ToolParam adds a description to the parameter in the generated JSON Schema. The parameter name city comes from the compiled code, which is why the -parameters flag matters.line 18
  4. A log line in terminal 1, so you can see the model called your code.line 19
  5. 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
src/main/java/dev/algorung/assistant/AgentController.java
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);
    }
}
  1. Tell the model when to use the tool. Small models need this push.line 17
  2. The key line. defaultTools reads every @Tool method 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 a tool message and calls the model again, until it answers in text.line 19
  3. One call() here can be several HTTP requests to the model: one per tool round.line 27
Run
curl -s localhost:8080/agent -H "Content-Type: application/json" -d '{"message": "Do I need an umbrella in Paris today?"}'
You should seeyour text will differ: the model writes it
# terminal 1 (the app log):
[tool] getWeather(Paris)

# terminal 2:
{"answer":"Yes, take an umbrella: it is 18°C with light rain in Paris."}
Why this way? Lab 4 had a max-steps guard so a confused model could not loop forever. Spring AI's loop has no step limit of its own, so keep tools few, well described and fast, and put a timeout on the whole request in production. Your tool is plain Java: unit test it without any model.
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 in spring.ai.openai.chat.options.model.
The model sends arg0 instead of city
The code was compiled without -parameters. Keep the spring-boot-starter-parent parent, or add <parameters>true</parameters> to the maven-compiler-plugin configuration.
registry.ollama.ai/library/... does not support tools
That model has no tool support. llama3.2:3b does; check the model name in application.properties.
6

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.

src/main/resources/handbook.md
## 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.
  1. The answer to the question you ask below: 250 euros a night in London.line 2
src/main/java/dev/algorung/assistant/RagConfig.java
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;
    }
}
  1. A @Bean method: Spring calls it once at startup and gives every class that needs a VectorStore this object. EmbeddingModel is the Ollama embedding model from the properties.line 22
  2. @Value("classpath:handbook.md") loads the file from src/main/resources, which ends up inside the jar.line 23
  3. 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
  4. A Document is 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
  5. SimpleVectorStore keeps everything in memory: perfect for learning and tests, gone on restart. Production uses PGVector, Redis, Qdrant and others through the same VectorStore interface (lab 6 did the same swap by hand).line 30
  6. add calls the embedding model for every document, then stores text, metadata and vector. With Ollama off, startup fails right here.line 31
src/main/java/dev/algorung/assistant/RagController.java
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);
    }
}
  1. The advisor lives in the spring-ai-advisors-vector-store module you added to pom.xml in step 1.line 4
  2. defaultAdvisors runs the advisor on every call of this client.line 20
  3. topK(2): the 2 most similar sections become the context, like k in lab 6. The default is 4. .similarityThreshold(0.5) would also drop weak matches.line 21
Run
# 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?"}'
You should seeyour text will differ: the model writes it
[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."}
Why this way? The second question is as important as the first: the handbook has no dress code, and the advisor's instructions make the model say so instead of inventing one. That is the behaviour you tested in lab 6. To see what was retrieved, call .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.
7

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.

src/main/java/dev/algorung/assistant/ChatController.java 9 new or changed lines
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();
    }
}
  1. The request now has a conversationId. A missing JSON field arrives as null.line 16
  2. Ask Spring for the auto-configured ChatMemory.line 21
  3. The memory advisor runs on every call of this client, streaming ones too.line 24
  4. No id: everyone shares one default conversation. Fine for curl, never for real users (see the trap in Troubleshooting).line 30
  5. Advisor parameters are set per call. ChatMemory.CONVERSATION_ID tells the memory advisor which history to load and save.line 33
  6. Streaming calls get their own id parameter, stream by default, so they do not mix into the /chat histories.line 40
Run
# 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?"}'
You should seeyour text will differ: the model writes it
{"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?"}
Why this way? The third call proves the histories are separate. Memory costs tokens: every remembered message is sent again on every call, which is why the window keeps only the last 20. Lab 2 showed the same trade-off with your own list. For memory that survives a restart, swap in the JDBC repository starter (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.
8

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.

src/main/java/dev/algorung/assistant/ApiErrors.java
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));
    }
}
  1. @RestControllerAdvice applies these handlers to every controller, and writes the return value as JSON.line 13
  2. 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
  3. 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
  4. 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
  5. A 5xx from the model server, still failing after the retries from spring.ai.retry.max-attempts.line 26
pom.xml (Ollama starter instead, fragment)
<dependency>
  <groupId>org.springframework.ai</groupId>
  <artifactId>spring-ai-starter-model-ollama</artifactId>
</dependency>
  1. Replaces spring-ai-starter-model-openai. Keep only one of the two, or Spring AI finds two chat models.line 3
application.properties (Ollama starter instead, fragment)
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
  1. The same server; Spring AI then calls /api/chat and /api/embed (Ollama's own API) instead of /v1/....line 1
  2. Pull the models at startup if they are missing. Handy on a new machine; the first start then takes minutes.line 5
Run
# 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"}'
You should seeyour text will differ: the model writes it
{"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}}"}
Why this way? Startup still works with the wrong chat model, because only the embedding model is called at startup. Stop the app with Ctrl+C and start it again without the variable before the next step. On a hosted provider, keep the key in an environment variable or a secret manager, never in application.properties in git.
Stuck on this step?
Windows: SPRING_AI_OPENAI_CHAT_OPTIONS_MODEL=... ./mvnw is not recognised
In PowerShell run $env:SPRING_AI_OPENAI_CHAT_OPTIONS_MODEL="no-such-model"; .\mvnw.cmd spring-boot:run, then Remove-Item Env:SPRING_AI_OPENAI_CHAT_OPTIONS_MODEL afterwards.
A hosted API answers 401
The key is wrong or not set. Check echo $SPRING_AI_OPENAI_API_KEY is 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.
9

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.

src/test/java/dev/algorung/assistant/FakeLlmServer.java
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);
        }
    }
}
  1. com.sun.net.httpserver.HttpServer ships with every JDK: a small HTTP server, no dependency needed.line 15
  2. The fake "embedding model": one number per topic word. Texts about hotels get similar vectors, so retrieval in the test is predictable.line 20
  3. Port 0 means "any free port". Tests never clash with a running app or Ollama on 11434.line 31
  4. Every request is kept, so a test can check what Spring AI sent (the memory test does).line 54
  5. Streaming: SSE chunks in the OpenAI format, data: {...} and a blank line each, then data: [DONE]. Same shape you watched with curl in lab 2.line 60
  6. Length 0 means "chunked": the length is unknown up front, as with any stream.line 62
  7. A request that offers tools gets a tool call for getWeather with {"city":"Paris"}: the reply shape you parsed by hand in lab 4.line 75
  8. Spring AI ran the tool and sent its result as a tool message. Echo it, so the test can see the tool's data in the answer.line 80
  9. The format instructions from .entity() start with this sentence. Reply with valid JSON for the Invoice record.line 82
  10. A text block (Java 15+). The \ at the line end joins the two lines without a newline.line 84
  11. Everything else: echo the last message. For /ask that message is the question plus the retrieved handbook sections.line 87
  12. Counts how often the word appears: splitting "hotel, hotels" on hotel gives 3 pieces, so 2 matches.line 116
  13. A small constant in every vector, so no vector is all zeros (cosine similarity divides by the length).line 118
src/test/java/dev/algorung/assistant/AssistantApplicationTests.java
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.");
    }
}
  1. Starts the whole app on a random port, with all real beans. TestRestTemplate below sends real HTTP requests to it.line 16
  2. A static field starts the fake before Spring builds the app. It must: the vector store embeds the handbook while the app starts.line 18
  3. The one line that matters: Spring AI's base URL becomes the fake. @DynamicPropertySource sets properties whose values are only known at runtime, like a random port.line 22
  4. No retries in tests: a mistake fails at once instead of after a long backoff.line 23
  5. The SSE body as Spring MVC wrote it: data:Hello, data: from, ...line 38
  6. Compare BigDecimal with isEqualByComparingTo: equals would say 25.0 is not 25.00.line 46
  7. Proves the loop ran: the answer can only contain "light rain" if Spring AI executed getWeather and sent its result back.line 52
  8. 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
  9. Proves memory: the second request to the model still contains the first message.line 65
Run
./mvnw test
You should see
[rag] indexed 5 handbook sections
...
[tool] getWeather(Paris)
...
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
Why this way? This test checks your wiring (properties, advisors, tools, the record mapping, the SSE endpoint), not the model's quality. Measure quality separately with an evaluation set of real questions, which is the evals lab later in this track. The fake also makes the tests safe to run in CI: no network, no key, no cost.
Stuck on this step?
Warnings like Mockito is currently self-attaching or A 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 refused during the tests
The test talks to Ollama instead of the fake: check the @DynamicPropertySource method sets spring.ai.openai.base-url, and that the class is in src/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.

Test
./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?"}'
You should see
[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_KEY from 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 /chat per user, because each call costs money on a hosted API.
  • Replace the in-memory parts. SimpleVectorStore and the in-memory chat memory vanish on restart and do not scale past one instance. Use a real vector store (PGVector, Redis, Qdrant: same VectorStore interface) 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-actuator and 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).

Run
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.)

Exercise
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.

Exercise
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.

Download Java project (.zip)