Quick revision
The short answer
A language model produces its answer by sampling one token at a time from a probability distribution, so the same prompt can lead to different answers; temperature and similar options reduce the randomness, but even a low temperature does not guarantee identical output. Format instructions are also followed only with high probability, not always. A Java service should therefore use structured output support, such as Spring AI's .call().entity(MyRecord.class) or a provider's native JSON schema mode, validate every parsed result, retry or fail cleanly, and log the prompt, model version and options so that a bad answer can be investigated.
What to remember
In this answer, we saw that a model samples each token from probabilities, so answers vary, and that temperature narrows the choice without making it deterministic. Format instructions only make the right format likely, so we used Spring AI's entity() method or a provider's schema mode, validated every result, retried a limited number of times and fell back cleanly, and logged prompt, model version and options so that every answer can be explained later.
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.
A language model produces its answer by sampling one token at a time from a probability distribution, so the same prompt can lead to different answers; temperature and similar options reduce the randomness, but even a low temperature does not guarantee identical output. Format instructions are also followed only with high probability, not always. A Java service should therefore use structured output support, such as Spring AI's .call().entity(MyRecord.class) or a provider's native JSON schema mode, validate every parsed result, retry or fail cleanly, and log the prompt, model version and options so that a bad answer can be investigated.
Why this question is asked
Developers who are used to deterministic code are often surprised the first time an LLM returns valid JSON nine times and a friendly paragraph the tenth. The bug report says the model is broken, but the behaviour is how these models work, and the fix belongs in our code, not in the prompt alone. Interviewers ask this to check that we understand the source of the randomness and that we design services which stay correct anyway. In this answer, we will see how a model picks its words, what temperature really changes, why format instructions are not a guarantee, and then build the parsing, validation and logging a Java service needs.
1How a Model Picks Its Next Word
A large language model, or LLM, works on tokens, pieces of text about three or four characters long on average. Given everything so far, the model computes a probability for every possible next token. For the prompt Classify this ticket, the next token might be Billing with probability 0.62, Technical with 0.30 and something else with 0.08. The provider then samples, which means it picks one token at random according to those probabilities, appends it, and repeats for the next token.
So randomness enters at every step, and one different early token changes everything after it. If the first token is Sure instead of an opening brace, the model is now writing a sentence, and the JSON we asked for may never arrive.
2What Temperature Changes and What It Does Not
Temperature is an option that reshapes the probabilities before sampling. A high temperature, such as 1.0, keeps them as they are or flattens them, so less likely tokens are chosen more often. A low temperature, such as 0.1, sharpens them so the most likely token almost always wins. A temperature of 0 is usually treated as always choose the most likely token. Other options such as top_p, which samples only from the smallest set of tokens covering a given share of probability, work in the same direction.
But there is a catch: even at temperature 0, output is not guaranteed to be identical across calls. Providers run requests in batches on many machines, and tiny floating-point differences between runs can flip a choice between two almost equally likely tokens. Providers also update models behind the same name. So lower temperature makes results more stable, which is right for extraction and classification, but our code must still not depend on exact repeatability. Some models also restrict or ignore temperature, so check your provider's documentation.
3Why the JSON Format Gets Ignored
When we write respond only with JSON in the prompt, we are adding text that makes JSON-shaped tokens more likely. We are not switching on a parser inside the model. Most of the time the instruction wins; sometimes the model wraps the JSON in a Markdown code fence, adds a sentence before it, invents a field name, writes a number as a string, or stops early because it hit the output token limit. Each of these breaks a naive objectMapper.readValue call.
Two things help a lot. The first is structured output support in the framework, which writes precise format instructions derived from our Java type and parses the answer for us. The second is a provider's native structured output, where we send a JSON schema with the request and the provider constrains generation so the output matches it. Native modes make malformed JSON very rare, but they still cannot make the values correct: a schema can say total is a number, not that it is the right number.
4Using Structured Output in Spring AI
In Spring AI, calling entity() instead of content() asks the ChatClient to return a typed object. Behind it, a converter (BeanOutputConverter) generates a JSON schema from the record, adds format instructions to the prompt, and parses the response into the record.
Notice that entity() can still fail. If the response is not valid JSON for the record, the converter throws an exception, and if it parses, the values might still be nonsense, such as priority 9. Whether Spring AI uses the provider's native schema mode for a given model, and how to turn it on, depends on the provider and the Spring AI version, so check your version's documentation on structured output.
5Validate, Retry or Fail Cleanly
So the service treats model output like any other untrusted input. It parses, validates with Bean Validation, and if either step fails it retries once or twice, perhaps adding the error message to the prompt so the model can correct itself. If retries fail, it returns a clear error or a safe default, such as routing the ticket to a human queue, rather than storing half-parsed data.
- Call the model with entity(TicketLabel.class)format instructions or native schema
- Parsed into the record?YesValidate the valuesNoRetry, at most twice
- Values valid?YesUse the resultNoRetry, at most twice
- Retries exhaustedroute to a human queue, log the case
4 steps in order. Play them, or step through them one at a time.
6Logging for Reproducibility
When someone reports a wrong answer, we need to see exactly what the model saw. We log, or store in a dedicated audit table, the full prompt after templating, the model name and version the provider reported in the response metadata, the options such as temperature and maximum tokens, the raw response and the parse result. With that, we can replay the call, compare model versions and build a test case. Prompts can contain personal data, so this log needs the same access controls and retention rules as the data itself.
7Follow-up questions
Can we set a seed to make answers repeatable?
Some providers accept a seed option that makes sampling repeatable on a best-effort basis. It helps in tests and investigations, but providers do not promise identical output across hardware or model updates, so we still design for variation.
Should we lower temperature for every use case?
No. For extraction, classification and answers that must match data, low temperature is right. For brainstorming or writing variations, some randomness is the point. The choice belongs to each feature, and we record it with the call.
Why not parse the JSON with a regular expression that strips the code fences?
It fixes one failure, the fence, and leaves all the others: missing fields, wrong types and wrong values. Structured output plus validation handles the whole class of problems, and a small cleanup step can live inside it if a model keeps adding fences.
8Conclusion
In this answer, we saw that a model samples each token from probabilities, so answers vary, and that temperature narrows the choice without making it deterministic. Format instructions only make the right format likely, so we used Spring AI's entity() method or a provider's schema mode, validated every result, retried a limited number of times and fell back cleanly, and logged prompt, model version and options so that every answer can be explained later.
Open with
The answer differs because the model generates text by sampling one token at a time from a probability distribution. Each step has some randomness, and one different early token changes the rest of the answer.
Then, if they want more
Temperature controls how sharp that distribution is, so a low temperature makes answers more stable, but even at zero you do not get guaranteed identical output, because of batching and floating-point effects on the provider's side and because models get updated.
The JSON problem has the same cause: a format instruction makes JSON tokens more likely, it does not enforce a grammar. So the model sometimes adds a sentence, a code fence or a wrong field. In a Java service I would use structured output.
In Spring AI that is call().entity(MyRecord.class), which adds format instructions from the record's schema and parses the result, and where the provider supports a native JSON schema mode I would turn it on. Then I validate the parsed object with Bean Validation, because valid JSON can still contain wrong values.
If parsing or validation fails, I retry once or twice and otherwise fail cleanly, for example by sending the case to a human. Finally I log the prompt, the model version from the response and the options, so any bad answer can be reproduced and investigated.
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 Java developer asks why an LLM answer differs each time for the same prompt and...": https://scrivio-interview-library.netlify.app/spring-boot/spring-ai/ef106103e3/