AI Engineering · Capstone 3 of 4

Build an internal AI assistant with Spring AI: RAG with sources, tools, per-user memory, streaming and pgvector

Build an HR and IT assistant in Spring Boot 3.5 and Spring AI 1.1: ingest a docs folder into a vector store, answer with sources or refuse, open tickets and check leave with safe @Tool methods, per-user memory behind Spring Security, SSE streaming, metrics, pgvector and Docker.

⏱ 480 minAdvanced💸 Free (local models)9 milestonesJava · Spring Boot

Java 21Spring Boot 3.5.15Spring AI 1.1.8Maven wrapperSpring SecurityActuator + MicrometerOllamallama3.2:3bnomic-embed-textSimpleVectorStorepgvectorDocker ComposeJUnit 5

Overview video

1 / 7

0 of 9 milestones done

What you will build

Larkspur Helpdesk, the internal assistant of a made-up company. Employees sign in and ask it things like "How many vacation days do I get?" (it answers from the HR docs and shows the section it used), "My laptop screen is broken" (it opens an IT ticket for them) or "How many vacation days do I have left?" (it reads their own balance). Ask it "Who won the World Cup?" and it says "I could not find that in the HR and IT docs." without calling the model at all.

Endpoint What it does Milestone The same idea in Python
GET /api/me who is signed in (two demo users) 1 (new: Spring Security)
GET /api/search?q= raw retrieval with scores, to calibrate 2 capstone 1, milestones 2 and 3
POST /api/ask answer from the docs, with sources, or refuse 3 capstone 1, milestone 5
POST /api/chat the assistant: memory per user, tools that act 4, 5 capstone 2: tools, checks in code
POST /api/tickets/from-text free text to a validated ticket 6 lab 3: validate and retry
GET /api/ask/stream?q= the answer as Server-Sent Events 7 capstone 1, milestone 6
/actuator/health, /actuator/metrics health, model calls, token usage 8 capstone 2: tracing and cost
(profile pgvector, Docker) the same app on PostgreSQL, in a container 9 lab 6 (pgvector), lab 14 (Docker)

It runs on the free local models in Ollama through the OpenAI-compatible API, exactly like lab 10, so a hosted provider is a change of properties. Small local models break rules: they skip tools, write a tool call as plain text, ask the user a question instead of acting, or answer from general knowledge when the docs say nothing. This project does not hope they behave. The code checks: a guard refuses before the model is called when retrieval finds nothing, every tool call is logged by the server and only logged actions are shown to the user, a missed tool call gets one nudge, and model output is validated before it becomes a ticket.

How a capstone works. Each milestone gives you the requirements, the exact names the tests use, Done when checks and hints; the reference solution is folded away. Every milestone has a test class, src/test/java/dev/algorung/helpdesk/Milestone<n>Test.java. Copy only that file from the solution when you start the milestone (in milestone 1 also FakeLlmServer.java, the fake model server every test uses), then write your own code until ./mvnw test -Dtest=Milestone<n>Test passes. Keep the earlier test files: ./mvnw test runs them all, so you notice when a change breaks something that worked. The tests start the whole app against the fake, so they need no model and run in seconds.

Before you start

  • Java and Spring Boot: @RestController, constructor injection, @Bean, application.properties, and a first @SpringBootTest. No Spring AI, Spring Security or Reactor experience needed: each new piece is explained where it appears.
  • The Spring AI basics: Spring AI end to end (75 minutes) builds ChatClient, streaming, .entity(), @Tool, QuestionAnswerAdvisor and chat memory one at a time. This capstone assumes you have seen them once.
  • The ideas behind RAG and refusing: RAG from scratch. Behind tools that act safely: Tool calling by hand. The Python capstones (docs assistant, support agent) are not required, but this one maps every piece to them.
  • About 3 GB of disk for the two models, about 400 MB for Maven downloads, and Docker Desktop (or Docker Engine) for milestone 9 only.
  • curl in a terminal. On Windows, run the curl commands in Git Bash or WSL: PowerShell quotes JSON differently.

Setup

S1Install JDK 21

Same as lab 10. On macOS, Homebrew installs Java 21 "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.9" 2025-10-21
OpenJDK Runtime Environment Homebrew (build 21.0.9)
OpenJDK 64-Bit Server VM Homebrew (build 21.0.9, mixed mode, sharing)

S2Install Maven (only to create the wrapper once)

Milestone 1 runs mvn -N wrapper:wrapper once to create ./mvnw, the Maven wrapper. Every later command uses ./mvnw, which downloads and pins one Maven version for this project.

Run
brew install maven
mvn -version
You should see
Apache Maven 3.9.14 (996c630dbc656c76214ce58821dcc58be960875b)
Maven home: /opt/homebrew/Cellar/maven/3.9.14/libexec
Java version: 21.0.9, vendor: Homebrew, runtime: /opt/homebrew/Cellar/openjdk@21/21.0.9/libexec/openjdk.jdk/Contents/Home
...

S3Install Ollama and pull both models

Download Ollama from ollama.com/download and open it once: it serves the OpenAI-compatible API on port 11434. llama3.2:3b (about 2 GB) answers and calls tools; nomic-embed-text (about 270 MB) turns text into vectors. If you did lab 10, you have both.

Run
ollama pull llama3.2:3b
ollama pull nomic-embed-text
You should see
pulling manifest
...
success
pulling manifest
...
success

S4Check both models answer

The same two URLs Spring AI will call: chat completions and embeddings. The second command 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-497","object":"chat.completion","created":1795948747,"model":"llama3.2:3b","system_fingerprint":"fp_ollama","choices":[{"index":0,"message":{"role":"assistant","content":"Hello from a friendly AI assistant!"},"finish_reason":"stop"}],"usage":{"prompt_tokens":31,"completion_tokens":8,"total_tokens":39}}
{"object":"list","data":[{"object":"embedding","embedding":[0.017934207,-0.005861857,-0.17534052,-0.013759711,0.03404504

S5Docker, for milestone 9 only

Milestone 9 runs PostgreSQL with pgvector in Docker Compose and builds the app into an image. Install Docker Desktop (macOS, Windows) or Docker Engine with the Compose plugin (Linux). You can do milestones 1 to 8 without it.

Run
docker --version
docker compose version
You should see
Docker version 28.5.1, build e180ab8
Docker Compose version v2.40.3-desktop.1
1

Project, two users and a secured chat endpoint

A Spring Boot 3.5 app with Spring AI 1.1, the Maven wrapper, basic auth for two users, a public health check and `POST /api/chat`.

Create the project in a folder helpdesk: a pom.xml with the Spring Boot parent 3.5.15, java.version 21, the spring-ai-bom 1.1.8 imported in dependencyManagement, and these dependencies: spring-boot-starter-web, spring-boot-starter-security, spring-boot-starter-actuator, spring-ai-starter-model-openai and spring-boot-starter-test (test scope). Use groupId dev.algorung, artifactId helpdesk, version 0.1.0, and put every class in the package dev.algorung.helpdesk. Then run mvn -N wrapper:wrapper -Dmaven=3.9.11 once; from then on use ./mvnw.

Settings in src/main/resources/application.properties, the same as lab 10: base URL http://localhost:11434 (no /v1: Spring AI adds it), key ollama, chat model llama3.2:3b at temperature 0.2, embedding model nomic-embed-text, spring.ai.retry.max-attempts=3. Add two of your own: helpdesk.users.ana-password=ana-pass and helpdesk.users.ben-password=ben-pass.

Security (SecurityConfig): HTTP basic auth, two in-memory users. ana has the role EMPLOYEE; ben has EMPLOYEE and ADMIN. Passwords come from the two properties and are stored encoded (PasswordEncoderFactories.createDelegatingPasswordEncoder()). Rules: /actuator/health is public, /actuator/** and /api/admin/** need ADMIN, everything else needs a login. No sessions (STATELESS) and CSRF off: this is an API for programs that send credentials on every request, not a browser form with cookies.

Endpoints. GET /api/me returns {"user": "ana", "roles": ["EMPLOYEE"]} (roles without the ROLE_ prefix, sorted). POST /api/chat takes {"message": "..."} and returns {"user": "ana", "answer": "..."} from one ChatClient call with a short system prompt. A missing or blank message, or one longer than 2,000 characters, is a 400 with {"error": "message is required"} (or "...is longer than 2000 characters"); check it before calling the model, because every call costs time. Model server errors become clear JSON errors, as in lab 10's ApiErrors (503 when Ollama is down, 502 when it rejects the request).

The tests. Copy FakeLlmServer.java and Milestone1Test.java from the solution into src/test/java/dev/algorung/helpdesk/. The fake is lab 10's fake OpenAI server, grown for the whole capstone: it already knows the replies every milestone needs, and acts like a small model on purpose for a few phrases (milestone 5 explains them). Each test class starts the app on a random port with the fake as the model and a fresh temporary helpdesk.data-dir.

Done when
  • ./mvnw test -Dtest=Milestone1Test passes (5 tests).
  • curl -s localhost:8080/actuator/health returns {"status":"UP"} with no login, and curl -s -o /dev/null -w "%{http_code}" localhost:8080/api/me prints 401.
  • curl -s -u ana:ana-pass localhost:8080/api/chat -H "Content-Type: application/json" -d '{"message": "Hi!"}' returns {"user":"ana","answer":"..."} from your local model.
Hints
  1. http.authorizeHttpRequests(auth -> auth.requestMatchers(...).permitAll() ... .anyRequest().authenticated()). Rules are checked top to bottom, so the public ones come first.
  2. A controller method can take a java.security.Principal (or an Authentication) parameter: Spring passes in the signed-in user. Use principal.getName(), never a user name from the request body.
  3. Throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "message is required") and add an @ExceptionHandler(ResponseStatusException.class) to your @RestControllerAdvice that returns {"error": e.getReason()} with e.getStatusCode().
  4. In tests, http.withBasicAuth("ana", "ana-pass") returns a TestRestTemplate that sends the credentials on every request.
Show the reference solution for milestone 1

Try it yourself first. This is one good way to do it, not the only one.

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>helpdesk</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.boot</groupId>
      <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.ai</groupId>
      <artifactId>spring-ai-starter-model-openai</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. Spring Boot 3.5.15: the version Spring AI 1.1.8 is built and tested on, as in lab 10.line 8
  2. The Spring AI BOM sets one version for every Spring AI module, so the dependencies below need no version.line 21
  3. Spring Security: with it on the classpath every endpoint needs a login until SecurityConfig says otherwise.line 34
  4. /actuator/health now, metrics in milestone 8. It also brings Micrometer, which Spring AI reports model calls to.line 38
  5. Chat model, embedding model, ChatClient.Builder and an in-memory ChatMemory, all from spring.ai.openai.*. It talks to Ollama, hosted APIs and the fake server alike.line 42
src/main/resources/application.properties
# Larkspur Helpdesk: an internal HR and IT assistant.
spring.application.name=helpdesk

# Local models 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

# Demo users. Real apps sign in through SSO; never commit real passwords.
helpdesk.users.ana-password=ana-pass
helpdesk.users.ben-password=ben-pass
  1. No /v1 at the end: Spring AI adds /v1/chat/completions and /v1/embeddings itself.line 5
  2. Not used until milestone 2, but set it now: without it Spring AI asks for OpenAI's default embedding model, which Ollama does not have.line 9
  3. Spring AI retries 5xx, timeouts and refused connections with growing pauses, by default 10 times. 3 is plenty while you learn; the tests use 1.line 11
  4. Demo passwords as properties so a deployment can override them (milestone 9 does). A real company signs users in through SSO and never keeps passwords here.line 14
src/main/java/dev/algorung/helpdesk/HelpdeskApplication.java
package dev.algorung.helpdesk;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class HelpdeskApplication {
    public static void main(String[] args) {
        SpringApplication.run(HelpdeskApplication.class, args);
    }
}
  1. Scans dev.algorung.helpdesk and below: every class in this capstone lives in that one package.line 6
src/main/java/dev/algorung/helpdesk/SecurityConfig.java
package dev.algorung.helpdesk;

import jakarta.servlet.DispatcherType;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth
                        .dispatcherTypeMatchers(DispatcherType.ASYNC, DispatcherType.ERROR).permitAll()
                        .requestMatchers("/actuator/health", "/actuator/health/**").permitAll()
                        .requestMatchers("/actuator/**", "/api/admin/**").hasRole("ADMIN")
                        .anyRequest().authenticated())
                .httpBasic(Customizer.withDefaults())
                .csrf(csrf -> csrf.disable())
                .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
        return http.build();
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Bean
    UserDetailsService users(PasswordEncoder encoder,
                             @Value("${helpdesk.users.ana-password}") String anaPassword,
                             @Value("${helpdesk.users.ben-password}") String benPassword) {
        return new InMemoryUserDetailsManager(
                User.withUsername("ana").password(encoder.encode(anaPassword)).roles("EMPLOYEE").build(),
                User.withUsername("ben").password(encoder.encode(benPassword)).roles("EMPLOYEE", "ADMIN").build());
    }
}
  1. Spring runs a request through the filters again for an async dispatch (the end of a stream, milestone 7) and for the error page. Those belong to a request that was already checked; without this line an error can turn into a confusing 401.line 24
  2. Public on purpose: load balancers and Docker health checks call it without credentials. Milestone 8 makes sure it shows details only to admins.line 25
  3. hasRole("ADMIN") checks for the authority ROLE_ADMIN; .roles("ADMIN") below adds exactly that.line 26
  4. Basic auth: the client sends Authorization: Basic base64(user:password) on every request. Simple for an API and for curl (-u ana:ana-pass); always behind HTTPS in production.line 28
  5. CSRF protection is for browsers that send cookies automatically. With no sessions and credentials on every request there is nothing to forge, and leaving it on would reject every POST with 403.line 29
  6. No HTTP session: every request proves who it is. That is also what makes "per user" safe later: the user always comes from the credentials of this request.line 30
  7. Encodes with bcrypt and stores {bcrypt}$2a$.... The prefix lets you change the algorithm later without breaking old passwords.line 36
  8. ben is the admin: only he can reindex (milestone 2) and read metrics (milestone 8).line 45
src/main/java/dev/algorung/helpdesk/MeController.java
package dev.algorung.helpdesk;

import java.util.List;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MeController {
    record Me(String user, List<String> roles) {}

    @GetMapping("/api/me")
    Me me(Authentication auth) {
        List<String> roles = auth.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .map(a -> a.replaceFirst("^ROLE_", ""))
                .sorted()
                .toList();
        return new Me(auth.getName(), roles);
    }
}
  1. Spring passes the signed-in user. Nothing in the request body can change it.line 15
  2. Spring stores roles as ROLE_EMPLOYEE; the API shows the plain names.line 18
src/main/java/dev/algorung/helpdesk/Inputs.java
package dev.algorung.helpdesk;

import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;

/** Checks for text that users send: every model call costs time and money, so reject bad input first. */
final class Inputs {
    static final int MAX_CHARS = 2000;

    private Inputs() {
    }

    static String require(String text, String field) {
        if (text == null || text.isBlank()) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, field + " is required");
        }
        if (text.length() > MAX_CHARS) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, field + " is longer than " + MAX_CHARS + " characters");
        }
        return text.strip();
    }
}
  1. A cap on input size is a cap on cost and latency: every character becomes tokens the model has to read.line 8
  2. 400 before any model call. ApiErrors turns it into {"error": "message is required"}.line 15
src/main/java/dev/algorung/helpdesk/ApiErrors.java
package dev.algorung.helpdesk;

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;
import org.springframework.web.server.ResponseStatusException;

@RestControllerAdvice
public class ApiErrors {

    @ExceptionHandler(ResponseStatusException.class)
    ResponseEntity<Map<String, String>> badInput(ResponseStatusException e) {
        return ResponseEntity.status(e.getStatusCode()).body(Map.of("error", String.valueOf(e.getReason())));
    }

    @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. Your own 400s (and later 422s) with a readable error field.line 17
  2. Connection refused or timed out, after the retries: Ollama is not running.line 22
  3. A 4xx from the model server, like a wrong model name. Retrying will not help.line 27
  4. A 5xx that kept failing through every retry.line 27
src/main/java/dev/algorung/helpdesk/ChatController.java
package dev.algorung.helpdesk;

import java.security.Principal;

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 user, String answer) {}

    private final ChatClient chat;

    ChatController(ChatClient.Builder builder) {
        this.chat = builder
                .defaultSystem("You are Larkspur's internal HR and IT assistant. Be concise and friendly.")
                .build();
    }

    @PostMapping("/api/chat")
    ChatReply chat(@RequestBody ChatRequest request, Principal principal) {
        String message = Inputs.require(request.message(), "message");
        String answer = chat.prompt()
                .user(message)
                .call()
                .content();
        return new ChatReply(principal.getName(), answer);
    }
}
  1. The JSON body {"message": "..."}, mapped by Jackson.line 12
  2. The signed-in user. The reply says who answered, which the tests check.line 24
  3. Validate first, then spend money on a model call.line 25
.gitignore
target/
data/
.idea/
*.iml
.vscode/
  1. Milestone 2 writes the vector index and its state here. It is rebuilt from docs/, so it never goes in git.line 2
src/test/java/dev/algorung/helpdesk/FakeLlmServer.java
package dev.algorung.helpdesk;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
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 small OpenAI-compatible server for the tests: chat (with tool calls and streaming) and embeddings.
 * It answers from fixed rules, and acts like a small model on purpose for a few phrases, so the tests
 * can check that your code copes: "keyboard" makes it ask a question instead of acting, "mouse" makes
 * it write the tool call as text, "monitor" makes it claim a ticket it never created, "headset" makes it
 * pack every argument into "category" on the first try (as llama3.2:3b did), and "PAYROLL" makes it pick
 * a category that is not allowed.
 */
public class FakeLlmServer {
    static final String NUDGE_MARKER = "Call the right tool now";
    private static final ObjectMapper JSON = new ObjectMapper();
    private static final List<String> WORDS = List.of("vacation", "year", "request", "sick", "parental", "hotel",
            "meal", "expense", "laptop", "monitor", "password", "vpn", "disconnect", "wi-fi");

