In Part 3 you built an /ask endpoint that returns a string. A string is fine for a chat box. It is a poor fit for code that has to act on the answer.
By the end of this part you will have four things. A /classify endpoint that returns a validated Java record. A safe failure path for when the model returns something wrong. An /ask/stream endpoint that sends the answer to the browser token by token. And a test suite that needs no model.
You need the Part 3 project, Java 17 or newer, and Ollama or a hosted model.
Why typed answers
Suppose the model writes a support ticket as text. You want the category. The quick fix is a regex.
private static final Pattern CATEGORY = Pattern.compile("category:\\s*(\\w+)");
private String categoryOf(String reply) {
Matcher m = CATEGORY.matcher(reply);
return m.find() ? m.group(1) : null;
}
It works for one wording and breaks for the rest. This test passes, and each isNull is a bug waiting in production:
assertThat(categoryOf("category: BILLING")).isEqualTo("BILLING");
assertThat(categoryOf("Category: BILLING")).isNull();
assertThat(categoryOf("The category is BILLING")).isNull();
assertThat(categoryOf("category: \"BILLING\"")).isNull();
Java is good at types. So we ask the model for a type, and we let the compiler and a validator do the checking.
Ask for a record
We start with the shape we want back. Two enums and a short summary:
record Ticket(
@NotNull Category category,
@NotNull Priority priority,
@NotBlank @Size(max = 200) String summary) {
enum Category {
BILLING("charges, invoices and refunds"),
BUG("something in the product is broken"),
ACCOUNT("login, password or profile problems"),
QUESTION("a how-to or general question");
private final String meaning;
Category(String meaning) {
this.meaning = meaning;
}
static String forPrompt() {
return Arrays.stream(values())
.map(c -> c.name() + " (" + c.meaning + ")")
.collect(Collectors.joining(", "));
}
}
enum Priority { LOW, MEDIUM, HIGH }
}
The annotations are Bean Validation rules. We use them in a minute. Add spring-boot-starter-validation to your pom.xml first. It is a Spring Boot starter, so no version is needed.
Now the call. This is the part that changes from Part 3:
ticket = chat.prompt()
.system(CLASSIFY_SYSTEM)
.user(text)
.options(ChatOptions.builder().temperature(0.0))
.call()
.entity(Ticket.class);
entity(Ticket.class) replaces content(). According to the Spring AI structured output page, three things happen behind it. A JSON schema is made from your record. The schema is added to the prompt. The model's reply is parsed back into your record.
We checked that on the wire. A test points the app at a fake Ollama server and records the request. Trimmed, and with the empty tools list left out, it looks like this:
{
"model": "test-model",
"messages": [
{ "role": "system", "content": "You sort customer messages into support tickets.\ncategory is one of: BILLING (charges, ..." },
{ "role": "user", "content": "I was charged twice.\r\nYour response should be in JSON format.\nDo not include any explanations, ..." }
],
"stream": false,
"options": { "temperature": 0.0 }
}
The format instructions ride along at the end of the user message. Here is what Spring AI appends for Ticket:
Here is the JSON Schema instance your output must adhere to:
{
"type" : "object",
"properties" : {
"category" : { "type" : "string", "enum" : [ "BILLING", "BUG", "ACCOUNT", "QUESTION" ] },
"priority" : { "type" : "string", "enum" : [ "LOW", "MEDIUM", "HIGH" ] },
"summary" : { "type" : "string" }
},
"required" : [ "category", "priority", "summary" ],
"additionalProperties" : false
}
The block above is shortened. The full text is printed by new BeanOutputConverter<>(Ticket.class).getFormat().
The system prompt comes from the enum, so the prompt and the code cannot drift apart:
private static final String CLASSIFY_SYSTEM = """
You sort customer messages into support tickets.
category is one of: %s.
priority is LOW, MEDIUM or HIGH.
summary is one sentence of at most 200 characters.
""".formatted(Ticket.Category.forPrompt());
The endpoint takes the text in a POST body. A GET would put customer text in the URL, and URLs end up in logs.
record TicketRequest(@NotBlank @Size(max = 2000) String text) { }
@PostMapping("/classify")
Ticket classify(@Valid @RequestBody TicketRequest request) {
return answer(() -> assistant.classify(request.text()));
}
Run it:
curl -X POST http://localhost:8080/classify \
-H "Content-Type: application/json" \
-d '{"text":"I was charged twice for my order #1234 and the checkout page showed an error."}'
In our test run (Spring AI 2.0.2, 2026-11-11, model llama3.2:3b) the reply was:
{"category":"BILLING","priority":"MEDIUM","summary":"Duplicate charge for order #1234"}
You get a Ticket, not a string. Your code can call ticket.category() and switch on it.
The format is a request, not a guarantee
The Spring AI docs say it plainly: the model is asked for JSON that matches the schema, not forced to produce it. When it does not comply, you see one of four things.
| What the model did | What happens |
|---|---|
| Wrote text around the JSON | The parser throws StreamReadException |
| Used a value outside the enum | The parser throws InvalidFormatException |
| Stopped early or sent nothing | The parser throws UnexpectedEndOfInputException or MismatchedInputException |
| Left a field out | Nothing throws. The field is null |
The last row is the dangerous one. We confirmed each row with sample text in TicketParsingTest, no model involved. For example:
@Test
void aMissingFieldDoesNotFailParsing() {
// Parsing alone lets this through. Bean Validation is what catches it.
var ticket = converter.convert("{\"category\":\"BUG\",\"priority\":\"HIGH\"}");
assertThat(ticket.summary()).isNull();
}
In Spring Boot 4 the parser is Jackson 3, so these exceptions live under tools.jackson. They all extend JacksonException, so one catch covers the parser rows. Validation covers the rest:
void check(Ticket ticket) {
Set<ConstraintViolation<Ticket>> problems = validator.validate(ticket);
if (!problems.isEmpty()) {
String fields = problems.stream()
.map(v -> v.getPropertyPath().toString())
.sorted()
.collect(Collectors.joining(", "));
throw new ModelOutputException("ticket breaks its rules, fields: " + fields, null);
}
}
Notice what the message holds: field names, never values. A model can copy private text into a field. If you log the value, you log that text.
Now wrap the call. One retry, then fail:
@Override
public Ticket classify(String text) {
try {
return classifyOnce(text);
} catch (ModelOutputException first) {
log.warn("Bad model output, retrying once: {}", first.getMessage());
return classifyOnce(text);
}
}
Why once? Models do vary between calls, so one more try is cheap insurance. If two tries fail, the task or the model is probably wrong. More tries add waiting time and, on a hosted model, cost.
Spring AI has its own switch, entity(Ticket.class, spec -> spec.validateSchema()). Per the docs it validates against the JSON schema, tells the model what was wrong and retries, up to 3 attempts by default. We wrote our own for two reasons. We wanted exactly one retry. And we wanted our Bean Validation rules, which a JSON schema does not carry. We did not run validateSchema() ourselves.
The controller turns the two kinds of failure into two status codes:
private <T> T answer(Supplier<T> call) {
try {
return call.get();
} catch (ModelOutputException e) {
log.warn("Model output rejected: {}", e.getMessage());
throw new ResponseStatusException(HttpStatus.BAD_GATEWAY,
"The assistant gave an answer we cannot use. Try again.");
} catch (RuntimeException e) {
log.warn("Model call failed: {}", e.toString());
throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE,
"The assistant is unavailable. Try again later.");
}
}
We chose 502 over 422. RFC 9110 says 422 means the server could not process the instructions in the request content. Here the caller's request was fine. A server we depend on, the model, gave us a bad reply. That is what 502 describes. A dead model stays 503, as in Part 3.
A real failure
We needed a message that does not fit any category. We sent a request for a poem:
curl -X POST http://localhost:8080/classify \
-H "Content-Type: application/json" \
-d '{"text":"Write me a poem about my cat."}' \
-w "\nHTTP %{http_code}\n"
In our test run (Spring AI 2.0.2, 2026-11-11, model llama3.2:3b) the answer was a 502:
{"timestamp":"2026-11-11T17:52:54.529Z","status":502,"error":"Bad Gateway","path":"/classify"}
HTTP 502
The log showed one retry, then the rejection:
WARN ... ChatAssistant : Bad model output, retrying once: reply is not valid JSON for Ticket (UnexpectedEndOfInputException)
WARN ... AskController : Model output rejected: reply is not valid JSON for Ticket (UnexpectedEndOfInputException)
The exception says the text ended too soon. We do not log the reply, on purpose, so we cannot say if it was empty or cut off. A weather question failed the same way. The billing message from the last section passed.
Spring also logs the rejected value when @Valid fails on the request. In our test run that line appeared for an empty text. For a 2,000 character message it would hold the message. We silenced it in application.properties:
logging.level.org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver=ERROR
Lists and fixed choices
A customer email often holds several problems. Ask for a list of records. entity(Class) cannot express List<Ticket>, so the docs use ParameterizedTypeReference:
tickets = chat.prompt()
.system(CLASSIFY_SYSTEM + "The message may hold several problems. Write one ticket for each.")
.user(text)
.call()
.entity(new ParameterizedTypeReference<List<Ticket>>() { });
We validate every element, and we reject an empty list:
if (tickets == null || tickets.isEmpty()) {
throw new ModelOutputException("reply holds no tickets", null);
}
tickets.forEach(this::check);
In our test run (Spring AI 2.0.2, 2026-11-11, model llama3.2:3b), this message went to /classify/many: "My password reset email never arrives. Also the invoice page crashes when I open it, and I was charged twice in October."
[{"category":"BILLING","priority":"MEDIUM","summary":"No password reset email received"},{"category":"BILLING","priority":"HIGH","summary":"Invoice page crashes on opening"},{"category":"BILLING","priority":"MEDIUM","summary":"Duplicate charge in October"}]
Three tickets, all valid. Look at the categories, though. The first two should be ACCOUNT and BUG. Validation proves the shape is right. It cannot prove the model is right. With the smaller llama3.2:1b, three tries on list requests all returned 502.
To make the model choose from a fixed set, we do two things. The enum is the set, and Category.forPrompt() puts each value and its meaning in the system prompt. A value outside the enum fails parsing, so it cannot reach your code.
On settings: the temperature(0.0) call you saw above is a portable option. ChatOptions.Builder has model, temperature, maxTokens, topP, topK, frequencyPenalty, presencePenalty and stopSequences. Each provider also has its own options class. For Ollama that is OllamaChatOptions, with extras such as numCtx and keepAlive. Whether a provider applies each portable option is up to its integration, so check its page. We confirmed only that Ollama received "temperature" in the request above.
The Spring AI docs also describe useProviderStructuredOutput(), which sends the schema to the provider as a constraint. The docs call Ollama support model-specific. We did not test it.
Stream the answer
A model can take seconds to finish. Streaming shows words as they arrive. The service method is one line:
@Override
public Flux<String> askStream(String question) {
return chat.prompt().user(question).stream().content();
}
stream().content() returns a Flux<String>, a stream of text chunks from Reactor. The ChatClient docs say streaming needs the reactive stack on the classpath. In our project it was already there through the Ollama starter, and the code compiled and streamed.
The controller wraps each chunk as a server-sent event (SSE), which is a long-lived HTTP response of data: lines:
@GetMapping(path = "/ask/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
Flux<ServerSentEvent<Object>> askStream(@RequestParam String q) {
check(q);
return assistant.askStream(q)
.map(token -> ServerSentEvent.<Object>builder(new Token(token)).build())
.concatWith(Flux.just(ServerSentEvent.<Object>builder("").event("done").build()))
.onErrorResume(e -> {
log.warn("Stream failed: {}", e.toString());
return Flux.just(ServerSentEvent.<Object>builder("The assistant stopped. Try again.")
.event("failed").build());
});
}
record Token(String text) { }
Three choices here came from real problems:
- Each token is JSON, such as
{"text":" Java"}. Tokens start with a space. The SSE rules say a client removes one space afterdata:, so plain text would glue words together. - A
doneevent closes the stream. Without it,EventSourcesees the connection end and reconnects, which asks the model again. - Errors use the event name
failed, noterror.EventSourcealready fireserrorfor connection problems.
Watch it with curl -N, which turns off curl's own buffering:
curl -N --get --data-urlencode "q=Name three Java collection classes in one sentence." \
http://localhost:8080/ask/stream
In our test run (Spring AI 2.0.2, 2026-11-11, model llama3.2:3b) the output began like this:
data:{"text":"Three"}
data:{"text":" Java"}
data:{"text":" collection"}
data:{"text":" classes"}
...
data:{"text":"."}
event:done
data:
Here is a browser page. It is static/stream.html in the example, and Spring Boot serves it at /stream.html:
const out = document.getElementById('out');
document.getElementById('go').onclick = () => {
out.textContent = '';
const q = encodeURIComponent(document.getElementById('q').value);
const es = new EventSource('/ask/stream?q=' + q);
es.onmessage = (e) => { out.textContent += JSON.parse(e.data).text; };
es.addEventListener('failed', (e) => { out.textContent += '\n[' + e.data + ']'; es.close(); });
es.addEventListener('done', () => es.close());
es.onerror = () => es.close();
};
We ran the same client code in Node 24 with its built-in EventSource, not in a browser. It rebuilt the full sentence with spaces intact. Open the page in your browser and check.
Time to first token is how long you wait for the first piece of text. Total time is how long until the last piece. Streaming improves the first number and leaves the second about the same. In one run on a warm model and a laptop CPU, the first byte of a streamed answer arrived in 0.34 s, against 3.3 s for the blocking /ask. That is one run each, not a benchmark.
What goes wrong with streams
We checked each of these, as far as we could. Most checks used a fake Ollama server, a small test class that sends chosen text, so we could cut the stream when we wanted.
- A proxy buffers the stream. nginx buffers proxied responses by default (
proxy_buffering on), and its docs say a backend can switch that off with theX-Accel-Buffering: noresponse header. We did not run a proxy. If your stream arrives all at once in production and not on your laptop, look here first. - Timeouts. Spring MVC has
spring.mvc.async.request-timeout, which is unset by default, so the server's own default applies. We did not tune it. Also check any gateway idle timeout in front of you. - An error in the middle. The status line is already sent, so the status is 200. In our fake-server test, a broken line from the model server became an
event:failedand noevent:done. Your client must handle that event. - The client leaves. In our fake-server test, the browser side closed after three events. The fake model server then saw its connection fail, and it had sent far fewer than its 200 chunks. So Spring cancelled the upstream call. The Servlet API gives no notice when a client leaves, so Spring finds out only when a write fails, as the Spring Framework docs explain. A model that stays silent for a long time keeps running until its next chunk. The docs suggest a periodic heartbeat event. We did not add one, and we did not test any of this against a real Ollama.
- A slow failure. When the fake server answered with HTTP 500, our first test hung. Spring AI retries by default. The property metadata shows
spring.ai.retry.max-attemptsof 10, a first wait of 2 seconds and a multiplier of 5. Set the retry properties on purpose.
Typed and streamed together
You cannot stream a typed entity with ChatClient. The docs say entity(...) works only after call(), and validateSchema() does not work with streaming. We checked the API as well:
@Test
void streamingHasNoEntityMethod() {
// The streaming spec offers text and metadata only. A typed answer needs the whole reply.
assertThat(Arrays.stream(ChatClient.StreamResponseSpec.class.getMethods()).map(m -> m.getName()))
.contains("content", "chatResponse")
.doesNotContain("entity", "responseEntity");
}
A half-finished JSON object is not a record, so this is by design. You have two options. Stream text to the screen and ask for the record in a second, non-streamed call. Or buffer the chunks, then convert, which is what the docs show:
String whole = String.join("", ChatClient.builder(model).build()
.prompt().user("Typo on the page.")
.stream().content()
.collectList().block());
assertThat(converter.convert(whole).priority()).isEqualTo(Ticket.Priority.LOW);
We ran the buffer-then-convert test with a scripted model, not a real one. Buffering gives up the point of streaming, so use it only when you need the type.
Test it without a model
Tests that call a model are slow and give different answers each time. Almost everything above can be tested without one. You need these test dependencies. The Spring Boot 4.0 migration guide says Spring Boot 4 split its test support into modules, and the generated project already has them:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc-test</artifactId>
<scope>test</scope>
</dependency>
Validation rules need only a validator:
@Test
void rejectsMissingFields() {
var ticket = new Ticket(null, null, null);
assertThat(validator.validate(ticket))
.extracting(v -> v.getPropertyPath().toString())
.containsExactlyInAnyOrder("category", "priority", "summary");
}
Parsing of good and bad samples uses the same converter that entity() uses. These are two of the three bad samples:
@Test
void rejectsTextAroundTheJson() {
var reply = "Sure! Here is the ticket: {\"category\":\"BUG\",\"priority\":\"HIGH\",\"summary\":\"x\"}";
assertThatThrownBy(() -> converter.convert(reply)).isInstanceOf(JacksonException.class);
}
@Test
void rejectsAValueOutsideTheEnum() {
var reply = "{\"category\":\"SPAM\",\"priority\":\"HIGH\",\"summary\":\"x\"}";
assertThatThrownBy(() -> converter.convert(reply)).isInstanceOf(JacksonException.class);
}
The retry rule needs a model that replays fixed replies. This small class also remembers each prompt it was given:
@Override
public ChatResponse call(Prompt prompt) {
prompts.add(prompt);
return reply(replies.remove());
}
With it, the real ChatClient and the real converter run, and only the model is fake:
@Test
void failsAfterTheSecondBadAnswer() {
var model = new ScriptedChatModel(MISSING_SUMMARY, "not json at all", GOOD);
assertThatThrownBy(() -> assistantWith(model).classify("anything"))
.isInstanceOf(ModelOutputException.class);
assertThat(model.prompts).hasSize(2); // the third scripted reply is never used
}
The controller and the error mapping use a fake Assistant, the interface from Part 3. In Spring Boot 4, @WebMvcTest lives in org.springframework.boot.webmvc.test.autoconfigure. @MockBean is gone, so we use a hand-written fake in a @TestConfiguration. The migration guide names @MockitoBean as its replacement. We used a fake and did not compile a @MockitoBean version.
@Test
void badModelOutputIsA502() throws Exception {
fake.failure = new ModelOutputException("ticket breaks its rules, fields: summary", null);
mvc.perform(post("/classify").contentType(MediaType.APPLICATION_JSON).content(body("Checkout fails.")))
.andExpect(status().isBadGateway());
}
The same class tests the stream, including an error halfway:
@Test
void streamErrorBecomesAnErrorEventNotAStackTrace() throws Exception {
fake.tokens = Flux.concat(Flux.just("Hel"), Flux.error(new IllegalStateException("boom: secret detail")));
String sse = stream("/ask/stream?q=hi");
assertThat(sse).contains("data:{\"text\":\"Hel\"}", "event:failed", "The assistant stopped. Try again.");
assertThat(sse).doesNotContain("secret detail", "event:done");
}
One optional test calls the real local model. It is tagged, and the build skips it unless you ask:
@Tag("live-model")
@SpringBootTest
class LiveModelTest {
./mvnw test -Dtest=LiveModelTest -Dexcluded.groups=none
The plain ./mvnw test ran 35 tests with no failures in our test run, and none of them needed a model.
When something goes wrong
| What you see | Likely cause | What to check |
|---|---|---|
StreamReadException or UnexpectedEndOfInputException in the log | Text around the JSON, an empty reply or a cut-off reply | Try a larger model. Check num_predict or maxTokens is not too low |
InvalidFormatException | A value outside the enum | Compare the enum with the prompt. Add a catch-all value such as QUESTION |
Parses fine, but a check failure names a field | The model left a field out or wrote an empty one | The field name in the log shows which |
/classify answers 502 after a long wait | Both tries failed, and each try is slow on a local model | Time one call to the model without the app |
| A request hangs, then 503, when the model server errors | Spring AI retries 5xx replies by default | spring.ai.retry.max-attempts and the backoff properties |
| 429 from a hosted provider | A rate limit. We could not test this | The property metadata says client errors are not retried unless you set spring.ai.retry.on-client-errors or on-http-codes. Read your provider's rate limits |
The stream rows live in the section above: a proxy that buffers, an error in the middle, and a client that leaves.
Five mistakes to avoid
- Parsing with a regex. A new wording breaks it. Ask for a type.
- Trusting enum values and fields. Parsing a missing field does not fail. Validate after the call.
- Retrying in a loop. Retry once, with a reason. Then fail with a clear code.
- Streaming through a proxy you have not tested. Test on the real path, not only on localhost.
- Logging whole prompts. They can hold personal data. Log field names, counts and codes.
Cheat sheet
| Task | What to use |
|---|---|
| Get a record | .call().entity(Ticket.class) |
| Get a list | .entity(new ParameterizedTypeReference<List<Ticket>>() { }) |
| Check the record | Bean Validation annotations and a Validator |
| Catch bad JSON | tools.jackson.core.JacksonException |
| Retry from Spring AI | entity(Ticket.class, spec -> spec.validateSchema()), 3 tries by default |
| Portable setting | .options(ChatOptions.builder().temperature(0.0)) |
| Stream text | .stream().content(), a Flux<String> |
| Send it to a browser | produces = TEXT_EVENT_STREAM_VALUE and ServerSentEvent |
| Watch a stream | curl -N |
| Test the controller | @WebMvcTest from org.springframework.boot.webmvc.test.autoconfigure |
| Test without a model | A scripted ChatModel, sample JSON, a fake Assistant |
Try it yourself
- Add a flag. Add
boolean needsHumantoTicket, and say in the prompt when it must be true. Hint: update the parsing tests, because the schema changes. A good result is a test that fails on a missing flag, and a real run where an angry message sets it to true. - Return action items. Add
/actionsthat returns aList<ActionItem>with an owner and a due text, from meeting notes. Hint: copysplitIntoTickets. A good result is a list of valid records, and a 502 when you send text with no actions. - Count chunks. Stream a long answer and count the
data:lines withcurl -Nandgrep -c. Hint: the lines are separated by blank lines. A good result is a number, and a sentence about whether it matches the number of words.
What comes next
In Part 5, RAG with Spring AI and pgvector, the model answers from your own documents, and you can check that it does.
Ten parts are planned. Five are published.
- Java Developer to AI Engineer: The Complete Roadmap
- How LLMs work, for Java developers
- Call your first LLM from Spring Boot
- Typed answers and streaming with Spring AI (this article)
- RAG with Spring AI and pgvector
- Agents: the plan, act, observe loop (Stage 3)
- MCP servers and clients in Java (Stage 3)
- Evaluating and tracing LLM apps (Stage 4)
- Guardrails, approvals and cost control (Stage 4)
- Your portfolio and interviews (finish)
To get the next part, subscribe to the blog feed. You can also find us as @agentworkshq on X and Instagram.