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.


_16
import { z } from 'zod';
_16
import { zodOutputFormat } from '@anthropic-ai/sdk/helpers/zod';
_16
_16
const Verdict = z.object({
_16
sentiment: z.enum(['positive', 'neutral', 'negative']),
_16
confidence: z.number().min(0).max(1),
_16
});
_16
_16
const response = await client.messages.parse({
_16
model: 'claude-opus-5-5',
_16
max_tokens: 256,
_16
messages: [{ role: 'user', content: `Classify this review:\n\n${review}` }],
_16
output_config: { format: zodOutputFormat(Verdict) },
_16
});
_16
_16
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.


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

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.


_10
const SYSTEM = `Classify support tickets by priority.
_10
- high: the customer cannot use the product at all, or data is at risk.
_10
- medium: a feature is broken but there is a workaround.
_10
- low: everything else, including questions and feature requests.
_10
If a ticket fits two categories, pick the higher one.
_10
_10
Example: "Site is down for all our users" -> high
_10
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.


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

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.


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

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.


_10
const results = await Promise.all(
_10
Array.from({ length: 20 }, () => classify(sampleReview)),
_10
);
_10
const counts = results.reduce<Record<string, number>>((acc, r) => {
_10
acc[r.sentiment] = (acc[r.sentiment] ?? 0) + 1;
_10
return acc;
_10
}, {});
_10
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.
#

quick question

Was this resource helpful?