    private final HttpServer server;
    private final List<JsonNode> chatRequests = 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 UncheckedIOException(e);
        }
    }

    /** A new empty folder for one test class's index, so every run starts from scratch. */
    public static String freshDataDir() {
        try {
            return Files.createTempDirectory("helpdesk-test-").toString();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    public String baseUrl() {
        return "http://127.0.0.1:" + server.getAddress().getPort();
    }

    public synchronized int chatRequestCount() {
        return chatRequests.size();
    }

    /** The last chat request Spring AI sent, as JSON. */
    public synchronized JsonNode lastChatRequest() {
        return chatRequests.get(chatRequests.size() - 1);
    }

    private void chat(HttpExchange ex) throws IOException {
        JsonNode body = JSON.readTree(ex.getRequestBody());
        synchronized (this) {
            chatRequests.add(body);
        }
        JsonNode messages = body.path("messages");
        JsonNode last = messages.get(messages.size() - 1);
        String lastRole = last.path("role").asText();
        String lastText = last.path("content").asText();

        Map<String, Object> toolCall = null;
        String text;
        if (lastRole.equals("tool")) {
            text = "The tool says: " + lastText;
        } else if (lastText.contains("Your response should be in JSON format")) {
            text = ticketJson(lastText);
        } else if (body.has("tools")) {
            boolean nudged = lastText.contains(NUDGE_MARKER);
            String request = nudged ? previousUserText(messages) : lastText;
            String lower = request.toLowerCase(Locale.ROOT);
            if ((lower.contains("ticket") || lower.contains("broken")) && offers(body, "createItTicket")) {
                String category = request.contains("PAYROLL") ? "PAYROLL" : "HARDWARE";
                String args = JSON.writeValueAsString(Map.of("category", category, "summary", request, "priority", "MEDIUM"));
                if (lower.contains("headset") && !nudged) {
                    args = JSON.writeValueAsString(Map.of("category", args));
                }
                if (lower.contains("monitor")) {
                    text = "Done! I opened ticket IT-4242 for your monitor.";
                } else if (lower.contains("keyboard") && !nudged) {
                    text = "Sure! How urgent is it, and can you describe the problem a bit more?";
                } else if (lower.contains("mouse") && !nudged) {
                    text = "{\"name\": \"createItTicket\", \"arguments\": " + args + "}";
                } else {
                    text = null;
                    toolCall = Map.of("id", "call_1", "type", "function",
                            "function", Map.of("name", "createItTicket", "arguments", args));
                }
            } else if ((lower.contains("days") || lower.contains("balance")) && offers(body, "checkLeaveBalance")) {
                text = null;
                toolCall = Map.of("id", "call_1", "type", "function",
                        "function", Map.of("name", "checkLeaveBalance", "arguments", "{\"leaveType\":\"ANNUAL\"}"));
            } else {
                text = "echo: " + lastText;
            }
        } else {
            text = "echo: " + lastText;
        }

        if (body.path("stream").asBoolean()) {
            stream(ex, text == null ? "" : text);
            return;
        }
        Map<String, Object> message = new HashMap<>(Map.of("role", "assistant"));
        if (toolCall != null) {
            message.put("tool_calls", List.of(toolCall));
        } else {
            message.put("content", text);
        }
        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", toolCall != null ? "tool_calls" : "stop")),
                "usage", Map.of("prompt_tokens", 10, "completion_tokens", 5, "total_tokens", 15)));
    }

    /** Milestone 6: the structured-output reply for a ticket, by keyword. */
    private static String ticketJson(String prompt) {
        String lower = prompt.toLowerCase(Locale.ROOT);
        boolean retry = prompt.contains("Fix these problems");
        if (lower.contains("nonsense")) {
            return "Sorry, I can only help with IT problems.";
        }
        if (lower.contains("printer")) {
            return "{\"category\":\"" + (retry ? "HARDWARE" : "PRINTER")
                    + "\",\"priority\":\"LOW\",\"summary\":\"The printer on floor 3 is jammed\"}";
        }
        if (lower.contains("vpn")) {
            return "{\"category\":\"NETWORK\",\"priority\":\"HIGH\",\"summary\":\"The VPN disconnects every few minutes\"}";
        }
        return "{\"category\":\"SOFTWARE\",\"priority\":\"MEDIUM\",\"summary\":\"A software problem\"}";
    }

    /** The user message before the nudge: the request the nudge is about. */
    private static String previousUserText(JsonNode messages) {
        for (int i = messages.size() - 1; i >= 0; i--) {
            JsonNode m = messages.get(i);
            String content = m.path("content").asText();
            if (m.path("role").asText().equals("user") && !content.contains(NUDGE_MARKER)) {
                return content;
            }
        }
        return "";
    }

    private static boolean offers(JsonNode body, String tool) {
        for (JsonNode t : body.path("tools")) {
            if (t.path("function").path("name").asText().equals(tool)) {
                return true;
            }
        }
        return false;
    }

    /** SSE chunks in the OpenAI format, one per word (the space stays with the next word), then [DONE]. */
    private static void stream(HttpExchange ex, String text) throws IOException {
        ex.getResponseHeaders().set("Content-Type", "text/event-stream");
        ex.sendResponseHeaders(200, 0);
        try (OutputStream out = ex.getResponseBody()) {
            for (String piece : text.split("(?= )")) {
                out.write(sse(Map.of("content", piece), null));
            }
            out.write(sse(Map.of(), "stop"));
            out.write("data: [DONE]\n\n".getBytes(StandardCharsets.UTF_8));
        }
    }

    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; off-topic text scores near 0. */
    static float[] embed(String text) {
        String lower = text.toLowerCase(Locale.ROOT);
        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. Lab 10's fake OpenAI-compatible server, extended for every milestone. Copy it once now; you never need to change it.line 28
  2. Milestone 5: your nudge message must contain this sentence, so the fake can tell a nudge from a normal message.line 29
  3. The fake embedding model counts these words. Texts about the same topic get similar vectors, and a question about football gets a vector near zero: perfect for testing refusals.line 31
  4. Every test class gets a new, empty folder for the index, so a run never depends on the one before.line 55
  5. After Spring AI runs one of your tools, the fake echoes the tool's result, so tests can see what the tool returned.line 88
  6. Milestone 6: .entity() adds instructions that start with this sentence. The fake answers with ticket JSON.line 90
  7. Milestone 5: a request that offers tools gets a tool call when the message is about a ticket or leave days.line 92
  8. Small-model habits on purpose: "monitor" claims a ticket without calling the tool, "keyboard" asks a question back, "mouse" writes the call as text.line 102
  9. Milestone 7: a streaming request gets the same text as SSE chunks, one word each, then data: [DONE].line 124
  10. Same text, same vector, every time. The constant 0.1 at the end keeps any vector from being all zeros.line 209
src/test/java/dev/algorung/helpdesk/Milestone1Test.java
package dev.algorung.helpdesk;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.List;
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;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class Milestone1Test {
    static final FakeLlmServer FAKE = FakeLlmServer.start();
    static final String DATA = FakeLlmServer.freshDataDir();

    @DynamicPropertySource
    static void useTheFake(DynamicPropertyRegistry registry) {
        registry.add("spring.ai.openai.base-url", FAKE::baseUrl);
        registry.add("spring.ai.retry.max-attempts", () -> "1");
        registry.add("helpdesk.data-dir", () -> DATA);
    }

    @Autowired
    TestRestTemplate http;

    TestRestTemplate as(String user) {
        return http.withBasicAuth(user, user + "-pass");
    }

    @Test
    void healthIsPublic() {
        ResponseEntity<Map> health = http.getForEntity("/actuator/health", Map.class);
        assertThat(health.getStatusCode()).isEqualTo(HttpStatus.OK);
        assertThat(health.getBody()).containsEntry("status", "UP");
    }

    @Test
    void theApiNeedsALogin() {
        assertThat(http.getForEntity("/api/me", String.class).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
        assertThat(http.withBasicAuth("ana", "wrong").getForEntity("/api/me", String.class).getStatusCode())
                .isEqualTo(HttpStatus.UNAUTHORIZED);
    }

    @Test
    void meShowsTheSignedInUserAndRoles() {
        assertThat(as("ana").getForObject("/api/me", Map.class))
                .containsEntry("user", "ana").containsEntry("roles", List.of("EMPLOYEE"));
        assertThat(as("ben").getForObject("/api/me", Map.class))
                .containsEntry("user", "ben").containsEntry("roles", List.of("ADMIN", "EMPLOYEE"));
    }

    @Test
    void chatAnswersThroughTheModel() {
        Map<String, Object> reply = as("ana").postForObject("/api/chat", Map.of("message", "Hello"), Map.class);
        assertThat(reply).containsEntry("user", "ana").containsEntry("answer", "echo: Hello");
    }

    @Test
    void aBlankMessageIsABadRequest() {
        ResponseEntity<Map> reply = as("ana").postForEntity("/api/chat", Map.of("message", "   "), Map.class);
        assertThat(reply.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
        assertThat(reply.getBody()).containsEntry("error", "message is required");
    }
}
  1. Starts the whole app on a free port. TestRestTemplate sends real HTTP requests to it, through Spring Security.line 17
  2. A static field: the fake starts before Spring builds the app, which matters from milestone 2 on, when startup embeds the docs.line 19
  3. Not used until milestone 2. Setting it in every test class from the start keeps tests from writing into your project folder later.line 26
  4. No credentials, or wrong ones: 401, and Spring Security never calls your controller.line 45
  5. The fake echoes the last message, so the answer proves the request went through ChatClient to the model server.line 61
Run
mkdir helpdesk && cd helpdesk
# create the files above, then:
mvn -N wrapper:wrapper -Dmaven=3.9.11
./mvnw test -Dtest=Milestone1Test

# terminal 1
./mvnw spring-boot:run
# terminal 2
curl -s localhost:8080/actuator/health
curl -s -u ana:ana-pass localhost:8080/api/me
curl -s -u ana:ana-pass localhost:8080/api/chat -H "Content-Type: application/json" -d '{"message": "Hi! What can you help me with?"}'
You should seeyour text will differ: the model writes it
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
...
Started HelpdeskApplication in 0.862 seconds (process running for 0.943)
{"status":"UP"}
{"user":"ana","roles":["EMPLOYEE"]}
{"user":"ana","answer":"Hello! I'd be happy to assist you. Are you looking for information on company policies, benefits, or perhaps technical support (e.g., password reset, Wi-Fi issues)? Or is there something else on your mind? Let me know how I can help!"}
Why this way? Security comes first because everything after it depends on knowing who is asking: memory, tools and tickets are all per user. The user always comes from Spring Security, never from the request body or from the model.
Stuck on this milestone?
./mvnw: Permission denied
Run chmod +x mvnw once. On Windows use mvnw.cmd.
Every POST returns 403, even with the right password
CSRF is still on. Add .csrf(csrf -> csrf.disable()) to the filter chain.
The log says Using generated security password: ... and your users do not work
Spring Boot made its own default user because it found no UserDetailsService bean. Check SecurityConfig has @Configuration and the users(...) method has @Bean.
Could not resolve placeholder 'helpdesk.users.ana-password'
The property is missing from application.properties, or its name differs by one character from the @Value.
A test does not compile: incompatible types: java.lang.String cannot be converted to capture#1 of ?
Seen on the first build of this project. assertThat(map).containsEntry("user", "ana") does not compile when map is a Map<?, ?>: the compiler cannot prove a String fits ?. Declare it as Map<String, Object> reply = ...postForObject(..., Map.class) (an unchecked conversion, which is fine in a test).
2

Ingest the docs folder into a saved vector store

At startup, every section of `docs/*.md` is embedded into a `SimpleVectorStore` that is saved to a file, and a restart reuses it instead of embedding everything again.

The data. Copy the five files of docs/ from the solution as they are: Larkspur's leave policy, expenses, laptops and equipment, accounts and passwords, network and VPN. 17 sections in all, each under a ## heading. The tests count on these exact files.

pom.xml: add spring-ai-advisors-vector-store (it brings SimpleVectorStore now and QuestionAnswerAdvisor in milestone 3). Properties: helpdesk.docs-dir=docs and helpdesk.data-dir=data.

VectorStoreConfig: a @Bean SimpleVectorStore built from the EmbeddingModel. If <data-dir>/vectors.json exists, load it, so a restart starts with the saved vectors.

Ingestor, a @Component that implements ApplicationRunner (Spring calls run once, after startup, before the app takes requests; tests wait for it too). It needs these exact names, which the tests use:

  • public record Report(String status, int files, int chunks), with status either "indexed" or "unchanged".
  • static List<Document> split(String source, String markdown): one Document per ## section. The text is the whole section, starting with its ## line. Metadata source is the file name and section is the heading text without ## . The id is a UUID made from source + "#" + heading with UUID.nameUUIDFromBytes, so the same section always gets the same id (pgvector, in milestone 9, requires UUID ids). The text before the first ## (the page title) is not a chunk.
  • Report ingest(boolean force) throws IOException: split every .md file in the docs folder, and compute a fingerprint: SHA-256 over the embedding model name and every file's name and bytes. If the fingerprint equals the one saved in <data-dir>/ingest-state.json, force is false and the store is not empty, return unchanged without embedding anything. Otherwise delete the ids saved in the state, add all documents, save the store to vectors.json (only when it is a SimpleVectorStore), and write the new state: {"fingerprint": "...", "ids": [...]}.
  • Report lastReport(): the result of the last ingest.

run calls ingest(false) and logs one line like [ingest] indexed: 17 chunks from 5 files into SimpleVectorStore.

SearchController: GET /api/search?q=...&k=5 returns the raw hits, best first, as [{"source", "section", "score"}] with the score rounded to 3 decimals and no threshold. You will use it to choose the RAG threshold in milestone 3. POST /api/admin/reindex (ADMIN only, from milestone 1's rules) runs ingest(true) and returns the Report.

Done when
  • ./mvnw test -Dtest=Milestone2Test passes (6 tests).
  • The first ./mvnw spring-boot:run logs [ingest] indexed: 17 chunks from 5 files into SimpleVectorStore; stop it and start again, and it logs [ingest] unchanged: ... and starts faster.
  • curl -s -u ana:ana-pass "localhost:8080/api/search?q=My%20VPN%20keeps%20disconnecting" lists network-and-vpn.md / VPN first; curl -s -u ana:ana-pass -X POST localhost:8080/api/admin/reindex -o /dev/null -w "%{http_code}" prints 403, and with -u ben:ben-pass it returns the report.
Hints
  1. Split with a lookahead so each piece keeps its heading: markdown.split("\\n(?=## )"), the same trick as lab 10.
  2. Document.builder().id(id).text(section).metadata(Map.<String, Object>of("source", ..., "section", ...)).build(). The explicit <String, Object> is needed because Map.of with two strings is a Map<String, String>.
  3. SimpleVectorStore.add throws on an empty list, and save(File) does not create missing folders: call Files.createDirectories(dataDir) first.
  4. Why check that the store is not empty when the fingerprint matches? Because the state file and the store can get out of step: vectors.json deleted, or (milestone 9) a fresh database. One cheap search with topK(1) tells you.
Show the reference solution for milestone 2

Try it yourself first. This is one good way to do it, not the only one.

docs/leave-policy.md
# Leave policy

Larkspur's rules for vacation, sick leave and parental leave.

## Vacation days
Everyone gets 25 vacation days a year, plus public holidays. You can carry up to 5 unused vacation days into the next year; carried-over days expire on 31 March. Ask the assistant for your own balance: it reads it from the HR system.

## Requesting vacation
Request vacation in the HR portal. For 3 or more vacation days in a row, request at least 2 weeks ahead. Your manager approves or declines within 3 working days.

## Sick leave
There is no fixed number of sick days. Tell your manager before 10:00 on your first sick day. From the fourth sick day in a row, send a doctor's note to the People team.

## Parental leave
Parents get 16 weeks of fully paid parental leave, to be taken within the first year after the birth or adoption. Tell the People team about your parental leave plans at least 8 weeks before you start.
  1. Each ## heading starts one chunk. The # Leave policy title and the intro line above are not a chunk.line 5
  2. The fact milestone 3's test looks for in the answer.line 6
docs/expenses.md
# Expenses

What Larkspur pays for, and how to claim it.

## Hotels
Hotels are covered up to 180 euros a night. In London, Paris and New York the hotel 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. Keep every meal receipt.

## Home office budget
New joiners get a one-time home office budget of 1,000 euros for a desk, a chair and a monitor. Internet at home is paid with 40 euros a month; claim it as an expense.

## Claiming an expense
Submit every expense in the finance portal within 30 days, with a photo of the receipt. Expenses are paid with your next salary.
  1. The fact milestone 7 streams.line 6
docs/laptops-and-equipment.md
# Laptops and equipment

The hardware Larkspur gives you, and what to do when it breaks.

## Your laptop
Everyone gets a laptop: a MacBook Pro or a ThinkPad, your choice. Laptops are replaced every 3 years. Never install software that IT has not approved on your laptop.

## Broken or lost equipment
If your laptop, monitor or any other equipment is broken, ask the assistant to open an IT ticket with the category HARDWARE. A lost or stolen laptop must be reported within 24 hours, so IT can lock it remotely.

## Monitors and accessories
You can order one monitor, a keyboard, a mouse and a headset from the IT shop. Ask your manager before you order a second monitor.
docs/accounts-and-passwords.md
# Accounts and passwords

How to keep your Larkspur accounts safe.

## Passwords
Your password must be at least 16 characters long. Use the company password manager and never share a password, not even with IT. IT will never ask for your password.

## Two-factor authentication
Every account uses two-factor authentication with the Larkspur Authenticator app. If you get a new phone, move the authenticator before you reset the old phone. A lost phone needs an IT ticket with the category ACCESS.

## Access requests
To get access to a system or a shared drive, open an IT ticket with the category ACCESS and name the system. Your manager approves the access before IT grants it. Password resets also use the category ACCESS.
docs/network-and-vpn.md
# Network and VPN

How to get online in the office and from home.

## VPN
Outside the office, connect to the VPN with the Larkspur Connect app before you open internal tools. If the VPN keeps disconnecting, restart Larkspur Connect first; if that does not help, open an IT ticket with the category NETWORK.

## Office Wi-Fi
In the office, use the Wi-Fi network LARKSPUR-STAFF and sign in with your Larkspur account. Guests use the Wi-Fi network LARKSPUR-GUEST; the guest Wi-Fi password is at the reception desk and changes every Monday.

## Working from abroad
You can work from abroad for up to 20 working days a year. The VPN works in every country except where local law forbids it. Tell your manager and the People team before you travel.
  1. The section /api/search?q=My VPN keeps disconnecting must find first.line 5
pom.xml 1 new line
<?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>helpdesk</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.boot</groupId>
      <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-actuator</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. New: SimpleVectorStore (in its spring-ai-vector-store dependency) and, for milestone 3, QuestionAnswerAdvisor.line 46
src/main/resources/application.properties 3 new or changed lines
# Larkspur Helpdesk: an internal HR and IT assistant.
spring.application.name=helpdesk

# Local models 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

# Demo users. Real apps sign in through SSO; never commit real passwords.
helpdesk.users.ana-password=ana-pass
helpdesk.users.ben-password=ben-pass

# Milestone 2: where the docs are read from, and where the index and its state are kept.
helpdesk.docs-dir=docs
helpdesk.data-dir=data
  1. A folder on disk, not the classpath: you can change the docs without rebuilding the app, and Docker copies the folder into the image (milestone 9).line 18
  2. The index and its state live here. Delete the folder to force a full rebuild.line 19
src/main/java/dev/algorung/helpdesk/VectorStoreConfig.java
package dev.algorung.helpdesk;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class VectorStoreConfig {

    /** In memory while the app runs, saved to data/vectors.json so a restart does not embed everything again. */
    @Bean
    SimpleVectorStore simpleVectorStore(EmbeddingModel embeddingModel,
                                        @Value("${helpdesk.data-dir}") Path dataDir) throws IOException {
        SimpleVectorStore store = SimpleVectorStore.builder(embeddingModel).build();
        Files.createDirectories(dataDir);
        File file = dataDir.resolve("vectors.json").toFile();
        if (file.exists()) {
            store.load(file);
        }
        return store;
    }
}
  1. An in-memory store that compares the query vector with every stored vector by cosine similarity, like the NumPy store of lab 5. Fine for hundreds of chunks; milestone 9 swaps in pgvector.line 21
  2. Loads text, metadata and vectors from the JSON file. No embedding calls: that is the point.line 25
src/main/java/dev/algorung/helpdesk/Ingestor.java
package dev.algorung.helpdesk;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Stream;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/** Reads every Markdown file in the docs folder at startup and keeps the vector store in step with it. */
@Component
public class Ingestor implements ApplicationRunner {
    public record Report(String status, int files, int chunks) {}

    record State(String fingerprint, List<String> ids) {}

    private static final ObjectMapper JSON = new ObjectMapper();

    private final VectorStore store;
    private final Path docsDir;
    private final Path dataDir;
    private final String embeddingModel;
    private volatile Report last = new Report("not run", 0, 0);

    Ingestor(VectorStore store,
             @Value("${helpdesk.docs-dir}") Path docsDir,
             @Value("${helpdesk.data-dir}") Path dataDir,
             @Value("${spring.ai.openai.embedding.options.model}") String embeddingModel) {
        this.store = store;
        this.docsDir = docsDir;
        this.dataDir = dataDir;
        this.embeddingModel = embeddingModel;
    }

    @Override
    public void run(ApplicationArguments args) throws IOException {
        Report report = ingest(false);
        System.out.println("[ingest] " + report.status() + ": " + report.chunks() + " chunks from "
                + report.files() + " files into " + store.getClass().getSimpleName());
    }

    public Report lastReport() {
        return last;
    }

    /** Embeds the docs again only when they (or the embedding model) changed, or when the store is empty. */
    public synchronized Report ingest(boolean force) throws IOException {
        List<Path> files = markdownFiles();
        List<Document> docs = new ArrayList<>();
        for (Path file : files) {
            docs.addAll(split(file.getFileName().toString(), Files.readString(file, StandardCharsets.UTF_8)));
        }
        String fingerprint = fingerprint(files);
        State old = readState();

        if (!force && old != null && old.fingerprint().equals(fingerprint) && !storeIsEmpty()) {
            last = new Report("unchanged", files.size(), docs.size());
            return last;
        }
        if (old != null && !old.ids().isEmpty()) {
            store.delete(old.ids());
        }
        if (!docs.isEmpty()) {
            store.add(docs);
        }
        if (store instanceof SimpleVectorStore simple) {
            simple.save(dataDir.resolve("vectors.json").toFile());
        }
        writeState(new State(fingerprint, docs.stream().map(Document::getId).toList()));
        last = new Report("indexed", files.size(), docs.size());
        return last;
    }

    /** One Document per "## " section. The text before the first section (the page title) is not a chunk. */
    static List<Document> split(String source, String markdown) {
        List<Document> docs = new ArrayList<>();
        for (String part : markdown.split("\\n(?=## )")) {
            String section = part.strip();
            if (!section.startsWith("## ")) {
                continue;
            }
            String heading = section.lines().findFirst().orElseThrow().substring(3).strip();
            String id = UUID.nameUUIDFromBytes((source + "#" + heading).getBytes(StandardCharsets.UTF_8)).toString();
            docs.add(Document.builder()
                    .id(id)
                    .text(section)
                    .metadata(Map.<String, Object>of("source", source, "section", heading))
                    .build());
        }
        return docs;
    }

    private List<Path> markdownFiles() throws IOException {
        if (!Files.isDirectory(docsDir)) {
            throw new IllegalStateException("docs folder not found: " + docsDir.toAbsolutePath());
        }
        try (Stream<Path> paths = Files.list(docsDir)) {
            return paths.filter(p -> p.toString().endsWith(".md")).sorted().toList();
        }
    }

    private String fingerprint(List<Path> files) throws IOException {
        try {
            MessageDigest sha = MessageDigest.getInstance("SHA-256");
            sha.update(embeddingModel.getBytes(StandardCharsets.UTF_8));
            for (Path file : files) {
                sha.update(file.getFileName().toString().getBytes(StandardCharsets.UTF_8));
                sha.update(Files.readAllBytes(file));
            }
            return HexFormat.of().formatHex(sha.digest());
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(e);
        }
    }

    private boolean storeIsEmpty() {
        return store.similaritySearch(SearchRequest.builder().query("leave").topK(1).build()).isEmpty();
    }

    private State readState() throws IOException {
        Path file = dataDir.resolve("ingest-state.json");
        return Files.exists(file) ? JSON.readValue(file.toFile(), State.class) : null;
    }

    private void writeState(State state) throws IOException {
        Files.createDirectories(dataDir);
        JSON.writeValue(dataDir.resolve("ingest-state.json").toFile(), state);
    }
}
  1. Spring calls run once the app is built and before it serves requests. In @SpringBootTest, the tests also start only after it finished.line 29
  2. What is saved in ingest-state.json: the fingerprint and the ids that are in the store, so the next run can delete exactly those.line 32
  3. Spring converts the property string into a Path. A relative path is relative to the folder you start the app from (the project folder with ./mvnw).line 43
  4. Part of the fingerprint: vectors from two different embedding models cannot be compared, so a new model means embedding everything again.line 45
  5. The state file says "done", but is the store really full? This guards against a deleted vectors.json or a new database.line 73
  6. Removes the chunks of the previous run, including sections that no longer exist. Stable ids make this exact.line 78
  7. Embeds every document (one embedding call each with SimpleVectorStore) and stores text, metadata and vector.line 81
  8. Only the file-based store needs saving. pgvector (milestone 9) writes to the database inside add.line 83
  9. Split before every line that starts with ## . The lookahead (?=## ) keeps the heading in the next piece.line 94
  10. A UUID computed from the text: the same section always gets the same id, on every machine. pgvector needs UUID ids.line 100
  11. Any change to any file, or a renamed file, gives a new fingerprint.line 121
  12. Any query works: an empty store returns nothing for every query.line 134
src/main/java/dev/algorung/helpdesk/SearchController.java
package dev.algorung.helpdesk;

import java.io.IOException;
import java.util.List;

import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SearchController {
    public record Hit(String source, String section, double score) {
        static Hit of(Document d) {
            double score = d.getScore() == null ? 0 : Math.round(d.getScore() * 1000) / 1000.0;
            return new Hit(String.valueOf(d.getMetadata().get("source")), String.valueOf(d.getMetadata().get("section")), score);
        }
    }

    private final VectorStore store;
    private final Ingestor ingestor;

    SearchController(VectorStore store, Ingestor ingestor) {
        this.store = store;
        this.ingestor = ingestor;
    }

    /** Raw retrieval with every score and no threshold: the tool you calibrate the RAG threshold with. */
    @GetMapping("/api/search")
    List<Hit> search(@RequestParam String q, @RequestParam(defaultValue = "5") int k) {
        String query = Inputs.require(q, "q");
        return store.similaritySearch(SearchRequest.builder().query(query).topK(Math.min(k, 20)).build())
                .stream().map(Hit::of).toList();
    }

    @PostMapping("/api/admin/reindex")
    Ingestor.Report reindex() throws IOException {
        return ingestor.ingest(true);
    }
}
  1. One search result as JSON. Milestone 3 reuses it for the sources of an answer.line 16
  2. The score is the cosine similarity, 1.0 for the same direction. Three decimals are plenty to compare.line 18
  3. Cap what a client can ask for: a big k is a big response.line 35
  4. force: embed everything again, even if nothing changed. Only ben (ADMIN) gets here.line 41
src/test/java/dev/algorung/helpdesk/Milestone2Test.java
package dev.algorung.helpdesk;

import static org.assertj.core.api.Assertions.assertThat;

import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.SimpleVectorStore;
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;
import org.springframework.http.HttpStatus;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class Milestone2Test {
    static final FakeLlmServer FAKE = FakeLlmServer.start();
    static final String DATA = FakeLlmServer.freshDataDir();

    @DynamicPropertySource
    static void useTheFake(DynamicPropertyRegistry registry) {
        registry.add("spring.ai.openai.base-url", FAKE::baseUrl);
        registry.add("spring.ai.retry.max-attempts", () -> "1");
        registry.add("helpdesk.data-dir", () -> DATA);
    }

    @Autowired
    TestRestTemplate http;

    TestRestTemplate as(String user) {
        return http.withBasicAuth(user, user + "-pass");
    }

    @Autowired
    Ingestor ingestor;

    @Autowired
    EmbeddingModel embeddingModel;

    @Test
    @Order(1)
    void startupIndexedEverySection() {
        Ingestor.Report report = ingestor.lastReport();
        assertThat(report.status()).isEqualTo("indexed");
        assertThat(report.files()).isEqualTo(5);
        assertThat(report.chunks()).isEqualTo(17);
    }

    @Test
    @Order(2)
    void theIndexIsSavedAndLoadsBack() {
        Path vectors = Path.of(DATA, "vectors.json");
        assertThat(vectors).exists();
        assertThat(Path.of(DATA, "ingest-state.json")).exists();
        SimpleVectorStore reloaded = SimpleVectorStore.builder(embeddingModel).build();
        reloaded.load(vectors.toFile());
        assertThat(reloaded.similaritySearch(SearchRequest.builder().query("vpn").topK(50).build())).hasSize(17);
    }

    @Test
    @Order(3)
    void unchangedDocsAreNotEmbeddedAgain() throws IOException {
        assertThat(ingestor.ingest(false).status()).isEqualTo("unchanged");
    }

    @Test
    @Order(4)
    void searchFindsTheRightSectionWithItsScore() {
        List<Map<String, Object>> hits = as("ana").getForObject("/api/search?q=My VPN keeps disconnecting", List.class);
        assertThat(hits.get(0)).containsEntry("source", "network-and-vpn.md").containsEntry("section", "VPN");
        assertThat(((Number) hits.get(0).get("score")).doubleValue()).isGreaterThan(0.7);
    }

    @Test
    @Order(5)
    void onlyAdminsCanReindex() {
        assertThat(as("ana").postForEntity("/api/admin/reindex", null, String.class).getStatusCode())
                .isEqualTo(HttpStatus.FORBIDDEN);
        Map<String, Object> report = as("ben").postForObject("/api/admin/reindex", null, Map.class);
        assertThat(report).containsEntry("status", "indexed").containsEntry("chunks", 17);
    }

    @Test
    void splitMakesOneDocumentPerSectionWithStableIds() {
        String md = "# Title\nIntro text.\n\n## One\nFirst part.\n\n## Two\nSecond part.\n";
        List<Document> docs = Ingestor.split("guide.md", md);
        assertThat(docs).hasSize(2);
        assertThat(docs.get(0).getText()).startsWith("## One").contains("First part.");
        assertThat(docs.get(1).getMetadata()).containsEntry("source", "guide.md").containsEntry("section", "Two");
        assertThat(Ingestor.split("guide.md", md).get(0).getId()).isEqualTo(docs.get(0).getId());
        assertThat(UUID.fromString(docs.get(0).getId())).isNotNull();
    }
}
  1. The first test checks what startup did, before later tests reindex. The order makes that explicit.line 27
  2. 17 sections in the five docs files.line 58
  3. A second store loaded from the file must hold all 17 chunks: proof that the file is complete.line 68
  4. The docs did not change since startup, so nothing is embedded again.line 75
  5. ana is signed in but is not an admin: 403, not 401.line 90
  6. Throws if the id is not a UUID.line 103
Run
./mvnw test -Dtest=Milestone2Test

# terminal 1: start twice, and watch the [ingest] line
./mvnw spring-boot:run

# terminal 2: what does retrieval find, and how sure is it?
curl -s -u ana:ana-pass "localhost:8080/api/search?q=My%20VPN%20keeps%20disconnecting&k=3"
curl -s -u ana:ana-pass "localhost:8080/api/search?q=Who%20won%20the%20World%20Cup&k=3"
You should see
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
...
[ingest] indexed: 17 chunks from 5 files into SimpleVectorStore
(second start) [ingest] unchanged: 17 chunks from 5 files into SimpleVectorStore
[{"source":"network-and-vpn.md","section":"VPN","score":0.653},{"source":"network-and-vpn.md","section":"Office Wi-Fi","score":0.513},{"source":"accounts-and-passwords.md","section":"Two-factor authentication","score":0.49}]
[{"source":"network-and-vpn.md","section":"Office Wi-Fi","score":0.455},{"source":"accounts-and-passwords.md","section":"Two-factor authentication","score":0.454},{"source":"network-and-vpn.md","section":"VPN","score":0.438}]
Why this way? Look at the scores of the second search: a question the docs cannot answer still scores about 0.45 with a real embedding model, and the right section for a real question often scores only 0.65 to 0.8. Real scores are bunched together. That is why you measure before you choose a threshold in the next milestone, instead of guessing.
Stuck on this milestone?
docs folder not found: /.../docs
Start the app from the project folder (where pom.xml and docs/ are), or set helpdesk.docs-dir to an absolute path.
Startup fails with Connection refused while embedding
Ollama is not running, and ingestion needs it at startup. Open the Ollama app and start again.
It logs indexed on every start
The state file is not written or not read back. Check data/ingest-state.json exists after the first start and that fingerprint includes only things that do not change between runs (no timestamps).
IllegalArgumentException: Documents list cannot be empty
No .md file had a ## heading, or the folder is empty. Copy the docs from the solution, and skip add when the list is empty.
Right after the first start, /api/search returns other sections, or fewer than k
Ingestion runs after Tomcat has started, so the app already answers while it is still embedding. Wait for the [ingest] line in the log. On the first start that takes a few seconds for 17 sections; later starts load data/vectors.json and are ready at once.
3

Answers from the docs with sources, or a refusal

`POST /api/ask` answers through `QuestionAnswerAdvisor`, returns the sections it used, and refuses without a model call when nothing relevant was found.

The endpoint. POST /api/ask takes {"question": "..."} (same input rules as /api/chat) and returns {"answer": "...", "refused": false, "sources": [{"source", "section", "score"}]}. Sources are the retrieved sections, best first, each section once.

Retrieval is a QuestionAnswerAdvisor on the ChatClient with a SearchRequest of topK and similarityThreshold from two new properties: helpdesk.rag.top-k=3 and helpdesk.rag.similarity-threshold=0.7. Get the documents it used from the response: call .call().chatClientResponse() instead of .content(); its context() holds them under the key QuestionAnswerAdvisor.RETRIEVED_DOCUMENTS.

The guard. When no section passes the threshold, the advisor still calls the model, with an empty context. A small model then answers from general knowledge, which is exactly the answer you must not give in an HR tool. Write NoContextGuard, a @Component that implements CallAdvisor and StreamAdvisor with an order higher than 0, so it runs after QuestionAnswerAdvisor (order 0) has put the documents in the request context. If that list is empty it does not call the rest of the chain: it returns a ChatClientResponse whose answer starts with "I could not find that in the HR and IT docs.", with a flag in the context that your controller turns into "refused": true.

The threshold. Start the app and use milestone 2's /api/search with three questions the docs answer and three they do not. With nomic-embed-text on a Mac, real scores were bunched: the right section scored 0.65 to 0.8, an off-topic question still 0.44 to 0.49. A threshold of 0.65 lets weak sections through ("Working from abroad" scored 0.666 for a vacation question). 0.7 keeps them out, and it also refuses a few questions the docs do answer: "My VPN keeps disconnecting" scored 0.653 and "Can I expense my home internet?" 0.586. That is the trade-off: a refusal is better than a guess. Pick a value between your two groups and write down the numbers you measured. The test checks that a section below the threshold never reaches the prompt.

Done when
  • ./mvnw test -Dtest=Milestone3Test passes (4 tests).
  • curl -s -u ana:ana-pass localhost:8080/api/ask -H "Content-Type: application/json" -d '{"question": "How many vacation days do I get a year?"}' answers with 25 days and lists leave-policy.md / Vacation days first in sources.
  • The same call with "Who won the football World Cup in 2022?" returns "refused":true, the refusal sentence and "sources":[], and the app log shows no chat request for it.
Hints
  1. QuestionAnswerAdvisor.builder(vectorStore).searchRequest(SearchRequest.builder().topK(topK).similarityThreshold(threshold).build()).build(), then pass it and your guard to .defaultAdvisors(...).
  2. Advisors run in order of getOrder(), lowest first, each wrapping the next. Your guard's adviseCall(request, chain) either returns its own response or chain.nextCall(request).
  3. A fixed answer: new ChatResponse(List.of(new Generation(new AssistantMessage(REFUSAL)))), wrapped with ChatClientResponse.builder().chatResponse(...).context(request.context()).context(REFUSED, true).build().
  4. For streaming (milestone 7) the guard needs adviseStream too: Flux.just(refusal) instead of chain.nextStream(request). Write it now; it is two lines.
Show the reference solution for milestone 3

Try it yourself first. This is one good way to do it, not the only one.

src/main/resources/application.properties 3 new or changed lines
# Larkspur Helpdesk: an internal HR and IT assistant.
spring.application.name=helpdesk

# Local models 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

# Demo users. Real apps sign in through SSO; never commit real passwords.
helpdesk.users.ana-password=ana-pass
helpdesk.users.ben-password=ben-pass

# Milestone 2: where the docs are read from, and where the index and its state are kept.
helpdesk.docs-dir=docs
helpdesk.data-dir=data

# Milestone 3: how many sections to retrieve, and the lowest similarity that counts as a match.
helpdesk.rag.top-k=3
helpdesk.rag.similarity-threshold=0.7
  1. At most 3 sections go into the prompt. More context costs tokens and gives a small model more chances to mix things up.line 22
  2. Sections scoring below this are dropped. Chosen from measured scores (milestone 2's /api/search), not guessed: with nomic-embed-text, 0.65 still let weak sections in.line 23
src/main/java/dev/algorung/helpdesk/NoContextGuard.java
package dev.algorung.helpdesk;

import java.util.List;

import reactor.core.publisher.Flux;

import org.springframework.ai.chat.client.ChatClientRequest;
import org.springframework.ai.chat.client.ChatClientResponse;
import org.springframework.ai.chat.client.advisor.api.CallAdvisor;
import org.springframework.ai.chat.client.advisor.api.CallAdvisorChain;
import org.springframework.ai.chat.client.advisor.api.StreamAdvisor;
import org.springframework.ai.chat.client.advisor.api.StreamAdvisorChain;
import org.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.model.Generation;
import org.springframework.stereotype.Component;

/**
 * Runs after QuestionAnswerAdvisor. When retrieval found nothing above the threshold, it answers with a fixed
 * refusal and never calls the model, so a small model cannot fill the gap from its general knowledge.
 */
@Component
public class NoContextGuard implements CallAdvisor, StreamAdvisor {
    public static final String REFUSAL = "I could not find that in the HR and IT docs. "
            + "Try other words, or ask the People team or IT directly.";
    public static final String REFUSED = "helpdesk_refused";

    @Override
    public ChatClientResponse adviseCall(ChatClientRequest request, CallAdvisorChain chain) {
        return nothingFound(request) ? refusal(request) : chain.nextCall(request);
    }

    @Override
    public Flux<ChatClientResponse> adviseStream(ChatClientRequest request, StreamAdvisorChain chain) {
        return nothingFound(request) ? Flux.just(refusal(request)) : chain.nextStream(request);
    }

    private static boolean nothingFound(ChatClientRequest request) {
        return request.context().get(QuestionAnswerAdvisor.RETRIEVED_DOCUMENTS) instanceof List<?> docs && docs.isEmpty();
    }

    private static ChatClientResponse refusal(ChatClientRequest request) {
        ChatResponse answer = new ChatResponse(List.of(new Generation(new AssistantMessage(REFUSAL))));
        return ChatClientResponse.builder()
                .chatResponse(answer)
                .context(request.context())
                .context(REFUSED, true)
                .build();
    }

    @Override
    public String getName() {
        return "NoContextGuard";
    }

    @Override
    public int getOrder() {
        return 100; // QuestionAnswerAdvisor has order 0: it runs first and puts the documents in the context
    }
}
  1. An advisor is middleware around the model call, like a servlet filter. One class covers both .call() and .stream().line 24
  2. One fixed sentence. Clients and tests can rely on it, and it never contains made-up policy.line 25
  3. The normal path: the next advisor, and finally the model.line 31
  4. QuestionAnswerAdvisor puts the documents it found in the request context under this key before it calls the next advisor.line 40
  5. A response built by hand: one generation with one assistant message. The model is never called.line 44
  6. A flag for the controller, instead of comparing answer strings.line 48
  7. Any number above 0 runs after QuestionAnswerAdvisor (order 0). Lower runs first.line 59
src/main/java/dev/algorung/helpdesk/RagController.java
package dev.algorung.helpdesk;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.ChatClientResponse;
import org.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Value;
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, boolean refused, List<SearchController.Hit> sources) {}

    private final ChatClient chat;

    RagController(ChatClient.Builder builder, VectorStore store, NoContextGuard guard,
                  @Value("${helpdesk.rag.top-k}") int topK,
                  @Value("${helpdesk.rag.similarity-threshold}") double threshold) {
        this.chat = builder
                .defaultSystem("You answer questions from Larkspur employees about HR and IT policies. "
                        + "Answer only from the context you are given, in at most three sentences.")
                .defaultAdvisors(
                        QuestionAnswerAdvisor.builder(store)
                                .searchRequest(SearchRequest.builder().topK(topK).similarityThreshold(threshold).build())
                                .build(),
                        guard)
                .build();
    }

    @PostMapping("/api/ask")
    AskReply ask(@RequestBody AskRequest request) {
        String question = Inputs.require(request.question(), "question");
        ChatClientResponse response = chat.prompt().user(question).call().chatClientResponse();
        return new AskReply(text(response), refused(response), sources(response));
    }

    private static String text(ChatClientResponse r) {
        ChatResponse cr = r.chatResponse();
        if (cr == null || cr.getResult() == null || cr.getResult().getOutput().getText() == null) {
            return "";
        }
        return cr.getResult().getOutput().getText();
    }

    private static boolean refused(ChatClientResponse r) {
        return Boolean.TRUE.equals(r.context().get(NoContextGuard.REFUSED));
    }

    /** The retrieved sections, best first, one entry per section. */
    @SuppressWarnings("unchecked")
    private static List<SearchController.Hit> sources(ChatClientResponse r) {
        Object docs = r.context().get(QuestionAnswerAdvisor.RETRIEVED_DOCUMENTS);
        if (!(docs instanceof List<?> list)) {
            return List.of();
        }
        Map<String, SearchController.Hit> unique = new LinkedHashMap<>();
        for (Document d : (List<Document>) list) {
            SearchController.Hit hit = SearchController.Hit.of(d);
            unique.putIfAbsent(hit.source() + "#" + hit.section(), hit);
        }
        return List.copyOf(unique.values());
    }
}
  1. The answer, whether it was refused, and the sections it came from: everything a UI needs to show "Source: Leave policy, Vacation days".line 22
  2. Both advisors on every call of this client. Their order comes from getOrder(), not from the order here.line 32
  3. The response plus the advisor context, where the retrieved documents are. .content() would give only the text.line 43
  4. One entry per section, in retrieval order (best first).line 69
src/test/java/dev/algorung/helpdesk/Milestone3Test.java
package dev.algorung.helpdesk;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.List;
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;
import org.springframework.http.HttpStatus;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class Milestone3Test {
    static final FakeLlmServer FAKE = FakeLlmServer.start();
    static final String DATA = FakeLlmServer.freshDataDir();

    @DynamicPropertySource
    static void useTheFake(DynamicPropertyRegistry registry) {
        registry.add("spring.ai.openai.base-url", FAKE::baseUrl);
        registry.add("spring.ai.retry.max-attempts", () -> "1");
        registry.add("helpdesk.data-dir", () -> DATA);
    }

    @Autowired
    TestRestTemplate http;

    TestRestTemplate as(String user) {
        return http.withBasicAuth(user, user + "-pass");
    }

    @Test
    void answersFromTheDocsWithSources() {
        Map<?, ?> reply = as("ana").postForObject("/api/ask", Map.of("question", "How many vacation days do I get a year?"), Map.class);
        assertThat(reply.get("refused")).isEqualTo(false);
        assertThat((String) reply.get("answer")).contains("25 vacation days");
        List<Map<String, Object>> sources = (List<Map<String, Object>>) reply.get("sources");
        assertThat(sources).isNotEmpty().hasSizeLessThanOrEqualTo(3);
        assertThat(sources.get(0)).containsEntry("source", "leave-policy.md").containsEntry("section", "Vacation days");
    }

    @Test
    void thePromptHasOnlySectionsAboveTheThreshold() {
        as("ana").postForObject("/api/ask", Map.of("question", "How many vacation days do I get a year?"), Map.class);
        String prompt = FAKE.lastChatRequest().path("messages").toString();
        assertThat(prompt).contains("Context information is below", "## Vacation days");
        assertThat(prompt).doesNotContain("## Requesting vacation");
    }

    @Test
    void offTopicQuestionsAreRefusedWithoutCallingTheModel() {
        int before = FAKE.chatRequestCount();
        Map<?, ?> reply = as("ana").postForObject("/api/ask", Map.of("question", "Who won the football World Cup in 2022?"), Map.class);
        assertThat(reply.get("refused")).isEqualTo(true);
        assertThat((String) reply.get("answer")).startsWith("I could not find that in the HR and IT docs.");
        assertThat((List<?>) reply.get("sources")).isEmpty();
        assertThat(FAKE.chatRequestCount()).isEqualTo(before);
    }

    @Test
    void askNeedsALogin() {
        assertThat(http.postForEntity("/api/ask", Map.of("question", "Hotels?"), String.class).getStatusCode())
                .isEqualTo(HttpStatus.UNAUTHORIZED);
    }
}
  1. The fake echoes the prompt, so the answer contains the retrieved section: proof that retrieval and the advisor worked.line 39
  2. That section shares the word "vacation" but scores below 0.7 with the fake embeddings. If it is in the prompt, the threshold is not applied.line 50
  3. The guard must refuse without calling the model at all.line 60
Run
./mvnw test -Dtest=Milestone3Test

# restart the app in terminal 1, then:
curl -s -u ana:ana-pass localhost:8080/api/ask -H "Content-Type: application/json" -d '{"question": "How many vacation days do I get a year?"}'
curl -s -u ana:ana-pass localhost:8080/api/ask -H "Content-Type: application/json" -d '{"question": "Who won the football World Cup in 2022?"}'
You should seeyour text will differ: the model writes it
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
{"answer":"You get 25 vacation days a year, plus public holidays. This total does not specify an exact number of days for public holidays, but it's included in your overall entitlement. You can carry up to 5 unused vacation days into the next year.","refused":false,"sources":[{"source":"leave-policy.md","section":"Vacation days","score":0.769},{"source":"leave-policy.md","section":"Requesting vacation","score":0.704}]}
{"answer":"I could not find that in the HR and IT docs. Try other words, or ask the People team or IT directly.","refused":true,"sources":[]}
Why this way? The prompt says "answer only from the context", but a small model given no context will still happily answer a football question. A rule the model can ignore is a wish; a check in code is a guarantee. Capstone 1 did the same in Python: refuse before the model call when retrieval is weak.
Stuck on this milestone?
Every question is refused
The threshold is above what your embeddings score. Run three real questions through /api/search, look at the top scores, and set helpdesk.rag.similarity-threshold a little below them (but above your off-topic scores).
Off-topic questions still get an answer
The guard runs before the advisor and finds no documents key at all. Check getOrder() returns more than 0, and that you add the guard to the same client as the advisor.
sources is always empty, but answers look right
You read the documents from chatResponse().getMetadata() before QuestionAnswerAdvisor added them, or from .content(). Read chatClientResponse().context().get(QuestionAnswerAdvisor.RETRIEVED_DOCUMENTS).
4

Chat memory per user

`POST /api/chat` remembers each user's conversation, and a user can never see or clear someone else's.

Add MessageChatMemoryAdvisor with the auto-configured ChatMemory (a window of the last 20 messages per conversation) to the chat client, as in lab 10. The difference is the conversation id: it is the signed-in user's name from Spring Security, never a value from the request. A client that sends "conversationId": "ben" in the body changes nothing.

Add DELETE /api/chat/memory: it clears the memory of the signed-in user only and returns {"user": "...", "memory": "cleared"}.

This mirrors capstone 2, where each customer's thread had its own memory, and the trap from lab 10's troubleshooting: an id anyone can guess or send is a data leak.

Done when
  • ./mvnw test -Dtest=Milestone4Test passes (3 tests).
  • Tell the assistant your name as ana, then ask "What is my name?" as ana (it knows) and as ben (it does not).
  • curl -s -u ana:ana-pass -X DELETE localhost:8080/api/chat/memory returns {"memory":"cleared","user":"ana"} (a Map.of has no fixed key order), and ana's next question starts a fresh conversation.
Hints
  1. .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, principal.getName())) on each call.
  2. ChatMemory has clear(String conversationId).
  3. The tests look at what the fake received: the second request of a conversation must contain the first message, and another user's request must not.
Show the reference solution for milestone 4

Try it yourself first. This is one good way to do it, not the only one.

src/main/java/dev/algorung/helpdesk/ChatController.java 15 new or changed lines
package dev.algorung.helpdesk;

import java.security.Principal;
import java.util.Map;

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.web.bind.annotation.DeleteMapping;
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 user, String answer) {}

    private final ChatClient chat;
    private final ChatMemory memory;

    ChatController(ChatClient.Builder builder, ChatMemory memory) {
        this.memory = memory;
        this.chat = builder
                .defaultSystem("You are Larkspur's internal HR and IT assistant. Be concise and friendly.")
                .defaultAdvisors(MessageChatMemoryAdvisor.builder(memory).build())
                .build();
    }

    @PostMapping("/api/chat")
    ChatReply chat(@RequestBody ChatRequest request, Principal principal) {
        String message = Inputs.require(request.message(), "message");
        String user = principal.getName();
        String answer = chat.prompt()
                .user(message)
                .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, user))
                .call()
                .content();
        return new ChatReply(user, answer);
    }

    @DeleteMapping("/api/chat/memory")
    Map<String, String> forget(Principal principal) {
        memory.clear(principal.getName());
        return Map.of("user", principal.getName(), "memory", "cleared");
    }
}
  1. The starter's ChatMemory bean: MessageWindowChatMemory, 20 messages per conversation, kept in memory.line 20
  2. Before each call it adds this conversation's earlier messages to the prompt; after the call it saves the new user message and the answer.line 7
  3. The conversation id is the user. One conversation per user is enough here; the stretch goals add several per user.line 33
  4. Per call: which history to load and save.line 36
  5. Only the signed-in user's history. There is no way to name another user.line 44
