---
title: "Why does an LLM give a different answer every time, and how do I make it consistent?"
description: "Models sample from a probability distribution, so repeat runs differ. Constrain the output with a schema, instruct tightly, validate with Zod, and test over many runs."
url: https://www.danny.engineering/answer/ai/why-does-an-llm-give-a-different-answer-every-time-and-how-do-i-make-it-consistent
author: Danny
published: 2026-12-03T00:00:00.000Z
updated: 2026-12-03T15:34:00.000Z
tags: ["AI"]
---

# Why does an LLM give a different answer every time, and how do I make it consistent?

## The short answer


A language model does not look up an answer, it generates one token at a time by sampling from a probability distribution over possible next tokens. Two runs of the same prompt can take different branches early and end up with different wording, structure or even conclusions. You cannot make generation deterministic, but you can make the parts you depend on consistent: constrain the shape with a JSON schema, pin down the behaviour with explicit instructions and examples, validate the result in code, and measure consistency across many runs rather than trusting one.


```typescript
import { z } from 'zod';
import { zodOutputFormat } from '@anthropic-ai/sdk/helpers/zod';

const Verdict = z.object({
  sentiment: z.enum(['positive', 'neutral', 'negative']),
  confidence: z.number().min(0).max(1),
});

const response = await client.messages.parse({
  model: 'claude-opus-5-5',
  max_tokens: 256,
  messages: [{ role: 'user', content: `Classify this review:\n\n${review}` }],
  output_config: { format: zodOutputFormat(Verdict) },
});

console.log(response.parsed_output); // typed as { sentiment, confidence }
```


## Why it happens


At each step the model produces a score for every token in its vocabulary. "The capital of France is" gives "Paris" an overwhelming score, so you will see it every time. "Suggest a name for this function" gives several plausible tokens similar scores, and the sampler picks among them. Once one is picked it becomes part of the context, and everything after it is conditioned on that choice. Small early differences compound into visibly different answers.


**Temperature is no longer the lever.** Older advice says to set `temperature` to 0 for deterministic output. Current Claude models do not accept `temperature`, `top_p` or `top_k`; the API rejects them. Even where a provider still offers it, temperature 0 was never a guarantee: batching and hardware differences meant runs could still diverge, and it made the model worse at tasks that need some variety. The honest position is that sampling is part of how these systems work, and consistency has to come from the structure around the call.


**Variation is not all one kind.** Wording changes are harmless if you only read a field. Structural changes (a list one time, a paragraph the next) break parsers. Decision changes (positive one run, neutral the next) are the ones that matter, and they usually mean the prompt leaves the decision genuinely ambiguous. Each kind has a different fix.


## How to make it consistent


### Constrain the shape with a schema


Structured outputs make the model return JSON that matches a schema you supply. The shape is then fixed, the keys are always present, and enums limit the decision to a known set. With Zod you get a parsed, typed object back and never touch the raw string. Without Zod, pass a JSON schema directly.


```typescript
const response = await client.messages.create({
  model: 'claude-opus-5-5',
  max_tokens: 256,
  messages: [{ role: 'user', content: prompt }],
  output_config: {
    format: {
      type: 'json_schema',
      schema: {
        type: 'object',
        properties: { priority: { type: 'string', enum: ['low', 'medium', 'high'] } },
        required: ['priority'],
        additionalProperties: false,
      },
    },
  },
});
```


### Remove the ambiguity with instructions and examples


If the model flips between "medium" and "high" on the same ticket, the prompt has not said what the difference is. Define each category in one sentence, state the tie-break rule, and give two or three short examples with the answer you expect. Examples are the most reliable way to nail down borderline cases, because they show the boundary instead of describing it.


```typescript
const SYSTEM = `Classify support tickets by priority.
- high: the customer cannot use the product at all, or data is at risk.
- medium: a feature is broken but there is a workaround.
- low: everything else, including questions and feature requests.
If a ticket fits two categories, pick the higher one.

Example: "Site is down for all our users" -> high
Example: "Export button does nothing, I can use the API instead" -> medium`;
```


### Lower the effort for simple tasks


Current models reason before answering, and more reasoning means more room to explore alternatives. For a classification or an extraction there is nothing to explore. Setting `output_config.effort` to `low` makes the model answer more directly, which is cheaper, faster and often more stable for simple tasks. Keep higher effort for work that genuinely needs it.


```typescript
const response = await client.messages.parse({
  model: 'claude-opus-5-5',
  max_tokens: 256,
  output_config: { effort: 'low', format: zodOutputFormat(Verdict) },
  messages,
});
```


### Validate and retry in code


Even with a schema, validate business rules the schema cannot express: a date must be in the future, a total must equal the sum of lines, a quoted ID must exist in your database. If validation fails, retry with the error fed back as a new user message so the model can correct itself. Cap the retries and fail loudly after that.


```typescript
async function classify(review: string, attempt = 1): Promise<z.infer<typeof Verdict>> {
  const response = await client.messages.parse({ /* as above */ });
  const result = Verdict.safeParse(response.parsed_output);
  if (result.success) return result.data;
  if (attempt >= 3) throw new Error(`Invalid output after 3 attempts: ${result.error.message}`);
  return classify(review, attempt + 1);
}
```


### Test across many runs, not one


A prompt that works once has told you almost nothing. Build a small set of representative inputs with the answers you expect, run each one ten or twenty times, and record how often the model agrees with you and with itself. That gives you a consistency number you can compare before and after a prompt change, instead of a feeling.


```typescript
const results = await Promise.all(
  Array.from({ length: 20 }, () => classify(sampleReview)),
);
const counts = results.reduce<Record<string, number>>((acc, r) => {
  acc[r.sentiment] = (acc[r.sentiment] ?? 0) + 1;
  return acc;
}, {});
console.log(counts); // e.g. { positive: 19, neutral: 1 }
```


## Common pitfalls

- **Reaching for** **`temperature: 0`****.** It is rejected on current Claude models, and it never guaranteed identical output anywhere. Fix the prompt and the schema instead.
- **Parsing free text with a regex.** The wording will drift. Ask for JSON through structured outputs and read fields, not sentences.
- **Trusting the schema to validate meaning.** The schema guarantees shape. A well-formed answer can still be wrong, so check the rules that matter in code.
- **Judging by one run.** One success in the REPL is an anecdote. Twenty runs on ten inputs is evidence.
- **Leaving the decision rule implicit.** If two reasonable humans would disagree on a case, the model will disagree with itself. Write the tie-break down.
- **Retrying forever.** Unbounded retries hide a prompt problem behind a cost problem. Cap them, log the failures and read them.

## Related reading

- [Structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)
- [Messages API reference](https://platform.claude.com/docs/en/api/messages/create)
- [Zod documentation](https://zod.dev/)
