Quick revision
The short answer
First we log the raw responses that fail (redacted) and sort them into causes: code fences, extra text, missing fields, wrong types, or answers cut off by the token limit. Then we use the provider's native JSON schema mode where it is supported instead of relying only on format instructions, lower the temperature, add a short example and raise max tokens. Parsed objects are checked with Bean Validation, a failure gets one retry with the error added to the prompt, and the failure rate is tracked per model and prompt version with a regression set.
What to remember
In this answer, we saw that entity() asks the model for JSON through format instructions and parses the reply, which fails when the model adds fences or text, gets types wrong or is truncated. We fixed it in layers: classify the logged failures, use native JSON schema mode where supported, lower the temperature, add an example and raise max tokens, validate with Bean Validation and retry once with the error, and track the failure rate per model and prompt version with a regression set.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
First we log the raw responses that fail (redacted) and sort them into causes: code fences, extra text, missing fields, wrong types, or answers cut off by the token limit. Then we use the provider's native JSON schema mode where it is supported instead of relying only on format instructions, lower the temperature, add a short example and raise max tokens. Parsed objects are checked with Bean Validation, a failure gets one retry with the error added to the prompt, and the failure rate is tracked per model and prompt version with a regression set.
Why this question is asked
Structured output is what turns a chat model into a component other code can use: instead of free text we get a List<LineItem> we can save or sum. A 3 percent failure rate sounds small, but at 100,000 calls a day it is 3,000 broken invoices, and each failure is invisible to users until something downstream goes wrong. Interviewers ask this question to see whether we debug by evidence and know the layers of defence. In this answer, we will recap how entity() works, classify the failures, then go through native schema mode, prompt and token settings, validation with a retry, and measuring the rate.
1A Quick Recap of How entity() Works
When we call .entity(new ParameterizedTypeReference<List<LineItem>>() {}), Spring AI uses an output converter, BeanOutputConverter, to do two things. Before the call, it generates a JSON schema from the Java type and appends format instructions to the prompt, telling the model to answer with JSON matching that schema. After the call, it takes the response text and parses it with Jackson into the Java type.
So by default the model is only asked, in words, to produce valid JSON. Most of the time it does. Sometimes it wraps the JSON in a markdown code fence, adds a polite sentence after it, leaves out a field, writes a price as "12,50 EUR" instead of a number, or runs out of output tokens halfway through the array. Any of those makes the Jackson parse fail.
2Look at the Failures
We cannot fix what we have not seen, so we catch the parse failure, log the raw response with personal data redacted, and tag the log with a cause. A small classifier in code is enough to sort most of them.
| Cause | What we see | Fix |
|---|---|---|
| Code fence | ``json [ ... ] `` | native schema mode; fence stripping |
| Trailing text | JSON, then 'Let me know if...' | native schema mode; lower temperature |
| Truncated | array ends mid-object | raise max tokens; fewer items per call |
| Missing field or wrong type | "price": "12,50 EUR" | schema mode; example; validation and retry |
Notice that the result changes the plan. If most failures were code fences, stripping fences would be enough. Here more than a third are truncation or trailing text, and a fifth are wrong fields or types, so we need several fixes. Newer Spring AI versions already strip a leading code fence in the converter, so check your version; the other causes remain.
3Use Native Structured Output Where Supported
Several providers can enforce a JSON schema while the model generates, often called JSON schema mode or structured outputs. The model is then constrained to produce text that matches the schema: no fences, no extra sentences, every required field present with the right type. That removes most failures at the source instead of cleaning them up afterwards.
Spring AI exposes this through provider options, for example a response format with a JSON schema in the OpenAI options, and newer versions add ways to ask ChatClient to use the native mode for entity(). The exact option names and which models support it vary by provider and Spring AI version, so check both before relying on it.
4Prompt and Token Settings
Where native mode is not available, or as extra safety, three settings reduce failures. A low temperature (0 to 0.2) makes the model follow the format more consistently. A short example of the exact output, one line item with realistic values, shows the model what a price or a quantity should look like. And a higher max tokens limit stops truncation: if an invoice has 40 lines and each line takes about 40 tokens, the answer needs about 1,600 tokens, so a limit of 1,000 cuts every large invoice in half. For very long inputs, splitting the document and extracting page by page is better than one huge answer.
We can confirm truncation directly: the response metadata carries a finish reason, and a value meaning length (the exact value differs per provider) tells us the model stopped because it hit the limit, not because it finished.
5Validate, Retry Once, Then Fail Clearly
Valid JSON is not the same as correct data. A line item with a negative quantity parses fine but is still wrong. So we annotate the record with Bean Validation constraints and validate after parsing. If parsing or validation fails, we retry once with the error message added to the prompt, which gives the model a concrete correction to make. If the retry fails too, we stop and report a clear error instead of retrying forever.
- Call the modelnative schema mode if supported
- Parses and validates?YesReturn the itemsNoRetry once with the error
- Retry parses and validates?YesReturn the itemsNoFail clearly; manual review
- Record outcomemetric per model and prompt version
4 steps in order. Play them, or step through them one at a time.
One retry is the sweet spot for most systems: it recovers most random failures and costs at most one extra call. More retries mostly repeat the same mistake and multiply cost and latency.
6Measure It and Guard Against Regressions
We record the failure rate as a metric tagged by model and prompt version, so we can see whether a change helped and catch the day a model update makes it worse. We also keep a regression set: a few hundred real inputs, including the ones that failed before, with the expected items. It runs in CI whenever the prompt, the model or the Spring AI version changes. With native schema mode, a lower temperature, enough tokens and one retry, a 3 percent failure rate typically drops well below 0.5 percent, and the remaining failures go to manual review instead of breaking silently.
7Follow-up questions
Why is BeanOutputConverter less reliable than native schema mode?
Because by itself it only asks. It adds format instructions to the prompt and parses whatever comes back, so the model is free to add fences, extra text or wrong types, and nothing stops it running out of tokens. Native schema mode constrains generation on the provider side, so the output matches the schema by construction. The converter is still useful in both cases: it generates the schema and parses the result.
Should we just strip code fences with a regex?
As a quick extra layer, yes, but it fixes only one cause. Truncation, trailing text and wrong types remain, and a growing pile of string fixes hides problems that native mode, settings and validation solve properly.
What do you do with inputs that fail twice?
Store them with the error and send them to a manual review queue or a fallback path, and add them to the regression set so the next prompt or model change is tested against them.
8Conclusion
In this answer, we saw that entity() asks the model for JSON through format instructions and parses the reply, which fails when the model adds fences or text, gets types wrong or is truncated. We fixed it in layers: classify the logged failures, use native JSON schema mode where supported, lower the temperature, add an example and raise max tokens, validate with Bean Validation and retry once with the error, and track the failure rate per model and prompt version with a regression set.
Open with
I would start with evidence. I catch the parse failures, log the raw response with personal data redacted, and classify them: code fences, trailing text, truncation by max tokens, missing fields or wrong types.
Then, if they want more
Usually it is a mix. By default entity uses BeanOutputConverter, which only adds format instructions and parses the reply, so the model can still drift.
The biggest fix is the provider's native structured output or JSON schema mode where it is supported, because it constrains generation to the schema; I would check which options our provider and Spring AI version offer.
Then I lower the temperature, add one short example of the output, and raise max tokens, confirming truncation from the finish reason in the metadata. After parsing I validate the records with Bean Validation, because valid JSON can still be wrong data.
If parsing or validation fails, I retry once with the error message added to the prompt, and if that fails too I fail clearly and send the case to manual review.
Finally, I track the failure rate as a metric per model and prompt version and keep a regression set of real inputs, including past failures, that runs whenever the prompt or model changes.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring AI reference
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A service uses chatClient.prompt().user(text).call().entity(new...": https://scrivio-interview-library.netlify.app/spring-boot/spring-ai/3063dfa885/