src/test/java/dev/algorung/helpdesk/Milestone4Test.java
package dev.algorung.helpdesk;

import static org.assertj.core.api.Assertions.assertThat;

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;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class Milestone4Test {
    static final FakeLlmServer FAKE = FakeLlmServer.start();
    static final String DATA = FakeLlmServer.freshDataDir();

    @DynamicPropertySource
    static void useTheFake(DynamicPropertyRegistry registry) {
        registry.add("spring.ai.openai.base-url", FAKE::baseUrl);
        registry.add("spring.ai.retry.max-attempts", () -> "1");
        registry.add("helpdesk.data-dir", () -> DATA);
    }

    @Autowired
    TestRestTemplate http;

    TestRestTemplate as(String user) {
        return http.withBasicAuth(user, user + "-pass");
    }

    String chat(String user, String message) {
        Map<?, ?> reply = as(user).postForObject("/api/chat", Map.of("message", message), Map.class);
        return (String) reply.get("answer");
    }

    String lastPrompt() {
        return FAKE.lastChatRequest().path("messages").toString();
    }

    @Test
    void earlierTurnsAreSentAgain() {
        chat("ana", "My name is Ana and I sit on floor 4.");
        chat("ana", "Where do I sit?");
        assertThat(lastPrompt()).contains("My name is Ana and I sit on floor 4.");
    }

    @Test
    void eachUserHasTheirOwnMemory() {
        chat("ana", "My favourite colour is green.");
        chat("ben", "What is my favourite colour?");
        assertThat(lastPrompt()).doesNotContain("green");
    }

    @Test
    void forgettingClearsOnlyYourOwnMemory() {
        chat("ana", "I work from the Lisbon office.");
        chat("ben", "I work from the Berlin office.");
        assertThat(as("ben").exchange("/api/chat/memory", HttpMethod.DELETE, null, Map.class).getStatusCode())
                .isEqualTo(HttpStatus.OK);
        chat("ben", "Which office do I work from?");
        assertThat(lastPrompt()).doesNotContain("Berlin");
        chat("ana", "Which office do I work from?");
        assertThat(lastPrompt()).contains("Lisbon");
    }
}
  1. Everything Spring AI sent to the model in the last request, as JSON text. Memory is just earlier messages in that list.line 40
  2. ben's request must not carry ana's history.line 55
  3. TestRestTemplate.exchange sends any method; there is no delete that returns the response.line 62
  4. ben clearing his memory must leave ana's untouched.line 67
Run
./mvnw test -Dtest=Milestone4Test

# restart the app, then:
curl -s -u ana:ana-pass localhost:8080/api/chat -H "Content-Type: application/json" -d '{"message": "Hi, I am Ana from the Lisbon office."}'
curl -s -u ana:ana-pass localhost:8080/api/chat -H "Content-Type: application/json" -d '{"message": "Which office am I in?"}'
curl -s -u ben:ben-pass localhost:8080/api/chat -H "Content-Type: application/json" -d '{"message": "Which office am I in?"}'
You should seeyour text will differ: the model writes it
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
{"user":"ana","answer":"Hello Ana! Welcome to our virtual space. How can I assist you today? Do you have a question about company policies, need help with an IT issue, or perhaps something else?"}
{"user":"ana","answer":"You're currently connected from the Lisbon office. Is there anything specific related to your location that you'd like assistance with?"}
{"user":"ben","answer":"You're currently in the Larkspur Office, located at [insert location]. If you need any assistance or have questions, feel free to reach out!"}
Why this way? Memory costs tokens: all 20 remembered messages go to the model on every call, so a long chat gets slower and more expensive. The window keeps it bounded. Memory is also lost on restart; the stretch goals swap in the JDBC repository, with the advisor code unchanged.
Stuck on this milestone?
The second question does not know the first answer
Both calls must be made as the same user, and the app must not have restarted in between: this memory lives in the running app.
ben sees ana's conversation
The conversation id comes from somewhere other than principal.getName(), or it is a constant. Print it once to check.
5

Tools that act for the signed-in user, checked in code

The assistant opens IT tickets and reads leave balances through `@Tool` methods, only for the signed-in user, with an allow-list, and copes when a small model gets tool calling wrong.

The services (stand-ins for real systems, plain Java you can unit test). TicketService: List<String> problems(TicketDraft) returns every rule a draft breaks, Ticket create(String user, TicketDraft) throws IllegalArgumentException with those problems, List<Ticket> openTickets(String user). The rules: category must be one of HARDWARE, SOFTWARE, ACCESS, NETWORK (the allow-list), priority one of LOW, MEDIUM, HIGH (blank means MEDIUM), summary 5 to 120 characters; a category problem says "category must be one of ..."; at most 5 open tickets per user. Normalize first (upper case, trimmed, one line). Records: TicketDraft(String category, String priority, String summary), Ticket(String id, String user, String category, String priority, String summary, String status) with ids IT-1001, IT-1002, ... and status OPEN. LeaveService.balance(String user, String leaveType) returns LeaveBalance(String user, String leaveType, int entitledDays, int takenDays, int remainingDays); types are ANNUAL (blank means ANNUAL) and CARRY_OVER, anything else throws with "leaveType must be ANNUAL or CARRY_OVER". ana has 25 annual days and took 7; ben has 25 and took 18.

The tools. HelpdeskTools is a @Component with two @Tool methods, createItTicket(String category, String summary, String priority, ToolContext context) (priority optional) and checkLeaveBalance(String leaveType, ToolContext context). Neither has a user parameter: the user comes only from the ToolContext, which your controller fills with Map.of(HelpdeskTools.USER, user, HelpdeskTools.LOG, log) on every call. No user in the context means IllegalStateException. The model's arguments are untrusted input: validate them in the services, and let exceptions out. Spring AI catches an exception from a tool and sends its message to the model as the tool result, so the model can explain or fix it.

The log. ToolCallLog records what the tools really did in this request: Action(String tool, boolean ok, String result), where result is the ticket id or the leave summary when ok, and the error message when not. POST /api/chat now returns {"user", "answer", "actions": [...]} from that log. Never derive actions from the answer text.

Checks in code for what small models do (on a Mac with llama3.2:3b, all of these happened): skip the tool and answer anyway, ask "what priority should it have?" instead of acting, write {"name": "createItTicket", ...} as plain text, pack every argument into category so the tool rejects the call, or say "I opened ticket IT-123" without a call that worked. After the first answer: if no tool call worked (none ran, or the tool rejected it) and (the answer contains a tool call written as text or the message clearly asks for an action, like "broken", "not working", "ticket" or "days left", and is not a question about the process like "How do I...") send one nudge as the next user message. The nudge must contain the sentence "Call the right tool now." and tell the model not to ask questions. If still no tool call worked and the answer claims an action (an IT- or # number, "ticket has been created", "opened a ticket") or is a tool call as text, replace it with an answer that starts with "I could not complete that action". One nudge, never a loop.

What the fake does (so you can read the tests): a request that offers tools gets a createItTicket call when the message mentions "ticket" or "broken", and checkLeaveBalance for "days" or "balance". To test your checks it misbehaves for some words: "keyboard" asks a question first, "mouse" writes the call as text first, "monitor" claims a ticket and never calls the tool, "headset" packs every argument into category on the first try (the real model did this), "PAYROLL" passes a category outside the allow-list. After a tool runs it answers "The tool says: " plus the tool result.

Done when
  • ./mvnw test -Dtest=Milestone5Test passes (9 tests).
  • As ana, "My laptop screen is broken, please open a ticket." returns an actions entry {"tool":"createItTicket","ok":true,"result":"IT-1001"} and the app log shows [tool] createItTicket for ana: IT-1001.
  • As ana and as ben, "How many vacation days do I have left?" says 18 and 7: the same question, the same model, a different user.
Hints
  1. Register the tools once on the builder; pass the per-request data with .toolContext(Map.of(...)) on each prompt(). .defaultTools(tools) works, but Spring AI lists the @Tool methods in reflection order, which can change from one start to the next. ToolCallbacks.from(tools) sorted by getToolDefinition().name() and passed to .defaultToolCallbacks(...) sends the same request on every start.
  2. Spring AI leaves a ToolContext parameter out of the JSON Schema it sends to the model, so the model cannot even see where the user comes from.
  3. A mutable object in the tool context works as a channel back to the controller: put a new ToolCallLog in the map, the tool adds to it, the controller reads it after .call().
  4. Regular expressions for the checks: "name"\s*:\s*"(createItTicket|checkLeaveBalance)" finds a tool call written as text; \bIT-\d+\b and #\d{3,} find a ticket number in the answer.
Show the reference solution for milestone 5

Try it yourself first. This is one good way to do it, not the only one.

src/main/java/dev/algorung/helpdesk/TicketDraft.java
package dev.algorung.helpdesk;

import com.fasterxml.jackson.annotation.JsonPropertyDescription;

/** What the model fills in: from a tool call (milestone 5) or from free text (milestone 6). Untrusted until checked. */
public record TicketDraft(
        @JsonPropertyDescription("one of HARDWARE, SOFTWARE, ACCESS, NETWORK") String category,
        @JsonPropertyDescription("one of LOW, MEDIUM, HIGH") String priority,
        @JsonPropertyDescription("one short sentence that describes the problem") String summary) {}
  1. What a model fills in, from a tool call here or from free text in milestone 6. Untrusted until TicketService.problems says it is clean.line 6
  2. Descriptions go into the JSON Schema for .entity() in milestone 6. They help the model; they guarantee nothing.line 7
src/main/java/dev/algorung/helpdesk/Ticket.java
package dev.algorung.helpdesk;

public record Ticket(String id, String user, String category, String priority, String summary, String status) {}
  1. What the ticket system returns. As a tool result Spring AI turns it into JSON for the model; as an endpoint result Spring turns it into JSON for the client.line 3
src/main/java/dev/algorung/helpdesk/TicketService.java
package dev.algorung.helpdesk;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.stereotype.Service;

/** A stand-in for the real ticket system. Every rule about a valid ticket lives here, in one place. */
@Service
public class TicketService {
    static final Set<String> CATEGORIES = Set.of("HARDWARE", "SOFTWARE", "ACCESS", "NETWORK");
    static final Set<String> PRIORITIES = Set.of("LOW", "MEDIUM", "HIGH");
    static final int MAX_OPEN_TICKETS = 5;

    private final AtomicInteger nextId = new AtomicInteger(1001);
    private final Map<String, List<Ticket>> byUser = new ConcurrentHashMap<>();

    /** Normalizes what a model wrote: upper-case codes, MEDIUM when no priority, one line of summary. */
    public TicketDraft normalize(TicketDraft d) {
        String category = d.category() == null ? "" : d.category().strip().toUpperCase(Locale.ROOT);
        String priority = d.priority() == null || d.priority().isBlank()
                ? "MEDIUM" : d.priority().strip().toUpperCase(Locale.ROOT);
        String summary = d.summary() == null ? "" : d.summary().replaceAll("\\s+", " ").strip();
        return new TicketDraft(category, priority, summary);
    }

    /** Everything wrong with a draft, as sentences a person (or a model) can act on. Empty means valid. */
    public List<String> problems(TicketDraft draft) {
        TicketDraft d = normalize(draft);
        List<String> problems = new ArrayList<>();
        if (!CATEGORIES.contains(d.category())) {
            problems.add("category must be one of " + String.join(", ", sorted(CATEGORIES)));
        }
        if (!PRIORITIES.contains(d.priority())) {
            problems.add("priority must be one of LOW, MEDIUM, HIGH");
        }
        if (d.summary().length() < 5 || d.summary().length() > 120) {
            problems.add("summary must be 5 to 120 characters");
        }
        return problems;
    }

    public Ticket create(String user, TicketDraft draft) {
        List<String> problems = problems(draft);
        if (!problems.isEmpty()) {
            throw new IllegalArgumentException("Ticket not created: " + String.join("; ", problems));
        }
        List<Ticket> mine = byUser.computeIfAbsent(user, u -> new CopyOnWriteArrayList<>());
        if (mine.size() >= MAX_OPEN_TICKETS) {
            throw new IllegalArgumentException("Ticket not created: " + user + " already has "
                    + MAX_OPEN_TICKETS + " open tickets");
        }
        TicketDraft d = normalize(draft);
        Ticket ticket = new Ticket("IT-" + nextId.getAndIncrement(), user, d.category(), d.priority(), d.summary(), "OPEN");
        mine.add(ticket);
        System.out.println("[ticket] " + ticket.id() + " for " + user + ": " + ticket.summary());
        return ticket;
    }

    public List<Ticket> openTickets(String user) {
        return List.copyOf(byUser.getOrDefault(user, List.of()));
    }

    private static List<String> sorted(Set<String> values) {
        return values.stream().sorted().toList();
    }
}
  1. The allow-list. A category the model invents, like PAYROLL, is rejected here, not trusted.line 17
  2. A limit a confused model cannot get around by calling the tool in a loop.line 19
  3. Be lenient about form (case, spaces, a missing priority), strict about content.line 25
  4. Every problem, as sentences. Milestone 6 sends them back to the model so it can fix its answer.line 34
  5. The message goes back to the model as the tool result, so it can tell the user what was wrong.line 52
  6. Thread-safe ids: two requests can create tickets at the same time.line 10
src/main/java/dev/algorung/helpdesk/LeaveBalance.java
package dev.algorung.helpdesk;

public record LeaveBalance(String user, String leaveType, int entitledDays, int takenDays, int remainingDays) {}
  1. The tool result the model reads, as JSON: {"user":"ana","leaveType":"ANNUAL","entitledDays":25,"takenDays":7,"remainingDays":18}.line 3
src/main/java/dev/algorung/helpdesk/LeaveService.java
package dev.algorung.helpdesk;

import java.util.Locale;
import java.util.Map;
import java.util.Set;

import org.springframework.stereotype.Service;

/** A stand-in for the HR system: fixed balances for the two demo users. */
@Service
public class LeaveService {
    static final Set<String> LEAVE_TYPES = Set.of("ANNUAL", "CARRY_OVER");

    private static final Map<String, Map<String, int[]>> BALANCES = Map.of(
            "ana", Map.of("ANNUAL", new int[] {25, 7}, "CARRY_OVER", new int[] {3, 0}),
            "ben", Map.of("ANNUAL", new int[] {25, 18}, "CARRY_OVER", new int[] {0, 0}));

    public LeaveBalance balance(String user, String leaveType) {
        String type = leaveType == null || leaveType.isBlank() ? "ANNUAL" : leaveType.strip().toUpperCase(Locale.ROOT);
        if (!LEAVE_TYPES.contains(type)) {
            throw new IllegalArgumentException("leaveType must be ANNUAL or CARRY_OVER");
        }
        Map<String, int[]> mine = BALANCES.get(user);
        if (mine == null) {
            throw new IllegalArgumentException("no leave record for " + user);
        }
        int[] days = mine.get(type);
        return new LeaveBalance(user, type, days[0], days[1], days[0] - days[1]);
    }
}
  1. The second allow-list: the model can only ask for these two.line 12
  2. Fixed demo data. A real version calls the HR system with the user's id.line 15
src/main/java/dev/algorung/helpdesk/ToolCallLog.java
package dev.algorung.helpdesk;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/** What the tools really did during one request. The reply shows this list, never what the model claims. */
public class ToolCallLog {
    public record Action(String tool, boolean ok, String result) {}

    private final List<Action> actions = new CopyOnWriteArrayList<>();

    void ok(String tool, String result) {
        actions.add(new Action(tool, true, result));
    }

    void rejected(String tool, String reason) {
        actions.add(new Action(tool, false, reason));
    }

    boolean anyOk() {
        return actions.stream().anyMatch(Action::ok);
    }

    List<Action> actions() {
        return List.copyOf(actions);
    }
}
  1. One entry per tool call: which tool, whether it worked, and the id or the error.line 8
  2. Thread-safe, in case Spring AI runs a tool on another thread.line 4
  3. True only if at least one tool call worked. A rejected call is in the log too, so "the log is not empty" is not enough to trust a claim.line 20
src/main/java/dev/algorung/helpdesk/HelpdeskTools.java
package dev.algorung.helpdesk;

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

/**
 * The model's only way to act. The user always comes from the ToolContext the server sets, never from
 * the model's arguments, so nobody can open tickets or read balances for someone else.
 */
@Component
public class HelpdeskTools {
    public static final String USER = "user";
    public static final String LOG = "log";

    private final TicketService tickets;
    private final LeaveService leave;

    HelpdeskTools(TicketService tickets, LeaveService leave) {
        this.tickets = tickets;
        this.leave = leave;
    }

    @Tool(description = "Open an IT support ticket for the signed-in employee. "
            + "Use it when something is broken or not working, or when they ask for a ticket.")
    public Ticket createItTicket(
            @ToolParam(description = "One of HARDWARE, SOFTWARE, ACCESS, NETWORK") String category,
            @ToolParam(description = "One short sentence that describes the problem") String summary,
            @ToolParam(description = "One of LOW, MEDIUM, HIGH. Use MEDIUM if unsure.", required = false) String priority,
            ToolContext context) {
        String user = user(context);
        try {
            Ticket ticket = tickets.create(user, new TicketDraft(category, priority, summary));
            record(context, "createItTicket", true, ticket.id());
            return ticket;
        } catch (IllegalArgumentException e) {
            record(context, "createItTicket", false, e.getMessage());
            throw e;
        }
    }

    @Tool(description = "How many leave days the signed-in employee has left. "
            + "leaveType is ANNUAL (this year's vacation) or CARRY_OVER (days kept from last year).")
    public LeaveBalance checkLeaveBalance(
            @ToolParam(description = "ANNUAL or CARRY_OVER", required = false) String leaveType,
            ToolContext context) {
        String user = user(context);
        try {
            LeaveBalance balance = leave.balance(user, leaveType);
            record(context, "checkLeaveBalance", true, balance.remainingDays() + " " + balance.leaveType() + " days left");
            return balance;
        } catch (IllegalArgumentException e) {
            record(context, "checkLeaveBalance", false, e.getMessage());
            throw e;
        }
    }

    private static String user(ToolContext context) {
        Object user = context.getContext().get(USER);
        if (!(user instanceof String name) || name.isBlank()) {
            throw new IllegalStateException("no signed-in user in the tool context");
        }
        return name;
    }

    private static void record(ToolContext context, String tool, boolean ok, String result) {
        System.out.println("[tool] " + tool + " for " + context.getContext().get(USER) + ": " + result);
        if (context.getContext().get(LOG) instanceof ToolCallLog log) {
            if (ok) {
                log.ok(tool, result);
            } else {
                log.rejected(tool, result);
            }
        }
    }
}
  1. The keys of the tool context, shared by the controller and the tools.line 14
  2. The model reads this description to decide when to call the tool, and the method name becomes the tool name.line 25
  3. Optional in the schema, so the model may leave it out; normalize turns a missing priority into MEDIUM.line 30
  4. Not in the schema the model sees. Spring AI passes the map your controller set with .toolContext(...).line 31
  5. The user is the signed-in user, always. There is no parameter the model could fill with "ben".line 32
  6. Rethrow after logging. Spring AI's default ToolExecutionExceptionProcessor returns the message to the model as the tool result instead of failing the request.line 39
  7. No user means a bug in the server, not a model mistake.line 62
  8. Record what really happened, for the reply's actions.line 69
src/main/java/dev/algorung/helpdesk/Nudges.java
package dev.algorung.helpdesk;

import java.util.Locale;
import java.util.regex.Pattern;

/** Checks in code for the habits of small models: skipping tools, writing tool calls as text, asking instead of acting. */
final class Nudges {
    static final String NUDGE = "Do not ask me questions and do not write a tool call as text. "
            + "Call the right tool now. Use priority MEDIUM if I did not say how urgent it is.";

    private static final Pattern ACTION = Pattern.compile(
            "\\b(ticket|broken|not working|stopped working|leave balance|days (do i have )?left|days have i got left)\\b");
    private static final Pattern QUESTION_ABOUT_PROCESS = Pattern.compile("^(how do|how can|how does|what is|what are|where)\\b");
    private static final Pattern TOOL_AS_TEXT = Pattern.compile("\"name\"\\s*:\\s*\"(createItTicket|checkLeaveBalance)\"");
    private static final Pattern CLAIMS_ACTION = Pattern.compile(
            "\\bIT-\\d+\\b|#\\d{3,}|ticket (has been|was|is) (created|opened|raised)"
            + "|(opened|created|raised) (a|an|the|your)( IT)? ticket", Pattern.CASE_INSENSITIVE);

    private Nudges() {
    }

    /** "My laptop is broken" needs a tool; "How do I open a ticket?" is a question about the process. */
    static boolean needsAction(String message) {
        String m = message.toLowerCase(Locale.ROOT).strip();
        return ACTION.matcher(m).find() && !QUESTION_ABOUT_PROCESS.matcher(m).find();
    }

    static boolean wroteToolCallAsText(String answer) {
        return answer != null && TOOL_AS_TEXT.matcher(answer).find();
    }

    static boolean claimsAction(String answer) {
        return answer != null && CLAIMS_ACTION.matcher(answer).find();
    }
}
  1. Contains "Call the right tool now", the sentence the fake looks for. Firm and short: small models follow short instructions best.line 8
  2. Words that mean "do something". A keyword list is crude, so it only decides whether to send **one** extra message, never what to do.line 11
  3. "How do I open a ticket?" is a question for the docs, not a request to open one. Without this, the nudge would create tickets nobody asked for.line 13
  4. A small model sometimes writes the tool call into the answer instead of calling it.line 14
  5. An answer that says a ticket exists: an id like IT-1001 or #1234, or "opened a ticket" (all three seen from llama3.2:3b). Only allowed when the log has a tool call that worked.line 15
src/main/java/dev/algorung/helpdesk/ChatController.java 29 new or changed lines
package dev.algorung.helpdesk;

import java.security.Principal;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

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.ai.support.ToolCallbacks;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.web.bind.annotation.DeleteMapping;
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 user, String answer, List<ToolCallLog.Action> actions) {}

    static final String COULD_NOT_ACT =
            "I could not complete that action. Please try again, or open a ticket in the IT portal.";

    private final ChatClient chat;
    private final ChatMemory memory;

    ChatController(ChatClient.Builder builder, ChatMemory memory, HelpdeskTools tools) {
        this.memory = memory;
        this.chat = builder
                .defaultSystem("""
                        You are Larkspur's internal HR and IT assistant. Be concise and friendly.
                        You act for the signed-in employee with your tools:
                        createItTicket when something is broken or they ask for an IT ticket,
                        checkLeaveBalance when they ask how many leave days they have left.
                        Call the tool instead of asking questions you can answer with sensible defaults.
                        Only say that a ticket exists if the tool returned its id.""")
                .defaultAdvisors(MessageChatMemoryAdvisor.builder(memory).build())
                .defaultToolCallbacks(inNameOrder(tools))
                .build();
    }

    @PostMapping("/api/chat")
    ChatReply chat(@RequestBody ChatRequest request, Principal principal) {
        String message = Inputs.require(request.message(), "message");
        String user = principal.getName();
        ToolCallLog log = new ToolCallLog();

        String answer = ask(user, message, log);
        if (!log.anyOk() && (Nudges.wroteToolCallAsText(answer) || Nudges.needsAction(message))) {
            answer = ask(user, Nudges.NUDGE, log);
        }
        if (!log.anyOk() && (Nudges.wroteToolCallAsText(answer) || Nudges.claimsAction(answer))) {
            answer = COULD_NOT_ACT;
        }
        return new ChatReply(user, answer, log.actions());
    }

    /** Spring AI lists @Tool methods in reflection order, which can change from one start to the next. */
    static ToolCallback[] inNameOrder(Object tools) {
        ToolCallback[] callbacks = ToolCallbacks.from(tools);
        Arrays.sort(callbacks, Comparator.comparing(c -> c.getToolDefinition().name()));
        return callbacks;
    }

    private String ask(String user, String text, ToolCallLog log) {
        return chat.prompt()
                .user(text)
                .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, user))
                .toolContext(Map.of(HelpdeskTools.USER, user, HelpdeskTools.LOG, log))
                .call()
                .content();
    }

    @DeleteMapping("/api/chat/memory")
    Map<String, String> forget(Principal principal) {
        memory.clear(principal.getName());
        return Map.of("user", principal.getName(), "memory", "cleared");
    }
}
  1. Now with actions: what the tools did, from the log. A UI shows these as facts, and the answer as text.line 22
  2. Tell the model what each tool is for and to act instead of asking. Helpful, not enough: the checks below handle the rest.line 33
  3. Spring AI sends both tool schemas with every request and runs the tool loop inside .call(). Same as .defaultTools(tools), but in a fixed order.line 41
  4. Found on a real run: Spring AI reads @Tool methods by reflection, and their order changed between starts. With createItTicket listed first, llama3.2:3b packed every argument into category on every call of that run. Sorted by name, it got them right on every start.line 62
  5. A new log per request.line 49
  6. Nudge when no tool call worked: none at all, or one the tool rejected. A small model that gets a rejection often asks the user instead of trying again.line 52
  7. The one nudge, as the next user message. Memory keeps the first exchange, so the model sees what was asked.line 53
  8. Not isEmpty(): on a real run the model sent arguments the tool rejected, then answered "I've opened a ticket... IT-1234" anyway. No call that worked means no claim reaches the user.line 52
  9. Trust the log, not the text: the model said it acted, the log says it did not.line 56
  10. The user and the log for the tools of this call. Server data, never model data.line 72
src/test/java/dev/algorung/helpdesk/Milestone5Test.java
package dev.algorung.helpdesk;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import java.util.List;
import java.util.Map;

import org.junit.jupiter.api.Test;
import org.springframework.ai.chat.model.ToolContext;
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 Milestone5Test {
    static final FakeLlmServer FAKE = FakeLlmServer.start();
    static final String DATA = FakeLlmServer.freshDataDir();

    @DynamicPropertySource
    static void useTheFake(DynamicPropertyRegistry registry) {
        registry.add("spring.ai.openai.base-url", FAKE::baseUrl);
        registry.add("spring.ai.retry.max-attempts", () -> "1");
        registry.add("helpdesk.data-dir", () -> DATA);
    }

    @Autowired
    TestRestTemplate http;

    TestRestTemplate as(String user) {
        return http.withBasicAuth(user, user + "-pass");
    }

    @Autowired
    TicketService tickets;

    @Autowired
    HelpdeskTools tools;

    Map<?, ?> chat(String user, String message) {
        return as(user).postForObject("/api/chat", Map.of("message", message), Map.class);
    }

    @SuppressWarnings("unchecked")
    List<Map<String, Object>> actions(Map<?, ?> reply) {
        return (List<Map<String, Object>>) reply.get("actions");
    }

    @Test
    void theTicketToolRunsForTheSignedInUser() {
        Map<?, ?> reply = chat("ana", "My laptop screen is broken, please open a ticket.");
        Map<String, Object> action = actions(reply).get(0);
        assertThat(action).containsEntry("tool", "createItTicket").containsEntry("ok", true);
        String id = (String) action.get("result");
        assertThat(id).matches("IT-\\d+");
        assertThat((String) reply.get("answer")).contains(id);
        assertThat(tickets.openTickets("ana")).anySatisfy(t -> assertThat(t.id()).isEqualTo(id));
        assertThat(tickets.openTickets("ben")).noneSatisfy(t -> assertThat(t.id()).isEqualTo(id));
    }

    @Test
    void leaveBalancesComeFromTheSignedInUserNotTheModel() {
        assertThat((String) chat("ana", "How many vacation days do I have left?").get("answer"))
                .contains("\"user\":\"ana\"", "\"remainingDays\":18");
        assertThat((String) chat("ben", "How many vacation days do I have left?").get("answer"))
                .contains("\"user\":\"ben\"", "\"remainingDays\":7");
    }

    @Test
    void aCategoryOutsideTheAllowListIsRejected() {
        int before = tickets.openTickets("ana").size();
        Map<?, ?> reply = chat("ana", "Open a ticket in category PAYROLL about my salary slip.");
        assertThat(actions(reply).get(0)).containsEntry("tool", "createItTicket").containsEntry("ok", false);
        assertThat((String) actions(reply).get(0).get("result")).contains("category must be one of");
        assertThat(tickets.openTickets("ana")).hasSize(before);
    }

    @Test
    void askingInsteadOfActingGetsOneNudge() {
        Map<?, ?> reply = chat("ben", "My keyboard is broken.");
        assertThat(actions(reply)).anySatisfy(a -> assertThat(a).containsEntry("tool", "createItTicket").containsEntry("ok", true));
    }

    @Test
    void aToolCallWrittenAsTextGetsOneNudge() {
        Map<?, ?> reply = chat("ben", "My mouse is broken.");
        assertThat(actions(reply)).anySatisfy(a -> assertThat(a).containsEntry("tool", "createItTicket").containsEntry("ok", true));
        assertThat((String) reply.get("answer")).doesNotContain("\"name\"");
    }

    @Test
    void aClaimWithoutAToolCallIsNotShownToTheUser() {
        Map<?, ?> reply = chat("ana", "My monitor is broken.");
        assertThat(actions(reply)).isEmpty();
        assertThat((String) reply.get("answer")).startsWith("I could not complete that action").doesNotContain("IT-4242");
    }

    @Test
    void aRejectedCallGetsOneNudgeToo() {
        Map<?, ?> reply = chat("ana", "My headset is broken.");
        assertThat(actions(reply)).hasSize(2);
        assertThat(actions(reply).get(0)).containsEntry("tool", "createItTicket").containsEntry("ok", false);
        assertThat(actions(reply).get(1)).containsEntry("tool", "createItTicket").containsEntry("ok", true);
        assertThat((String) reply.get("answer")).contains((String) actions(reply).get(1).get("result"));
    }

    @Test
    void theToolsAreSentInTheSameOrderOnEveryStart() {
        assertThat(ChatController.inNameOrder(tools)).extracting(c -> c.getToolDefinition().name())
                .containsExactly("checkLeaveBalance", "createItTicket");
    }

    @Test
    void theToolsReadTheUserFromTheToolContext() {
        LeaveBalance ben = tools.checkLeaveBalance("ANNUAL", new ToolContext(Map.of(HelpdeskTools.USER, "ben")));
        assertThat(ben.remainingDays()).isEqualTo(7);
        assertThatThrownBy(() -> tools.checkLeaveBalance("ANNUAL", new ToolContext(Map.of())))
                .isInstanceOf(IllegalStateException.class);
        assertThatThrownBy(() -> tools.checkLeaveBalance("SABBATICAL", new ToolContext(Map.of(HelpdeskTools.USER, "ben"))))
                .hasMessageContaining("ANNUAL or CARRY_OVER");
    }
}
  1. The result of a successful ticket action is the ticket id.line 57
  2. ana's ticket is not in ben's list.line 60
  3. The fake answers with the tool result, so the number in the answer comes from LeaveService for the signed-in user.line 66
  4. The model asks for a category outside the allow-list: the action is recorded with ok: false and no ticket exists.line 74
  5. The fake asks a question back first. Your nudge makes it act.line 82
  6. After the nudge, the final answer must not be the tool call written as text.line 90
  7. The fake claims ticket IT-4242 even after the nudge. The user must never see that claim.line 95
  8. The first call is rejected (all arguments packed into category), the nudge gets a good one: two actions, and the answer has the id of the second.line 102
  9. The same order on every start, whatever order reflection returns the methods in.line 112
  10. A unit test with no model: the tool is plain Java.line 117
Run
./mvnw test -Dtest=Milestone5Test

# restart the app, then:
curl -s -u ana:ana-pass localhost:8080/api/chat -H "Content-Type: application/json" -d '{"message": "My laptop screen is broken, please open a ticket."}'
curl -s -u ana:ana-pass localhost:8080/api/chat -H "Content-Type: application/json" -d '{"message": "How many vacation days do I have left?"}'
curl -s -u ben:ben-pass localhost:8080/api/chat -H "Content-Type: application/json" -d '{"message": "How many vacation days do I have left?"}'
You should seeyour text will differ: the model writes it
[INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
[ticket] IT-1001 for ana: Laptop screen is broken
[tool] createItTicket for ana: IT-1001
{"user":"ana","answer":"Your IT ticket has been created, IT-1001. The status of your request is currently \"OPEN\". Our team will review and respond to it as soon as possible. You can track the progress by logging into our portal or checking your email for updates.","actions":[{"tool":"createItTicket","ok":true,"result":"IT-1001"}]}
[tool] checkLeaveBalance for ana: 18 ANNUAL days left
{"user":"ana","answer":"You have 18 annual vacation days left.","actions":[{"tool":"checkLeaveBalance","ok":true,"result":"18 ANNUAL days left"}]}
[tool] checkLeaveBalance for ben: 7 ANNUAL days left
{"user":"ben","answer":"You have 7 vacation days left.","actions":[{"tool":"checkLeaveBalance","ok":true,"result":"7 ANNUAL days left"}]}
Why this way? Three layers keep tools safe, and none of them is the prompt. Who: the user comes from Spring Security through the tool context, so no prompt injection can act for someone else. What: allow-lists and limits in the services decide what is valid. Did it happen: the log, not the model's words, tells the user what was done. The nudge only makes a small model more useful; capstone 2 used the same idea with its retry-and-check loop in Python.
Stuck on this milestone?
ToolContext is required by the method as an argument
The call had no tool context. Every prompt() on this client needs .toolContext(Map.of(...)), the nudge too.
The model sends arg0 instead of category
The code was compiled without -parameters. Keep the spring-boot-starter-parent parent, which turns it on.
Every ticket call of one run is rejected with "category must be one of ...; summary must be 5 to 120 characters", and the next run works
Seen on a Mac with llama3.2:3b: the model sent {"category": "{\"type\":\"NETWORK\",\"summary\":...}"}, every argument packed into one. It happened on every start where createItTicket was the first tool in the request, and the order came from reflection. Register the tools sorted by name (inNameOrder), and nudge once when the only tool call was rejected.
With the real model, nothing happens and actions is empty
Look for [tool] lines in the log. If there are none, the model skipped the tool and the nudge did not trigger: is the message one of the ACTION words? llama3.1:8b (about 5 GB) calls tools far more reliably than a 3B model.
A tool error makes the whole request fail with 500
The exception is not a RuntimeException, or spring.ai.tools.throw-exception-on-error=true is set. Throw IllegalArgumentException for bad arguments.
After this milestone, "Hi!" or "What is my name?" answers with a leave balance
Seen on a Mac with llama3.2:3b: once tools are offered, it calls one on almost every message, and a line in the system prompt asking it not to did not change that. Here it is harmless, because checkLeaveBalance only reads, and actions shows the call. It is one more reason for the fixed order: with createItTicket listed first, the same model opened a ticket for "My name is Ana.". llama3.1:8b calls tools only when they are needed.
6

Structured output: free text to a validated ticket

`POST /api/tickets/from-text` turns a description into a `TicketDraft` with `.entity()`, validates it with the same rules as the tool, retries once with the problems, and creates the ticket or answers 422.

Why a second way to create tickets? A form, an email or a chat in another tool sends a whole paragraph, not tool arguments. You want typed data out of it, and you want the same rules as the tool, so there is one definition of a valid ticket: TicketService.problems.

TicketController with its own ChatClient (no tools, no memory) and a system prompt that names the allowed categories and priorities. POST /api/tickets/from-text takes {"text": "..."} (same input rules as before):

  1. .call().entity(TicketDraft.class). Spring AI adds the JSON Schema of the record to the prompt and maps the reply into the record (lab 10, milestone 4).
  2. If the reply was not JSON for the record, that counts as the problem "the answer was not valid JSON". Otherwise ask tickets.problems(draft).
  3. Any problems: call the model once more, with the same text plus Your previous answer had these problems: <problems>. Fix these problems and answer again. (the fake looks for "Fix these problems").
  4. Still problems: 422 with {"error": "Could not turn the text into a valid ticket", "problems": [...]}. No ticket.
  5. Valid: 201 with the created Ticket for the signed-in user.

Also add GET /api/tickets: the signed-in user's open tickets.

Only catch what you mean. .entity() throws a RuntimeException caused by Jackson's JsonProcessingException when the reply is not valid JSON. Ollama being down is a RuntimeException too, and must still reach ApiErrors as a 503, so check the cause, do not catch everything.

What the fake does: for text with "vpn" it returns a valid NETWORK ticket; for "printer" it first returns the category PRINTER (not allowed) and a valid HARDWARE ticket once it sees "Fix these problems"; for "nonsense" it never returns JSON.

Done when
  • ./mvnw test -Dtest=Milestone6Test passes (4 tests).
  • curl -s -u ana:ana-pass localhost:8080/api/tickets/from-text -H "Content-Type: application/json" -d '{"text": "Since this morning the VPN drops every few minutes and I cannot reach the wiki."}' returns 201 with a NETWORK ticket, and curl -s -u ana:ana-pass localhost:8080/api/tickets lists it.
  • The same list as ben does not contain ana's ticket.
Hints
  1. Keep the retry in a small helper, TicketDraft extract(String text, List<String> problems), that returns null for "not JSON". Then the endpoint reads like the five steps above.
  2. Walk the cause chain: for (Throwable t = e; t != null; t = t.getCause()) if (t instanceof JsonProcessingException) ....
  3. ResponseEntity.unprocessableEntity().body(...) is the 422; ResponseEntity.status(HttpStatus.CREATED).body(ticket) the 201.
Show the reference solution for milestone 6

Try it yourself first. This is one good way to do it, not the only one.

src/main/java/dev/algorung/helpdesk/TicketController.java
package dev.algorung.helpdesk;

import java.security.Principal;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.RestController;

@RestController
public class TicketController {
    record TextRequest(String text) {}

    private final ChatClient chat;
    private final TicketService tickets;

    TicketController(ChatClient.Builder builder, TicketService tickets) {
        this.tickets = tickets;
        this.chat = builder
                .defaultSystem("You turn an employee's description of an IT problem into a ticket. "
                        + "category is one of HARDWARE, SOFTWARE, ACCESS, NETWORK. "
                        + "priority is one of LOW, MEDIUM, HIGH. summary is one short sentence.")
                .build();
    }

    /** Free text in, a validated ticket out: 201 with the ticket, or 422 with the problems. */
    @PostMapping("/api/tickets/from-text")
    ResponseEntity<?> fromText(@RequestBody TextRequest request, Principal principal) {
        String text = Inputs.require(request.text(), "text");

        TicketDraft draft = extract(text, List.of());
        List<String> problems = draft == null ? List.of("the answer was not valid JSON") : tickets.problems(draft);
        if (!problems.isEmpty()) {
            draft = extract(text, problems);
            problems = draft == null ? List.of("the answer was not valid JSON") : tickets.problems(draft);
        }
        if (!problems.isEmpty()) {
            return ResponseEntity.unprocessableEntity()
                    .body(Map.of("error", "Could not turn the text into a valid ticket", "problems", problems));
        }
        return ResponseEntity.status(HttpStatus.CREATED).body(tickets.create(principal.getName(), draft));
    }

    @GetMapping("/api/tickets")
    List<Ticket> mine(Principal principal) {
        return tickets.openTickets(principal.getName());
    }

    /** One model call that must return a TicketDraft. null when the reply is not JSON for the record. */
    private TicketDraft extract(String text, List<String> problems) {
        String prompt = problems.isEmpty() ? text
                : text + "\n\nYour previous answer had these problems: " + String.join("; ", problems)
                        + ". Fix these problems and answer again.";
        try {
            return chat.prompt().user(prompt).call().entity(TicketDraft.class);
        } catch (RuntimeException e) {
            if (causedByBadJson(e)) {
                return null;
            }
            throw e;
        }
    }

    private static boolean causedByBadJson(Throwable e) {
        for (Throwable t = e; t != null; t = t.getCause()) {
            if (t instanceof JsonProcessingException) {
                return true;
            }
        }
        return false;
    }
}
  1. The allowed values in the prompt make a valid answer likely. TicketService.problems makes an invalid one impossible to save.line 27
  2. Attempt one.line 38
  3. Attempt two, with the exact problems: models fix a named mistake much more reliably than a vague "try again".line 41
  4. 422: the request was fine, but the model could not produce a valid ticket from it. The client can show the problems or ask the user.line 45
  5. 201 with the ticket, for the signed-in user only.line 48
  6. One model call. The reply is parsed into the record by Jackson; descriptions from @JsonPropertyDescription are in the schema.line 62
  7. Only bad JSON becomes a retry. A connection error is rethrown and becomes a 503 in ApiErrors.line 64
src/test/java/dev/algorung/helpdesk/Milestone6Test.java
package dev.algorung.helpdesk;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.List;
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;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class Milestone6Test {
    static final FakeLlmServer FAKE = FakeLlmServer.start();
    static final String DATA = FakeLlmServer.freshDataDir();

    @DynamicPropertySource
    static void useTheFake(DynamicPropertyRegistry registry) {
        registry.add("spring.ai.openai.base-url", FAKE::baseUrl);
        registry.add("spring.ai.retry.max-attempts", () -> "1");
        registry.add("helpdesk.data-dir", () -> DATA);
    }

    @Autowired
    TestRestTemplate http;

    TestRestTemplate as(String user) {
        return http.withBasicAuth(user, user + "-pass");
    }

    ResponseEntity<Map> fromText(String user, String text) {
        return as(user).postForEntity("/api/tickets/from-text", Map.of("text", text), Map.class);
    }

    @Test
    void freeTextBecomesAValidTicket() {
        ResponseEntity<Map> created = fromText("ana", "My VPN disconnects every few minutes when I work from home.");
        assertThat(created.getStatusCode()).isEqualTo(HttpStatus.CREATED);
        assertThat(created.getBody()).containsEntry("category", "NETWORK").containsEntry("priority", "HIGH")
                .containsEntry("user", "ana").containsEntry("status", "OPEN");
        Object id = created.getBody().get("id");
        assertThat(as("ana").getForObject("/api/tickets", List.class)).anySatisfy(t -> assertThat((Map<String, Object>) t).containsEntry("id", id));
        assertThat(as("ben").getForObject("/api/tickets", List.class)).noneSatisfy(t -> assertThat((Map<String, Object>) t).containsEntry("id", id));
    }

    @Test
    void anInvalidAnswerIsRetriedOnceWithTheProblems() {
        ResponseEntity<Map> created = fromText("ben", "The printer on floor 3 is jammed again.");
        assertThat(created.getStatusCode()).isEqualTo(HttpStatus.CREATED);
        assertThat(created.getBody()).containsEntry("category", "HARDWARE");
        String retryPrompt = FAKE.lastChatRequest().path("messages").toString();
        assertThat(retryPrompt).contains("Fix these problems", "category must be one of");
    }

    @Test
    void anAnswerThatIsNeverValidGives422AndNoTicket() {
        int before = as("ben").getForObject("/api/tickets", List.class).size();
        ResponseEntity<Map> reply = fromText("ben", "nonsense nonsense nonsense");
        assertThat(reply.getStatusCode()).isEqualTo(HttpStatus.UNPROCESSABLE_ENTITY);
        assertThat((List<?>) reply.getBody().get("problems")).isNotEmpty();
        assertThat(as("ben").getForObject("/api/tickets", List.class)).hasSize(before);
    }

    @Test
    void blankTextIsABadRequest() {
        assertThat(fromText("ana", " ").getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
    }
}
  1. Mapped by .entity(), checked by TicketService, created for ana.line 44
  2. The second request carried the problems of the first answer.line 57
  3. Two invalid answers: 422, and the ticket list did not grow.line 64
Run
./mvnw test -Dtest=Milestone6Test

# restart the app, then:
curl -s -u ana:ana-pass localhost:8080/api/tickets/from-text -H "Content-Type: application/json" -d '{"text": "Since this morning the VPN drops every few minutes and I cannot reach the wiki."}'
curl -s -u ana:ana-pass localhost:8080/api/tickets
You should seeyour text will differ: the model writes it
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
[ticket] IT-1001 for ana: VPN drops every few minutes, cannot reach wiki
{"id":"IT-1001","user":"ana","category":"NETWORK","priority":"MEDIUM","summary":"VPN drops every few minutes, cannot reach wiki","status":"OPEN"}
[{"id":"IT-1001","user":"ana","category":"NETWORK","priority":"MEDIUM","summary":"VPN drops every few minutes, cannot reach wiki","status":"OPEN"}]
Why this way? Structured output gives you a typed object, not a correct one. The rules live in one service that the tool and this endpoint both call, and the retry sends the model the exact problems, the loop you built with Pydantic in lab 3. Measure how often the second attempt is needed: if it is often, improve the prompt or the model, do not add a third attempt.
Stuck on this milestone?
Every request ends in 422 with the real model
Log the raw reply once (.call().content() in a test call). Small models sometimes wrap the JSON in prose or invent a category; the system prompt must list the allowed values, and llama3.1:8b follows schemas better.
A 500 instead of a 422
An exception that is not caused by JsonProcessingException escaped, or you catch nothing. Read the first Caused by: in the log.
The log shows ERROR ... BeanOutputConverter : Could not parse the given text to the desired target type, and the ticket is still created
That is the retry working. On a Mac the model once left out the closing } of the JSON; the second call, with "the answer was not valid JSON" as the problem, was fine. Spring AI logs the failed parse as ERROR before it throws.
7

Stream the answer over Server-Sent Events

`GET /api/ask/stream?q=` streams the same RAG answer as `/api/ask`: first the sources, then the text piece by piece, then a done event.

The events, in this order, each with a name and JSON data:

Event Data When
sources [{"source", "section", "score"}] (can be []) once, first
token {"text": " piece"} for every piece of the answer
done {"refused": true or false} once, last
error {"error": "..."} instead of done if the stream fails

How. Use the same client as /api/ask (advisors and guard included) with .stream().chatClientResponse(): a Flux<ChatClientResponse>, where every element carries the advisor context, so the first one already has the retrieved documents. Return a Flux<ServerSentEvent<Object>> from a method with produces = MediaType.TEXT_EVENT_STREAM_VALUE; Spring MVC writes each event as event:<name> and data:<json> lines and flushes them. The guard's adviseStream from milestone 3 makes an off-topic question stream the refusal without a model call.

Why JSON for the tokens (lab 10 sent bare text): the SSE format strips one space after data:, so a browser's EventSource turns the piece " from" into "from" and the words run together. {"text": " from"} keeps the space. Also send the sources first: the UI can show where the answer comes from before the first word arrives.

Done when
  • ./mvnw test -Dtest=Milestone7Test passes (4 tests).
  • curl -N -u ana:ana-pass "localhost:8080/api/ask/stream?q=What%20is%20the%20meal%20allowance%20on%20a%20work%20trip" prints event:sources with expenses.md, then event:token lines as they are generated, then event:done.
Hints
  1. Per-request state (have I sent the sources yet?) belongs inside Flux.defer(() -> ...), so each subscription gets its own.
  2. concatMapIterable turns one ChatClientResponse into zero, one or two events; .concatWith(...) adds the done event at the end; .onErrorResume(...) swaps a failure for an error event.
  3. ServerSentEvent.<Object>builder(data).event("token").build(), from org.springframework.http.codec. It works in Spring MVC, not only WebFlux.
Show the reference solution for milestone 7

Try it yourself first. This is one good way to do it, not the only one.

src/main/java/dev/algorung/helpdesk/RagController.java 29 new or changed lines
package dev.algorung.helpdesk;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

import reactor.core.publisher.Flux;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.ChatClientResponse;
import org.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
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;

@RestController
public class RagController {
    record AskRequest(String question) {}
    record AskReply(String answer, boolean refused, List<SearchController.Hit> sources) {}

    private final ChatClient chat;

    RagController(ChatClient.Builder builder, VectorStore store, NoContextGuard guard,
                  @Value("${helpdesk.rag.top-k}") int topK,
                  @Value("${helpdesk.rag.similarity-threshold}") double threshold) {
        this.chat = builder
                .defaultSystem("You answer questions from Larkspur employees about HR and IT policies. "
                        + "Answer only from the context you are given, in at most three sentences.")
                .defaultAdvisors(
                        QuestionAnswerAdvisor.builder(store)
                                .searchRequest(SearchRequest.builder().topK(topK).similarityThreshold(threshold).build())
                                .build(),
                        guard)
                .build();
    }

    @PostMapping("/api/ask")
    AskReply ask(@RequestBody AskRequest request) {
        String question = Inputs.require(request.question(), "question");
        ChatClientResponse response = chat.prompt().user(question).call().chatClientResponse();
        return new AskReply(text(response), refused(response), sources(response));
    }

    /** The same answer as /api/ask, streamed: one "sources" event, then "token" events, then "done". */
    @GetMapping(path = "/api/ask/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    Flux<ServerSentEvent<Object>> stream(@RequestParam String q) {
        String question = Inputs.require(q, "q");
        Flux<ChatClientResponse> responses = chat.prompt().user(question).stream().chatClientResponse();
        return Flux.defer(() -> {
            AtomicBoolean sourcesSent = new AtomicBoolean(false);
            AtomicBoolean refused = new AtomicBoolean(false);
            return responses
                    .concatMapIterable(r -> {
                        List<ServerSentEvent<Object>> events = new ArrayList<>();
                        if (sourcesSent.compareAndSet(false, true)) {
                            events.add(event("sources", sources(r)));
                        }
                        refused.compareAndSet(false, refused(r));
                        String piece = text(r);
                        if (!piece.isEmpty()) {
                            events.add(event("token", Map.of("text", piece)));
                        }
                        return events;
                    })
                    .concatWith(Flux.defer(() -> Flux.just(event("done", Map.of("refused", refused.get())))))
                    .onErrorResume(e -> Flux.just(event("error", Map.of("error", "The answer failed: " + e.getMessage()))));
        });
    }

    private static ServerSentEvent<Object> event(String name, Object data) {
        return ServerSentEvent.<Object>builder(data).event(name).build();
    }

    private static String text(ChatClientResponse r) {
        ChatResponse cr = r.chatResponse();
        if (cr == null || cr.getResult() == null || cr.getResult().getOutput().getText() == null) {
            return "";
        }
        return cr.getResult().getOutput().getText();
    }

    private static boolean refused(ChatClientResponse r) {
        return Boolean.TRUE.equals(r.context().get(NoContextGuard.REFUSED));
    }

    /** The retrieved sections, best first, one entry per section. */
    @SuppressWarnings("unchecked")
    private static List<SearchController.Hit> sources(ChatClientResponse r) {
        Object docs = r.context().get(QuestionAnswerAdvisor.RETRIEVED_DOCUMENTS);
        if (!(docs instanceof List<?> list)) {
            return List.of();
        }
        Map<String, SearchController.Hit> unique = new LinkedHashMap<>();
        for (Document d : (List<Document>) list) {
            SearchController.Hit hit = SearchController.Hit.of(d);
            unique.putIfAbsent(hit.source() + "#" + hit.section(), hit);
        }
        return List.copyOf(unique.values());
    }
}
  1. text/event-stream. With a Flux of ServerSentEvent, Spring MVC sends each element as soon as it is emitted.line 56
  2. Like .content(), but every element keeps the advisor context: the first one already has the retrieved documents.line 59
  3. Nothing runs until Spring subscribes, and each subscription gets fresh flags.line 60
  4. True only the first time: the sources are sent once, before the first token.line 66
  5. JSON keeps leading spaces that plain SSE text would lose.line 72
  6. Deferred so refused is read after the last token, not when the stream is built.line 76
  7. A stream that fails halfway cannot change its HTTP status any more (200 was sent with the first event). An error event tells the client.line 77
src/test/java/dev/algorung/helpdesk/Milestone7Test.java
package dev.algorung.helpdesk;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
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;
import org.springframework.http.HttpStatus;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class Milestone7Test {
    static final FakeLlmServer FAKE = FakeLlmServer.start();
    static final String DATA = FakeLlmServer.freshDataDir();

    @DynamicPropertySource
    static void useTheFake(DynamicPropertyRegistry registry) {
        registry.add("spring.ai.openai.base-url", FAKE::baseUrl);
        registry.add("spring.ai.retry.max-attempts", () -> "1");
        registry.add("helpdesk.data-dir", () -> DATA);
    }

    @Autowired
    TestRestTemplate http;

    TestRestTemplate as(String user) {
        return http.withBasicAuth(user, user + "-pass");
    }

    record Event(String name, JsonNode data) {}

    /** Reads a whole SSE body: events are separated by a blank line, each has "event:" and "data:" lines. */
    List<Event> stream(String question) throws Exception {
        String body = as("ana").getForObject("/api/ask/stream?q=" + question, String.class);
        ObjectMapper json = new ObjectMapper();
        List<Event> events = new ArrayList<>();
        for (String block : body.split("\\n\\n")) {
            String name = null;
            StringBuilder data = new StringBuilder();
            for (String line : block.split("\\n")) {
                if (line.startsWith("event:")) {
                    name = line.substring(6).strip();
                } else if (line.startsWith("data:")) {
                    data.append(line.substring(5));
                }
            }
            if (name != null) {
                events.add(new Event(name, json.readTree(data.toString())));
            }
        }
        return events;
    }

    String tokens(List<Event> events) {
        StringBuilder text = new StringBuilder();
        events.stream().filter(e -> e.name().equals("token")).forEach(e -> text.append(e.data().path("text").asText()));
        return text.toString();
    }

    @Test
    void sourcesComeFirstThenTokensThenDone() throws Exception {
        List<Event> events = stream("What is the hotel limit in London");
        assertThat(events.get(0).name()).isEqualTo("sources");
        assertThat(events.get(0).data().get(0).path("source").asText()).isEqualTo("expenses.md");
        assertThat(events.subList(1, events.size() - 1)).isNotEmpty().allSatisfy(e -> assertThat(e.name()).isEqualTo("token"));
        Event done = events.get(events.size() - 1);
        assertThat(done.name()).isEqualTo("done");
        assertThat(done.data().path("refused").asBoolean()).isFalse();
    }

    @Test
    void tokensKeepTheirSpaces() throws Exception {
        String answer = tokens(stream("What is the hotel limit in London"));
        assertThat(answer).startsWith("echo: What is the hotel limit in London").contains("250 euros a night");
    }

    @Test
    void offTopicStreamsTheRefusalWithoutCallingTheModel() throws Exception {
        int before = FAKE.chatRequestCount();
        List<Event> events = stream("Who won the football World Cup in 2022");
        assertThat(events.get(0).name()).isEqualTo("sources");
        assertThat(events.get(0).data().size()).isZero();
        assertThat(tokens(events)).startsWith("I could not find that in the HR and IT docs.");
        assertThat(events.get(events.size() - 1).data().path("refused").asBoolean()).isTrue();
        assertThat(FAKE.chatRequestCount()).isEqualTo(before);
    }

    @Test
    void streamingNeedsALogin() {
        assertThat(http.getForEntity("/api/ask/stream?q=hotels", String.class).getStatusCode())
                .isEqualTo(HttpStatus.UNAUTHORIZED);
    }
}
  1. An SSE body is a list of events separated by a blank line.line 45
  2. The first event, before any token.line 71
  3. Joined back together, the tokens are the whole answer, spaces included.line 82
  4. Refused in the stream too, without a model call.line 93
Run
./mvnw test -Dtest=Milestone7Test

# restart the app; -N stops curl from buffering
curl -N -u ana:ana-pass "localhost:8080/api/ask/stream?q=What%20is%20the%20meal%20allowance%20on%20a%20work%20trip"
You should seeyour text will differ: the model writes it
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
event:sources
data:[{"source":"expenses.md","section":"Meals","score":0.78}]

event:token
data:{"text":"The"}

event:token
data:{"text":" meal"}

event:token
data:{"text":" allowance"}

event:token
data:{"text":" on"}
...
event:token
data:{"text":" expenses"}

event:token
data:{"text":"."}

event:done
data:{"refused":false}
Why this way? Streaming changes how the wait feels, not how long it is: the first words arrive in a second instead of the whole answer in five. The JSON event shapes are the same contract capstone 1 used between FastAPI and its chat page, so the same page works against this Java service.
Stuck on this milestone?
Everything arrives at once at the end
Use curl -N. Behind a proxy such as nginx, turn response buffering off for this path.
The words run together in the browser
You send bare text in data:. Send {"text": "..."} and append JSON.parse(e.data).text on the page.
The stream ends with an error event Stream processing failed
Something failed inside an advisor; the first Caused by: in the app log has the real reason (often Ollama not running).
event:sources has the right section, but the tokens say "I can't answer that question"
The 3B model, not your code. On a Mac, "What is the hotel limit in London" (Hotels, 0.726) got a refusal-like answer in 7 of 9 tries, while the meal question was right every time. The streamed and the plain /api/ask answer behave the same. A larger model (llama3.1:8b) or a more direct question helps; the sources show the retrieval worked.
8

Health, metrics and token usage

Actuator shows readiness (are the docs indexed?) and Micrometer metrics for every model call, token use, tool call and refusal, with details for admins only.

Exposure and access. Expose health and metrics over HTTP (management.endpoints.web.exposure.include). Health stays public but shows details only to ADMIN (management.endpoint.health.show-details=when-authorized and management.endpoint.health.roles=ADMIN); /actuator/metrics already needs ADMIN from milestone 1's rules.

Readiness. IngestHealthIndicator (a @Component implementing HealthIndicator; Spring names it ingest from the class name) is DOWN until the last ingest report has chunks, UP after, with the details status, files and chunks. A load balancer then sends no traffic to an instance that cannot answer yet.

Model calls and tokens are already measured. With Actuator on the classpath, Spring AI reports every model call as an observation: the timer gen_ai.client.operation and the counter gen_ai.client.token.usage with the tag gen_ai.token.type (input, output, total) plus the model name. You add nothing; you look. Also set spring.ai.openai.chat.options.stream-usage=true, so streamed answers report their tokens too (the server sends usage in the last chunk).

Your own counters, through an injected MeterRegistry: helpdesk.tool.calls with the tags tool and outcome (ok or rejected), counted in HelpdeskTools, and helpdesk.rag.refusals, counted in NoContextGuard. Tag by tool and outcome, never by user: every distinct tag value is a new time series in your monitoring, and thousands of users means thousands of series.

This is the Spring version of capstone 2's tracing and cost tracking: there you added OpenTelemetry spans and a cost per conversation by hand; here the framework emits the model metrics and you add the business ones.

Done when
  • ./mvnw test -Dtest=Milestone8Test passes (5 tests).
  • curl -s localhost:8080/actuator/health returns only {"status":"UP"}; curl -s -u ben:ben-pass localhost:8080/actuator/health also shows "ingest":{"status":"UP","details":{"status":"unchanged","files":5,"chunks":17}}.
  • After a few chats, curl -s -u ben:ben-pass "localhost:8080/actuator/metrics/gen_ai.client.token.usage?tag=gen_ai.token.type:output" shows the output tokens you have used, and the same URL as ana returns 403.
Hints
  1. meters.counter("helpdesk.tool.calls", "tool", tool, "outcome", ok ? "ok" : "rejected").increment(): name, then tag pairs. Micrometer reuses the counter with the same name and tags.
  2. Health.up().withDetail("chunks", n).build() or Health.down()....
  3. A metric that was never recorded does not exist yet: /actuator/metrics/gen_ai.client.token.usage answers 404 until the first model call.
Show the reference solution for milestone 8

Try it yourself first. This is one good way to do it, not the only one.

src/main/resources/application.properties 6 new or changed lines
# Larkspur Helpdesk: an internal HR and IT assistant.
spring.application.name=helpdesk

# Local models 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

# Demo users. Real apps sign in through SSO; never commit real passwords.
helpdesk.users.ana-password=ana-pass
helpdesk.users.ben-password=ben-pass

# Milestone 2: where the docs are read from, and where the index and its state are kept.
helpdesk.docs-dir=docs
helpdesk.data-dir=data

# Milestone 3: how many sections to retrieve, and the lowest similarity that counts as a match.
helpdesk.rag.top-k=3
helpdesk.rag.similarity-threshold=0.7

# Milestone 8: health is public, metrics need the ADMIN role (see SecurityConfig).
management.endpoints.web.exposure.include=health,metrics
management.endpoint.health.show-details=when-authorized
management.endpoint.health.roles=ADMIN
# Ask the server for token usage in the last chunk of a streamed answer too.
spring.ai.openai.chat.options.stream-usage=true
  1. Only what you need over HTTP. Other endpoints (env, beans, heapdump) can leak secrets.line 26
  2. Anonymous callers see UP or DOWN; ben sees which part is down and why.line 27
  3. Asks for token usage in streamed answers too, so /api/ask/stream shows up in gen_ai.client.token.usage.line 30
src/main/java/dev/algorung/helpdesk/IngestHealthIndicator.java
package dev.algorung.helpdesk;

import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

/** Shows up as "ingest" in /actuator/health: DOWN until the docs are in the vector store. */
@Component
public class IngestHealthIndicator implements HealthIndicator {
    private final Ingestor ingestor;

    IngestHealthIndicator(Ingestor ingestor) {
        this.ingestor = ingestor;
    }

    @Override
    public Health health() {
        Ingestor.Report report = ingestor.lastReport();
        Health.Builder health = report.chunks() > 0 ? Health.up() : Health.down();
        return health.withDetail("status", report.status())
                .withDetail("files", report.files())
                .withDetail("chunks", report.chunks())
                .build();
    }
}
  1. Spring Boot adds it to /actuator/health as ingest (the bean name without "HealthIndicator").line 9
  2. No chunks means no answers: the instance is not ready, even though the process runs.line 19
src/main/java/dev/algorung/helpdesk/HelpdeskTools.java 6 new or changed lines
package dev.algorung.helpdesk;

import io.micrometer.core.instrument.MeterRegistry;

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

/**
 * The model's only way to act. The user always comes from the ToolContext the server sets, never from
 * the model's arguments, so nobody can open tickets or read balances for someone else.
 */
@Component
public class HelpdeskTools {
    public static final String USER = "user";
    public static final String LOG = "log";

    private final TicketService tickets;
    private final LeaveService leave;
    private final MeterRegistry meters;

    HelpdeskTools(TicketService tickets, LeaveService leave, MeterRegistry meters) {
        this.tickets = tickets;
        this.leave = leave;
        this.meters = meters;
    }

    @Tool(description = "Open an IT support ticket for the signed-in employee. "
            + "Use it when something is broken or not working, or when they ask for a ticket.")
    public Ticket createItTicket(
            @ToolParam(description = "One of HARDWARE, SOFTWARE, ACCESS, NETWORK") String category,
            @ToolParam(description = "One short sentence that describes the problem") String summary,
            @ToolParam(description = "One of LOW, MEDIUM, HIGH. Use MEDIUM if unsure.", required = false) String priority,
            ToolContext context) {
        String user = user(context);
        try {
            Ticket ticket = tickets.create(user, new TicketDraft(category, priority, summary));
            record(context, "createItTicket", true, ticket.id());
            return ticket;
        } catch (IllegalArgumentException e) {
            record(context, "createItTicket", false, e.getMessage());
            throw e;
        }
    }

    @Tool(description = "How many leave days the signed-in employee has left. "
            + "leaveType is ANNUAL (this year's vacation) or CARRY_OVER (days kept from last year).")
    public LeaveBalance checkLeaveBalance(
            @ToolParam(description = "ANNUAL or CARRY_OVER", required = false) String leaveType,
            ToolContext context) {
        String user = user(context);
        try {
            LeaveBalance balance = leave.balance(user, leaveType);
            record(context, "checkLeaveBalance", true, balance.remainingDays() + " " + balance.leaveType() + " days left");
            return balance;
        } catch (IllegalArgumentException e) {
            record(context, "checkLeaveBalance", false, e.getMessage());
            throw e;
        }
    }

    private static String user(ToolContext context) {
        Object user = context.getContext().get(USER);
        if (!(user instanceof String name) || name.isBlank()) {
            throw new IllegalStateException("no signed-in user in the tool context");
        }
        return name;
    }

    private void record(ToolContext context, String tool, boolean ok, String result) {
        System.out.println("[tool] " + tool + " for " + context.getContext().get(USER) + ": " + result);
        if (context.getContext().get(LOG) instanceof ToolCallLog log) {
            if (ok) {
                log.ok(tool, result);
            } else {
                log.rejected(tool, result);
            }
        }
        meters.counter("helpdesk.tool.calls", "tool", tool, "outcome", ok ? "ok" : "rejected").increment();
    }
}
  1. The registry Actuator configured. In tests it is an in-memory one, so /actuator/metrics works there too.line 21
  2. Counted for every call, ok or rejected. A rising rejected count means the model keeps sending bad arguments: a prompt or model problem worth a look.line 80
src/main/java/dev/algorung/helpdesk/NoContextGuard.java 6 new or changed lines
package dev.algorung.helpdesk;

import java.util.List;

import io.micrometer.core.instrument.MeterRegistry;
import reactor.core.publisher.Flux;

import org.springframework.ai.chat.client.ChatClientRequest;
import org.springframework.ai.chat.client.ChatClientResponse;
import org.springframework.ai.chat.client.advisor.api.CallAdvisor;
import org.springframework.ai.chat.client.advisor.api.CallAdvisorChain;
import org.springframework.ai.chat.client.advisor.api.StreamAdvisor;
import org.springframework.ai.chat.client.advisor.api.StreamAdvisorChain;
import org.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.model.Generation;
import org.springframework.stereotype.Component;

/**
 * Runs after QuestionAnswerAdvisor. When retrieval found nothing above the threshold, it answers with a fixed
 * refusal and never calls the model, so a small model cannot fill the gap from its general knowledge.
 */
@Component
public class NoContextGuard implements CallAdvisor, StreamAdvisor {
    public static final String REFUSAL = "I could not find that in the HR and IT docs. "
            + "Try other words, or ask the People team or IT directly.";
    public static final String REFUSED = "helpdesk_refused";

    private final MeterRegistry meters;

    NoContextGuard(MeterRegistry meters) {
        this.meters = meters;
    }

    @Override
    public ChatClientResponse adviseCall(ChatClientRequest request, CallAdvisorChain chain) {
        return nothingFound(request) ? refusal(request) : chain.nextCall(request);
    }

    @Override
    public Flux<ChatClientResponse> adviseStream(ChatClientRequest request, StreamAdvisorChain chain) {
        return nothingFound(request) ? Flux.just(refusal(request)) : chain.nextStream(request);
    }

    private static boolean nothingFound(ChatClientRequest request) {
        return request.context().get(QuestionAnswerAdvisor.RETRIEVED_DOCUMENTS) instanceof List<?> docs && docs.isEmpty();
    }

    private ChatClientResponse refusal(ChatClientRequest request) {
        meters.counter("helpdesk.rag.refusals").increment();
        ChatResponse answer = new ChatResponse(List.of(new Generation(new AssistantMessage(REFUSAL))));
        return ChatClientResponse.builder()
                .chatResponse(answer)
                .context(request.context())
                .context(REFUSED, true)
                .build();
    }

    @Override
    public String getName() {
        return "NoContextGuard";
    }

    @Override
    public int getOrder() {
        return 100; // QuestionAnswerAdvisor has order 0: it runs first and puts the documents in the context
    }
}
  1. A Spring bean, so it gets the registry by constructor injection.line 32
  2. How often the docs had no answer. Read those questions: they are your list of missing docs.line 51
src/test/java/dev/algorung/helpdesk/Milestone8Test.java
package dev.algorung.helpdesk;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.List;
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;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class Milestone8Test {
    static final FakeLlmServer FAKE = FakeLlmServer.start();
    static final String DATA = FakeLlmServer.freshDataDir();

    @DynamicPropertySource
    static void useTheFake(DynamicPropertyRegistry registry) {
        registry.add("spring.ai.openai.base-url", FAKE::baseUrl);
        registry.add("spring.ai.retry.max-attempts", () -> "1");
        registry.add("helpdesk.data-dir", () -> DATA);
    }

    @Autowired
    TestRestTemplate http;

    TestRestTemplate as(String user) {
        return http.withBasicAuth(user, user + "-pass");
    }

    /** The value of the first measurement (COUNT for a counter or a timer) of one metric, as ben (ADMIN). */
    double metric(String nameAndTags) {
        ResponseEntity<Map> reply = as("ben").getForEntity("/actuator/metrics/" + nameAndTags, Map.class);
        assertThat(reply.getStatusCode()).as(nameAndTags).isEqualTo(HttpStatus.OK);
        List<Map<String, Object>> measurements = (List<Map<String, Object>>) reply.getBody().get("measurements");
        return ((Number) measurements.get(0).get("value")).doubleValue();
    }

    @Test
    void healthDetailsAreForAdminsOnly() {
        Map<String, Object> anonymous = http.getForObject("/actuator/health", Map.class);
        assertThat(anonymous).containsEntry("status", "UP").doesNotContainKey("components");
        Map<String, Object> admin = as("ben").getForObject("/actuator/health", Map.class);
        Map<String, Object> ingest = (Map<String, Object>) ((Map<String, Object>) admin.get("components")).get("ingest");
        assertThat(ingest).containsEntry("status", "UP");
        assertThat((Map<String, Object>) ingest.get("details")).containsEntry("chunks", 17);
    }

    @Test
    void metricsNeedTheAdminRole() {
        assertThat(as("ana").getForEntity("/actuator/metrics", String.class).getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
        assertThat(as("ben").getForEntity("/actuator/metrics", String.class).getStatusCode()).isEqualTo(HttpStatus.OK);
    }

    @Test
    void modelCallsAndTokenUsageAreRecorded() {
        as("ana").postForObject("/api/chat", Map.of("message", "Hello"), Map.class);
        assertThat(metric("gen_ai.client.operation")).isGreaterThanOrEqualTo(1);
        assertThat(metric("gen_ai.client.token.usage?tag=gen_ai.token.type:input")).isGreaterThanOrEqualTo(10);
        assertThat(metric("gen_ai.client.token.usage?tag=gen_ai.token.type:output")).isGreaterThanOrEqualTo(5);
    }

    @Test
    void toolCallsAreCountedByToolAndOutcome() {
        as("ana").postForObject("/api/chat", Map.of("message", "How many vacation days do I have left?"), Map.class);
        assertThat(metric("helpdesk.tool.calls?tag=tool:checkLeaveBalance&tag=outcome:ok")).isGreaterThanOrEqualTo(1);
    }

    @Test
    void refusalsAreCounted() {
        as("ana").postForObject("/api/ask", Map.of("question", "Who won the football World Cup in 2022?"), Map.class);
        assertThat(metric("helpdesk.rag.refusals")).isGreaterThanOrEqualTo(1);
    }
}
  1. Anonymous callers get the status only.line 47
  2. The readiness detail from your health indicator.line 51
  3. Spring AI's timer for model calls (chat and embeddings). Its first measurement is the number of calls.line 63
  4. The fake reports 10 input and 5 output tokens per chat call.line 64
  5. Filter one counter by its tags.line 71
Run
./mvnw test -Dtest=Milestone8Test

# restart the app, chat a little, then as the admin:
curl -s -u ben:ben-pass localhost:8080/actuator/health
curl -s -u ben:ben-pass "localhost:8080/actuator/metrics/gen_ai.client.token.usage?tag=gen_ai.token.type:output"
curl -s -u ben:ben-pass "localhost:8080/actuator/metrics/gen_ai.client.operation"
You should see
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
{"status":"UP","components":{"diskSpace":{"status":"UP","details":{...}},"ingest":{"status":"UP","details":{"status":"unchanged","files":5,"chunks":17}},"ping":{"status":"UP"},"ssl":{"status":"UP","details":{"validChains":[],"invalidChains":[]}}}}
{"name":"gen_ai.client.token.usage","description":"Measures number of input and output tokens used","measurements":[{"statistic":"COUNT","value":120.0}],"availableTags":[{"tag":"gen_ai.operation.name","values":["chat","embedding"]},{"tag":"gen_ai.response.model","values":["nomic-embed-text","llama3.2:3b"]},{"tag":"gen_ai.request.model","values":["nomic-embed-text","llama3.2:3b"]},{"tag":"gen_ai.system","values":["openai"]}]}
{"name":"gen_ai.client.operation","baseUnit":"seconds","measurements":[{"statistic":"COUNT","value":8.0},{"statistic":"TOTAL_TIME","value":3.5491552079999997},{"statistic":"MAX","value":1.112747}],"availableTags":[{"tag":"gen_ai.operation.name","values":["chat","embedding"]},{"tag":"gen_ai.response.model","values":["nomic-embed-text","llama3.2:3b"]},{"tag":"gen_ai.request.model","values":["nomic-embed-text","llama3.2:3b"]},{"tag":"error","values":["none"]},{"tag":"gen_ai.system","values":["openai"]}]}
Why this way? Token counts are your bill on a hosted API, and latency per call is your user experience. With these two metrics and the refusal and tool counters you can answer "what does the assistant cost per day, how slow is it, and where does it fail" without reading logs. In production you send them to Prometheus or an OpenTelemetry backend by adding one registry dependency.
Stuck on this milestone?
/actuator/metrics/gen_ai.client.token.usage returns 404
No model call has been made since the app started; send one chat first. If it still 404s, check management.endpoints.web.exposure.include lists metrics.
Health is DOWN right after startup
Ingestion has not finished, or found no chunks. Ask as ben: the ingest details say which.
Every model call logs WARN ... OpenAiChatModel : Removing streamOptions from the request as it is not a streaming request!
Harmless. It comes from spring.ai.openai.chat.options.stream-usage=true: Spring AI drops the stream option from calls that do not stream. Streamed answers keep it and report their tokens.
9

pgvector with Docker Compose, and the app in a container

The same app stores its vectors in PostgreSQL with pgvector under a `pgvector` profile, the default profile still needs no database, and a Dockerfile ships it.

pom.xml: add spring-ai-starter-vector-store-pgvector. It auto-configures a PgVectorStore bean, the JDBC driver and a connection pool, so two things must now be switched off by default, or every test and every plain ./mvnw spring-boot:run would look for a database:

  • spring.ai.vectorstore.type=simple in application.properties. Spring AI creates the pgvector store only when this property is pgvector (or missing). Your SimpleVectorStore bean gets @ConditionalOnProperty(name = "spring.ai.vectorstore.type", havingValue = "simple", matchIfMissing = true), so exactly one of the two stores exists.
  • spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration: no DataSource without a database.

application-pgvector.properties, read only when the profile pgvector is active, and stronger than application.properties: spring.ai.vectorstore.type=pgvector, an empty spring.autoconfigure.exclude= (a list property from a stronger file replaces the weaker one completely), the datasource URL jdbc:postgresql://localhost:5432/helpdesk with user and password helpdesk, and for the store initialize-schema=true, dimensions=768 (what nomic-embed-text returns), distance-type=COSINE_DISTANCE and index-type=HNSW.

Nothing else changes. Ingestor, QuestionAnswerAdvisor and /api/search only know the VectorStore interface. The deterministic UUID ids from milestone 2 make add an upsert in PostgreSQL, and the "is the store empty?" check re-ingests into a brand-new database even when data/ingest-state.json says nothing changed.

compose.yaml: a db service from the image pgvector/pgvector:pg17 (PostgreSQL 17 with the extension), database, user and password helpdesk, port 5432, a named volume and a pg_isready health check; and an app service under the Compose profile app (so docker compose up -d starts only the database), built from the Dockerfile, with SPRING_PROFILES_ACTIVE=pgvector, the datasource URL pointing at db, and the model URL at http://host.docker.internal:11434, which is your machine as seen from the container (extra_hosts makes that name work on Linux too).

Dockerfile, two stages: build with eclipse-temurin:21-jdk and ./mvnw package -DskipTests (dependencies first, in their own layer, so code changes do not download them again), then run target/helpdesk-0.1.0.jar on eclipse-temurin:21-jre as a non-root user, with docs/ copied next to it and a writable /app/data. Plus a .dockerignore that keeps target/ and data/ out of the build.

Done when
  • ./mvnw test -Dtest=Milestone9Test passes (2 tests), and the whole suite ./mvnw test passes (42 tests) without Docker running.
  • docker compose up -d, then ./mvnw spring-boot:run -Dspring-boot.run.profiles=pgvector logs [ingest] indexed: 17 chunks from 5 files into PgVectorStore, and docker compose exec db psql -U helpdesk -d helpdesk -c "select count(*) from vector_store" prints 17.
  • docker compose --profile app up --build -d starts the app in a container; curl -s localhost:8080/actuator/health returns {"status":"UP"} and /api/ask answers as before.
Hints
  1. A profile file is application-<profile>.properties next to application.properties. Activate it with -Dspring-boot.run.profiles=pgvector, or SPRING_PROFILES_ACTIVE=pgvector in the environment.
  2. Environment variables override properties: upper case, dots become underscores, dashes are dropped. spring.ai.openai.base-url is SPRING_AI_OPENAI_BASEURL.
  3. Stop the app running on your machine before docker compose --profile app up: both want port 8080.
Show the reference solution for milestone 9

Try it yourself first. This is one good way to do it, not the only one.

pom.xml 1 new line
<?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>helpdesk</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.boot</groupId>
      <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-actuator</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.ai</groupId>
      <artifactId>spring-ai-starter-vector-store-pgvector</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. New: PgVectorStore, the PostgreSQL driver, HikariCP and their auto-configuration.line 50
src/main/resources/application.properties 3 new or changed lines
# Larkspur Helpdesk: an internal HR and IT assistant.
spring.application.name=helpdesk

# Local models 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

# Demo users. Real apps sign in through SSO; never commit real passwords.
helpdesk.users.ana-password=ana-pass
helpdesk.users.ben-password=ben-pass

# Milestone 2: where the docs are read from, and where the index and its state are kept.
helpdesk.docs-dir=docs
helpdesk.data-dir=data

# Milestone 3: how many sections to retrieve, and the lowest similarity that counts as a match.
helpdesk.rag.top-k=3
helpdesk.rag.similarity-threshold=0.7

# Milestone 8: health is public, metrics need the ADMIN role (see SecurityConfig).
management.endpoints.web.exposure.include=health,metrics
management.endpoint.health.show-details=when-authorized
management.endpoint.health.roles=ADMIN
# Ask the server for token usage in the last chunk of a streamed answer too.
spring.ai.openai.chat.options.stream-usage=true

# Milestone 9: SimpleVectorStore and no database by default; the pgvector profile switches both on.
spring.ai.vectorstore.type=simple
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
  1. Any value but pgvector keeps Spring AI from creating the pgvector store. simple is our own name, read by VectorStoreConfig.line 33
  2. No database connection in the default profile: tests and a plain spring-boot:run keep working with nothing but Ollama.line 34
src/main/resources/application-pgvector.properties
# The pgvector profile: ./mvnw spring-boot:run -Dspring-boot.run.profiles=pgvector
# Values here win over application.properties.
spring.ai.vectorstore.type=pgvector
spring.autoconfigure.exclude=

spring.datasource.url=jdbc:postgresql://localhost:5432/helpdesk
spring.datasource.username=helpdesk
spring.datasource.password=helpdesk

spring.ai.vectorstore.pgvector.initialize-schema=true
spring.ai.vectorstore.pgvector.dimensions=768
spring.ai.vectorstore.pgvector.distance-type=COSINE_DISTANCE
spring.ai.vectorstore.pgvector.index-type=HNSW
  1. Spring AI's PgVectorStore is created, and VectorStoreConfig skips the simple one.line 3
  2. Empty on purpose: it replaces the default profile's exclusion, so the DataSource is created again.line 4
  3. Creates the vector extension and the vector_store table on first start. Off by default, because production schemas belong to migrations.line 10
  4. The table's vector size. It must match the embedding model: switching to a model with 1024 dimensions needs a new table.line 11
  5. Scores are 1 - distance, the same cosine similarity SimpleVectorStore reports, so your 0.7 threshold means the same thing.line 12
  6. An approximate nearest-neighbour index: fast search over millions of rows. With 17 rows it changes nothing, but it is what you want in production.line 13
src/main/java/dev/algorung/helpdesk/VectorStoreConfig.java 3 new or changed lines
package dev.algorung.helpdesk;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class VectorStoreConfig {

    /** The default store: in memory, saved to data/vectors.json. The pgvector profile replaces it. */
    @Bean
    @ConditionalOnProperty(name = "spring.ai.vectorstore.type", havingValue = "simple", matchIfMissing = true)
    SimpleVectorStore simpleVectorStore(EmbeddingModel embeddingModel,
                                        @Value("${helpdesk.data-dir}") Path dataDir) throws IOException {
        SimpleVectorStore store = SimpleVectorStore.builder(embeddingModel).build();
        Files.createDirectories(dataDir);
        File file = dataDir.resolve("vectors.json").toFile();
        if (file.exists()) {
            store.load(file);
        }
        return store;
    }
}
  1. This bean exists only when the type is simple (or not set at all, as in milestones 2 to 8).line 20
compose.yaml
services:
  db:
    image: pgvector/pgvector:pg17
    environment:
      POSTGRES_DB: helpdesk
      POSTGRES_USER: helpdesk
      POSTGRES_PASSWORD: helpdesk
    ports:
      - "5432:5432"
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U helpdesk -d helpdesk"]
      interval: 5s
      retries: 10

  app:
    profiles: ["app"]
    build: .
    depends_on:
      db:
        condition: service_healthy
    environment:
      SPRING_PROFILES_ACTIVE: pgvector
      SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/helpdesk
      SPRING_AI_OPENAI_BASEURL: http://host.docker.internal:11434
      HELPDESK_USERS_ANAPASSWORD: ${ANA_PASSWORD:-ana-pass}
      HELPDESK_USERS_BENPASSWORD: ${BEN_PASSWORD:-ben-pass}
    extra_hosts:
      - "host.docker.internal:host-gateway"
    ports:
      - "8080:8080"

volumes:
  pgdata:
  1. The official PostgreSQL image with the pgvector extension built in.line 3
  2. A named volume: the vectors survive docker compose down. down -v deletes them.line 11
  3. The app service waits for this check, not just for the container to exist.line 13
  4. Started only with --profile app. Plain docker compose up -d starts the database alone, for running the app with ./mvnw.line 18
  5. Inside Compose, the database host is the service name db, not localhost.line 25
  6. Ollama keeps running on your machine (it uses your GPU there). SPRING_AI_OPENAI_BASEURL is spring.ai.openai.base-url as an environment variable.line 26
  7. Override the demo passwords from your shell: ANA_PASSWORD=... docker compose --profile app up -d.line 27
  8. Makes host.docker.internal work on Linux; Docker Desktop has it already.line 30
Dockerfile
# Stage 1: build the jar with the Maven wrapper (needs a JDK).
FROM eclipse-temurin:21-jdk AS build
WORKDIR /src
COPY mvnw pom.xml ./
COPY .mvn/ .mvn/
RUN chmod +x mvnw && ./mvnw -q dependency:go-offline
COPY src/ src/
RUN ./mvnw -q package -DskipTests

# Stage 2: run it on a smaller image with only a JRE, as a user without root rights.
FROM eclipse-temurin:21-jre
WORKDIR /app
RUN useradd --system --uid 10001 helpdesk && mkdir -p /app/data && chown helpdesk /app/data
COPY --from=build /src/target/helpdesk-0.1.0.jar app.jar
COPY docs/ docs/
USER helpdesk
EXPOSE 8080
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "app.jar"]
  1. Stage one has the JDK and Maven. None of it ends up in the final image.line 2
  2. Downloads dependencies in their own layer. Docker reuses it until pom.xml changes, so a code change rebuilds in seconds.line 6
  3. Stage two: only a Java runtime, a much smaller image to ship.line 11
  4. Never run a web app as root in a container.line 13
  5. The docs folder sits next to the jar; helpdesk.docs-dir=docs is relative to /app.line 15
  6. Size the Java heap from the container's memory limit, not the host's.line 18
.dockerignore
target/
data/
.git/
.idea/
.vscode/
*.iml
  1. Built inside the image; a local target/ would only slow the build down.line 1
README.md
# Larkspur Helpdesk (Spring AI capstone)

An internal HR and IT assistant: answers policy questions from the docs with sources, opens IT tickets and
checks leave balances with tools, remembers each user's conversation, streams answers over SSE, and reports
health and token usage through Actuator.

    ollama pull llama3.2:3b
    ollama pull nomic-embed-text
    mvn -N wrapper:wrapper -Dmaven=3.9.11      # once, creates ./mvnw
    ./mvnw test                                 # every milestone's tests, against a fake model server
    ./mvnw spring-boot:run                      # http://localhost:8080, users ana / ana-pass and ben / ben-pass

With pgvector instead of the file-based store:

    docker compose up -d                        # PostgreSQL with pgvector on port 5432
    ./mvnw spring-boot:run -Dspring-boot.run.profiles=pgvector

Everything in Docker (the app reaches Ollama on your machine):

    docker compose --profile app up --build -d

Endpoints: GET /api/me, POST /api/chat, DELETE /api/chat/memory, POST /api/ask, GET /api/ask/stream?q=,
GET /api/search?q=, POST /api/tickets/from-text, GET /api/tickets, POST /api/admin/reindex,
GET /actuator/health, GET /actuator/metrics/{name}.
  1. The whole suite, every milestone, against the fake.line 10
src/test/java/dev/algorung/helpdesk/Milestone9Test.java
package dev.algorung.helpdesk;

import static org.assertj.core.api.Assertions.assertThat;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.sql.DataSource;

import org.junit.jupiter.api.Test;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.ClassPathResource;
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 Milestone9Test {
    static final FakeLlmServer FAKE = FakeLlmServer.start();
    static final String DATA = FakeLlmServer.freshDataDir();

    @DynamicPropertySource
    static void useTheFake(DynamicPropertyRegistry registry) {
        registry.add("spring.ai.openai.base-url", FAKE::baseUrl);
        registry.add("spring.ai.retry.max-attempts", () -> "1");
        registry.add("helpdesk.data-dir", () -> DATA);
    }

    @Autowired
    TestRestTemplate http;

    TestRestTemplate as(String user) {
        return http.withBasicAuth(user, user + "-pass");
    }

    @Autowired
    ApplicationContext context;

    @Test
    void theDefaultProfileUsesTheFileStoreAndNoDatabase() {
        assertThat(context.getBean(VectorStore.class)).isInstanceOf(SimpleVectorStore.class);
        assertThat(context.getBeanNamesForType(DataSource.class)).isEmpty();
    }

    @Test
    void thePgvectorProfileSwitchesTheStoreAndMatchesTheEmbeddingModel() throws IOException {
        Properties pg = new Properties();
        try (InputStream in = new ClassPathResource("application-pgvector.properties").getInputStream()) {
            pg.load(in);
        }
        assertThat(pg.getProperty("spring.ai.vectorstore.type")).isEqualTo("pgvector");
        assertThat(pg.getProperty("spring.ai.vectorstore.pgvector.dimensions")).isEqualTo("768");
        assertThat(pg.getProperty("spring.ai.vectorstore.pgvector.initialize-schema")).isEqualTo("true");
        assertThat(pg.getProperty("spring.datasource.url")).startsWith("jdbc:postgresql://");
    }
}
  1. With the pgvector starter on the classpath, the default profile still uses the file-based store.line 46
  2. And no database: the exclusion works, so ./mvnw test never needs Docker.line 47
  3. A wrong dimension only fails at the first insert, at runtime. Checking the file catches it in the build.line 57
Run
./mvnw test -Dtest=Milestone9Test
./mvnw test

# pgvector, with the app on your machine
docker compose up -d
./mvnw spring-boot:run -Dspring-boot.run.profiles=pgvector
docker compose exec db psql -U helpdesk -d helpdesk -c "select count(*) from vector_store"

# everything in Docker (stop the app above first)
docker compose --profile app up --build -d
curl -s localhost:8080/actuator/health
curl -s -u ana:ana-pass localhost:8080/api/ask -H "Content-Type: application/json" -d '{"question": "How much is the home office budget for new joiners?"}'
You should seeyour text will differ: the model writes it
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
...
[INFO] Tests run: 42, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
...
[ingest] indexed: 17 chunks from 5 files into PgVectorStore
 count 
-------
    17
(1 row)
...
{"status":"UP"}
{"answer":"The home office budget for new joiners is 1,000 euros, which covers a desk, chair, and monitor. The internet cost at home (40 euros per month) should be claimed as an expense separately.","refused":false,"sources":[{"source":"expenses.md","section":"Home office budget","score":0.799}]}
Why this way? One interface, two stores, chosen by configuration: the same move lab 6 made by hand in Python. The default profile stays light on purpose, so tests and new teammates need nothing but a JDK, and the database only matters where it is used. Ingestion at startup is fine for 17 sections; with real document volumes, move it to a separate job that writes to the same database while the service only reads.
Stuck on this milestone?
Default profile: Failed to configure a DataSource: 'url' attribute is not specified
The pgvector starter brought JDBC, and the exclusion is missing or misspelled. Check spring.autoconfigure.exclude in application.properties.
pgvector profile: two beans of type VectorStore
VectorStoreConfig still creates the SimpleVectorStore. Add the @ConditionalOnProperty from the solution.
expected 768 dimensions, not 1536 (or another number) on insert
The table was created for another size. Set dimensions to what your embedding model returns, then drop the table (docker compose exec db psql -U helpdesk -d helpdesk -c "drop table vector_store") and start again.
The container logs Connection refused for host.docker.internal:11434
Ollama listens only on 127.0.0.1 on Linux. Start it with OLLAMA_HOST=0.0.0.0 ollama serve, or run Ollama in Compose as well.
Search finds nothing after docker compose down -v
The volume and its vectors are gone. Restart the app: the empty-store check sees it and ingests again.
The image build prints useradd warning: helpdesk's uid 10001 is greater than SYS_UID_MAX 999
Harmless. A system user normally gets a uid below 1000; 10001 is on purpose, so it never matches a user on your machine. docker compose exec app id shows uid=10001(helpdesk).
"Can I expense my home internet?" is refused, although expenses.md answers it
Its best section scores 0.586 with nomic-embed-text, in pgvector exactly as in SimpleVectorStore, which is below the 0.7 threshold. Ask with the words of the docs ("How much is the home office budget for new joiners?" scores 0.799), or lower the threshold after measuring, as in milestone 3.

Check it works

Two checks. All 42 tests pass with no model and no database running. Then, with Ollama running and the app started, one question goes through RAG, one through a tool, and one is refused. Ask a few questions of your own too, as both users, and watch the [tool] and [ingest] lines in the log. The three answers below are examples: your model words them differently, and the scores depend on your embeddings.

Test
./mvnw test
./mvnw spring-boot:run   # in terminal 1, then in terminal 2:
curl -s -u ana:ana-pass localhost:8080/api/ask -H "Content-Type: application/json" -d '{"question": "What is the meal allowance on a work trip?"}'
curl -s -u ben:ben-pass localhost:8080/api/chat -H "Content-Type: application/json" -d '{"message": "My VPN is not working, please open a ticket."}'
curl -s -u ana:ana-pass localhost:8080/api/ask -H "Content-Type: application/json" -d '{"question": "What is the capital of Australia?"}'
You should see
[INFO] Tests run: 42, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
{"answer":"The meal allowance on a work trip is up to 60 euros per day, excluding alcohol. Employees should keep every meal receipt as proof of expenses. This policy applies to all work-related trips.","refused":false,"sources":[{"source":"expenses.md","section":"Meals","score":0.777}]}
{"user":"ben","answer":"The VPN ticket has been created. I've assigned it the ID IT-1001 and you'll receive updates on its status via email. In the meantime, you can try restarting your VPN client or contacting our IT team for assistance.","actions":[{"tool":"createItTicket","ok":true,"result":"IT-1001"}]}
{"answer":"I could not find that in the HR and IT docs. Try other words, or ask the People team or IT directly.","refused":true,"sources":[]}

Review rubric

Review your project the way a senior engineer or an interviewer would. Aim for the right column on every row.

AreaWorksProduction-ready
Security and identityEndpoints need a login.Roles separate admin endpoints, the user always comes from the security context (memory ids, tool context, tickets), health is public without details, and a test proves one user cannot see or act for another.
Ingestion and the indexThe docs are embedded at every startup.Sections with stable ids and metadata, a fingerprint that skips unchanged docs, a check that the store is really filled, deletes of removed sections, and a forced reindex for admins.
Grounded answersThe prompt says "answer from the context".A threshold chosen from measured scores, a guard that refuses before any model call, sources returned with every answer, and a test that a below-threshold section never reaches the prompt.
Tools that actTwo @Tool methods the model can call.User from the tool context only, allow-lists and limits in services shared with other endpoints, errors returned to the model, a server-side log as the only source of "what was done", and one nudge for the small-model failure modes.
Structured output.entity() maps the reply to a record.The same validation as the tool, one retry that names the problems, a 422 with reasons when it still fails, and only JSON errors caught (connection errors still become 503).
Streaming and API designAn endpoint streams text.Named SSE events with JSON data (sources first, done or error last), refusals streamed without a model call, input limits, and the same contract as the non-streaming endpoint.
OperationsThe app runs with ./mvnw spring-boot:run.Readiness that reflects the index, token and latency metrics per model, business counters without user tags, a default profile with no database, pgvector by profile, and a small non-root Docker image.

Stretch goals

  • Memory that survives a restart: add spring-ai-starter-model-chat-memory-repository-jdbc and use the pgvector profile's PostgreSQL for chat memory too. The advisor code does not change. Add several conversations per user with ids like ana:2, and check in code that the prefix is the signed-in user.
  • One endpoint for everything: route each /api/chat message either to the RAG client or to the tool client (a cheap classifier call, or keywords first), and measure how often the route is wrong on 20 sample messages.
  • Access control on documents: add a groups metadata field (for example managers for a pay-bands page) and pass a filter expression with QuestionAnswerAdvisor.FILTER_EXPRESSION built from the user's roles, so retrieval never even returns a section the user may not read. Write the test first.
  • A confirmation step for tickets: make createItTicket return a draft with a short-lived id, and add POST /api/tickets/{draftId}/confirm. Compare it with capstone 2's human approval for refunds: which actions deserve a confirmation, and which do not?
  • Evals in CI: 15 labelled questions (5 that must be refused, 5 that need a tool), run against a real model on a schedule, with refusal accuracy, tool accuracy and p95 latency in a report. Capstone 1's eval gate shows the pattern.

Troubleshooting

./mvnw test passes, but a real question is refused

The fake embeddings and real ones score differently. Calibrate helpdesk.rag.similarity-threshold with /api/search against Ollama, as in milestone 3. Real nomic-embed-text scores are bunched between about 0.45 and 0.8, and a short or vague question can score below 0.7 even when the docs answer it: try more specific words.

A test class fails to compile with cannot find symbol for a class you have not written yet

You copied a test file from a later milestone. Maven compiles every test file before it runs any test, so keep only the test files of the milestones you have done.

Answers take 20 seconds or more

The model runs on the CPU. /api/chat can make up to four model calls (answer, after the tool, nudge, after the tool again) and /api/ask sends three sections. Lower helpdesk.rag.top-k to 2, use llama3.2:1b for experiments, and use streaming for anything a person waits for.

Every request returns 401 although the password is right

Check for a typo in helpdesk.users.*-password, and that curl sends -u ana:ana-pass (no spaces). In Docker, the passwords come from ANA_PASSWORD and BEN_PASSWORD if set.

model "nomic-embed-text" not found at startup

Pull it: ollama pull nomic-embed-text. Startup embeds the docs, so a missing embedding model stops the app before it serves anything.

Old answers after you edited a doc

The fingerprint changes when a file changes, so a restart re-indexes. Without a restart, call POST /api/admin/reindex as ben.

What changes in production

  • Real identity, not demo users. Swap basic auth for your company's SSO (spring-boot-starter-oauth2-resource-server with JWTs). The rest of the code only reads the principal's name and roles, so nothing else changes.
  • Ingest offline. A separate job (or a CI step) splits and embeds the docs into pgvector when they change; the service only reads. Startup ingestion is fine for 17 sections and wrong for 17,000 pages.
  • Cap every request. Input size (done), a rate limit per user on /api/chat and /api/ask, a timeout on the whole request, and a limit on concurrent model calls. Tool rounds and nudges multiply the calls per request.
  • Treat docs and model output as untrusted. A doc can contain "ignore your rules"; a model can invent tool arguments. Allow-lists and the security context decide what happens, never the text. Log questions that end in refusals or rejected tool calls: they are your next docs and your next eval cases.
  • Watch cost and quality, not just uptime. Alert on gen_ai.client.token.usage per model, p95 of gen_ai.client.operation, helpdesk.rag.refusals and rejected tool calls. A sudden change in any of them usually means a prompt, model or docs change.

Interview angle

“Walk me through the internal assistant you built in Spring AI. How do you keep it from doing the wrong thing?”

It is a Spring Boot 3.5 service on Spring AI 1.1 for HR and IT questions and actions. At startup it splits a docs folder into sections with stable UUID ids, fingerprints the folder so unchanged docs are not embedded again, and stores the vectors in a SimpleVectorStore saved to a file, or in pgvector under a profile; the code only sees the VectorStore interface. Policy questions go through QuestionAnswerAdvisor with a threshold I chose from measured scores, because real embedding scores are bunched between about 0.45 and 0.8; a guard advisor refuses before any model call when nothing passes it, and every answer returns its sources. Actions are two @Tool methods; the user comes from Spring Security through the tool context, never from the model, and allow-lists and limits live in services that the structured-output endpoint uses too. Small models skip tools or claim actions they never took, so a server-side log is the only source of "what was done", a missed tool call gets one nudge, and a claimed but unlogged action is never shown. Memory is per user, the answer streams as typed SSE events, and Actuator shows readiness plus token and latency metrics from Spring AI's observations. 42 tests run the whole app against a fake OpenAI-compatible server, so CI needs no model. The trade-offs I would name: the nudge costs an extra call, the threshold has to be recalibrated per embedding model, and startup ingestion does not scale, which is why production ingests in a separate job.

Clean up

Stop the app with Ctrl+C and the containers with docker compose --profile app down (add -v to delete the database volume too). data/ can always be rebuilt from docs/. Keep the models if you go on to the next capstone.

Run
docker compose --profile app down -v
rm -rf data target

Practice

No model needed: these run in your browser and check your answer.

When to nudge

Write the check from milestone 5 in Python. should_nudge(message, answer, tools_called) returns True when no tool was called and either the answer contains a tool call written as text ("name": "create_ticket" or "name": "check_leave", with any spaces around the colon) or the message asks for an action (it contains broken, not working, ticket or days left, ignoring case) and does not start with how do, how can, what is or where (ignoring case). Otherwise return False.

Exercise
import re


def should_nudge(message, answer, tools_called):
    # tools_called: how many tools ran during this request
    return False


print(should_nudge("My laptop is broken", "What priority should it have?", 0))
Hint

Return `False` first when `tools_called > 0`. Then `re.search(r'"name"\s*:\s*"(create_ticket|check_leave)"', answer)`. For the action words, lower-case the message once and use `any(w in m for w in [...])`, and `m.startswith((...))` for the process questions.

Choose the threshold from your measurements

You ran /api/search for questions the docs answer and for questions they do not, and wrote down the top score of each. Write choose_threshold(good, off_topic): if every good score is higher than every off-topic score, return the point halfway between the lowest good score and the highest off-topic score, rounded to 2 decimals. If the two groups overlap (or touch), return None: no threshold separates them, and you need better retrieval, not a different number.

Exercise
def choose_threshold(good, off_topic):
    return 0.7


print(choose_threshold([0.78, 0.74, 0.81], [0.55, 0.61, 0.52]))
Hint

`low_good = min(good)`, `high_off = max(off_topic)`. If `low_good <= high_off` return `None`, else `round((low_good + high_off) / 2, 2)`.

The full project

The full reference solution, as it is after the last milestone. Build your own first, then compare.

Download Java project (.zip)