cd /news/large-language-models/llm-temperature-test-12-steps-75-min · home › topics › large-language-models › article
[ARTICLE · art-180926] src=shattered.io ↗ pub= topic=large-language-models verified=true sentiment=· neutral

LLM Temperature Test: 12 Steps, 75 Min

A 12-step, roughly 75-minute harness sends 540 short calls to Claude Haiku 5.5, Gemini 4 Hydrogen and GPT-6.2 Sol and scores answer drift at temperatures of 0, 0.7 and 1.0, logging exact-match rates, distinct-output counts, a similarity score and a JSON validity rate to a rerunnable file. The tutorial argues temperature 0 is not a guarantee of identical output because batching, differing hardware and floating-point ordering can flip near-ties between tokens, and it notes that Gemini 4 Hydrogen's four thinking levels (low, medium, high by default, and xhigh) add hidden reasoning-token randomness to visible output. A dry-run mode with a built-in simulator lets users test every script before spending money, and all sample output in the tutorial comes from that simulator.

recommendation

Run a 540-call sweep per model at temperatures 0, 0.7 and 1.0, logging exact-match, distinct-output, similarity and JSON-validity rates, and rerun it after every vendor update to size retries and fallbacks.

more in playbook: Evals and testing for LLM apps
by read33 min views15 publishedDec 3, 2026
LLM Temperature Test: 12 Steps, 75 Min
Image: Shattered (auto-discovered)

LLM temperature is the one sampling dial nearly every model API exposes, and almost nobody measures what it does. Teams set it to 0 for extraction, 1 for brainstorming, and ship. The harness below replaces that habit with data. It sends 540 short calls to Claude Haiku 5.5, Gemini 4 Hydrogen and GPT-6.2 Sol, then scores how much the answers drift at temperatures of 0, 0.7 and 1.0.

The result is a per-model, per-task table you can trust more than folklore. You get exact-match rates, distinct-output counts, a similarity score and a JSON validity rate, all logged to a file you can rerun after every vendor update. Pair it with the token and latency logging from an LLM observability setup and you can see quality, cost and speed in one place.

Budget about 75 minutes. Roughly 45 of those are the sweep itself, and you can work on the report scripts while it runs. A dry-run mode with a built-in simulator lets you test every script before spending a cent, and all the sample output in this tutorial comes from that simulator so you can reproduce it exactly.

Don't miss new tech stories on Google

Add Shattered once in the Google app and our stories show up in your news suggestions.

Add now

What LLM Temperature Actually Changes #

A language model produces a score for every possible next token. The sampler turns those scores into probabilities and draws one token. Temperature divides the scores before that conversion. Low values sharpen the distribution, so the top token wins almost every draw. High values flatten it, so runner-up tokens get picked more often and the text wanders further from the most likely phrasing.

At a temperature of 0, most APIs switch to picking the single highest-scoring token every time. That is called greedy decoding. It sounds like a guarantee of identical output, and it is not one. Providers batch requests together, run them on different hardware and use floating-point math whose order of operations can change between calls. A tiny numeric difference can flip a near-tie between two tokens, and once the first token differs, the rest of the answer follows a different path.

Mixture-of-experts routing and speculative decoding are other commonly cited sources of drift. Treat these as plausible mechanisms rather than confirmed facts for the three models in this test, because none of the vendors documents its serving stack in enough detail to say. What you can do is measure the outcome, which is the entire point of the exercise.

The measurement matters because people use temperature as a reliability setting. A zero is supposed to make extraction safe, and a high value is supposed to make naming ideas fresh. Both beliefs are partly true. If your app already checks model output with guardrails around each model call, a variance table tells you how often those checks will fire at each setting, which is exactly what you need to size retries and fallbacks.

Temperature, top_p and seed in one paragraph

The top_p setting cuts the distribution down to the smallest group of tokens whose probabilities add up to p, then samples from that group. Vendors commonly advise changing temperature or top_p but not both, because the two interact and make results hard to interpret. Some APIs also offer a seed parameter that makes sampling repeatable on a best-effort basis. Leave top_p and seed at their defaults in this test so only one variable moves.

Thinking levels add their own randomness

Gemini 4 Hydrogen offers four thinking levels, low, medium, high (the default) and xhigh. Reasoning tokens are sampled before the final answer appears, so the randomness you see in the visible text includes randomness from the hidden reasoning. A model that looks stable at a low thinking level can look noisier at a high one. Record the level next to every result and keep it constant within a sweep.

Prerequisites and Tested Versions #

You need a machine that can run Python and three API accounts. If you only have one or two vendors, delete the others from the MODELS dictionary in Step 3 and the rest of the harness works unchanged. The simulator needs no packages and no keys, so you can finish Steps 1 through 12 offline first and add real providers afterward.

Requirement Version or value Why you need it
Python 3.12 or newer (tested on 3.12.3) Runs every script in the harness
openai (pip) Latest release Calls GPT-6.2 Sol
anthropic (pip) Latest release Calls Claude Haiku 5.5
google-genai (pip) Latest release Calls Gemini 4 Hydrogen
pytest (pip) Latest release Runs the stability gate in Step 12
API keys OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY One per vendor, read from the environment
Disk and time A few megabytes, about 75 minutes JSONL log plus the full sweep

Accounts take the longest to prepare, so sort them out first. Create a project-scoped key at each vendor rather than reusing a personal key with broad permissions, and give it a spending cap. A scoped key limits the damage if a log file or shell history leaks, and a cap turns a runaway loop into a small annoyance instead of a surprise invoice. Revoke the keys when the experiment ends, or keep them only if the nightly gate in Step 12 will use them.

Pin your package versions the moment the install succeeds. SDKs change parameter names more often than people expect, and a harness that ran cleanly in December can break in March for reasons unrelated to the models. Step 1 writes the pins to requirements.txt so a rerun in six months uses the same client code.

Cost is small because the prompts are tiny and every call is capped at 800 output tokens. For scale, Anthropic lists Claude Haiku 5.5 from $0.10 per million input tokens and $0.50 per million output tokens for prompts up to 100,000 tokens, per its model overview page. Even so, set a billing limit on each account before a loop that makes hundreds of calls.

The Three Models Under Test as of December 3, 2026 #

Each vendor has a larger, slower tier. This test deliberately uses the small and fast tiers because temperature sweeps are repetitive, and repetition is cheap on small models. The method transfers to any model ID, so swapping in a bigger sibling later is a one-line change.

Model Vendor Announced API model ID Role in this test
GPT-6.2 Sol OpenAI Nov 17, 2026 gpt-6.2-sol The cheaper model of the GPT-6.2 pair
Claude Haiku 5.5 Anthropic Oct 7, 2026 Copy from the Haiku 5.5 overview page The current Haiku, replacing Haiku 4.5
Gemini 4 Hydrogen Nov 12, 2026 gemini-4-hydrogen The fast tier for agentic work and everyday coding

OpenAI introduced GPT-6.2 Astra and GPT-6.2 Sol together, and the harness targets Sol. OpenAI keeps its guidance on picking between models in a model selection guide, which is worth a read before you decide whether Astra deserves its own sweep. Sol is reportedly listed at $2 per million input tokens and $10 per million output tokens on the December 1 pricing page, though that figure rests on a single source, so check the page before budgeting.

Anthropic announced Claude Haiku 5.5 on October 7, 2026, and it is now the current Haiku. Its predecessor, Haiku 4.5, counts as the prior model. Anthropic describes the new one as the fastest and most efficient model in the Claude 5.5 family, built for high-volume, cost-sensitive work. No official source reports it renamed or retired, though you should check the docs before treating the model ID as fixed. A larger tier, Claude Fable 5.2, arrived on November 9 and is outside this test.

Google introduced Gemini 4 Hydrogen on November 12, 2026, and its launch post positions it for agentic workflows. It supports a context window of up to 1 million tokens and the four thinking levels mentioned earlier. Reportedly it costs $1.50 per million input tokens and $7.50 per million output tokens, again from a single source.

One caveat shapes the whole design. The official pages for these three models do not state that temperature behaves the same way on each, and they do not confirm that every value from 0 to 1.0 is accepted. That is why the provider adapters in Step 5 treat a rejected request as a result to record rather than an error to crash on. If a model refuses temperature 0.7, that refusal is itself a finding.

Steps 1 to 3: Set Up the Project, Keys and Config #

Step 1: Create the project and a virtual environment. Isolation keeps SDK versions from colliding with other projects. The last two commands freeze your dependency versions and create the folder for results.

mkdir temp_lab && cd temp_lab
python3 -m venv .venv
source .venv/bin/activate
pip install openai anthropic google-genai pytest
pip freeze > requirements.txt
mkdir results

Step 2: Export your keys and model IDs. The SDKs read keys from the environment, so nothing secret lands in your code. Copy the Claude Haiku 5.5 model ID from its overview page, because the harness refuses to guess it. Never commit these exports to version control. A .env file listed in .gitignore or a secrets manager works if you do not want to retype them each session.

export OPENAI_API_KEY="your-openai-key"
export ANTHROPIC_API_KEY="your-anthropic-key"
export GEMINI_API_KEY="your-google-key"

export MODEL_GPT="gpt-6.2-sol"
export MODEL_CLAUDE="paste-the-haiku-5-5-id-from-the-docs"
export MODEL_GEMINI="gemini-4-hydrogen"

Step 3: Write config.py. This file drives the whole LLM temperature sweep. It holds the three temperatures, the trial count and the model table. Ten trials per cell is a screening-grade sample, and the TRIALS variable lets you raise it later without touching code. The DRY_RUN switch swaps the real models for two simulators, which is how you test the plumbing for free. The active_models function stops with a clear message if a model ID is missing, so a half-configured run fails in one second instead of after twenty minutes.

import os

TEMPERATURES = [0.0, 0.7, 1.0]
TRIALS = int(os.environ.get("TRIALS", "10"))
MAX_TOKENS = int(os.environ.get("MAX_TOKENS", "800"))

MODELS = {
    "gpt": {"provider": "openai", "model": os.environ.get("MODEL_GPT", "gpt-6.2-sol")},
    "claude": {"provider": "anthropic", "model": os.environ.get("MODEL_CLAUDE", "")},
    "gemini": {"provider": "google", "model": os.environ.get("MODEL_GEMINI", "gemini-4-hydrogen")},
}

DRY_RUN = os.environ.get("DRY_RUN") == "1"

def active_models():
    if DRY_RUN:
        return {"sim-a": {"provider": "fake", "model": "sim-a"},
                "sim-b": {"provider": "fake", "model": "sim-b"}}
    missing = [k for k, v in MODELS.items() if not v["model"]]
    if missing:
        raise SystemExit(f"Set MODEL_{missing[0].upper()} before running (see the model overview page).")
    return MODELS

With six prompts, three temperatures, three models and ten trials, the full sweep makes 540 calls. A pilot with three trials makes 162. Keep those numbers in mind when you read progress logs, because they let you estimate how far along a run is by counting lines in the results file.

Steps 4 and 5: Build the Prompt Suite and Provider Adapters #

Step 4: Write prompts.py. A temperature test is only as informative as its prompts. A suite where every prompt has one obvious answer will show zero variance at every setting and teach you nothing. The six prompts here cover the range on purpose. The fact prompt has a single correct answer. The sentiment prompt is borderline, so the model can reasonably say neutral or negative. The JSON prompt tests format discipline. The summary prompt allows many valid wordings. The naming prompt invites creativity. The code prompt has a correct behavior but many valid spellings.

PROMPTS = [
    {"id": "fact", "kind": "short",
     "text": "What is the capital of Australia? Reply with the city name only."},
    {"id": "sentiment", "kind": "short",
     "text": "Classify the sentiment of this review as positive, negative or neutral. "
             "Reply with one word only. Review: The battery lasts two days but the screen scratches far too easily."},
    {"id": "json", "kind": "json", "keys": ["name", "city", "year"],
     "text": "Extract the fields from this text and reply with JSON only, using exactly the keys "
             "name, city and year. Text: Priya Nair opened her bakery in Leeds in 2019."},
    {"id": "summary", "kind": "long",
     "text": "Summarize the following in exactly two sentences. A password manager stores every login in an "
             "encrypted vault, fills credentials only on matching sites, generates long random passwords, "
             "and syncs the vault across devices so users remember a single master password."},
    {"id": "naming", "kind": "creative",
     "text": "Suggest one name for a coffee shop that sells only decaf. Reply with the name only."},
    {"id": "code", "kind": "code",
     "text": "Write a Python function slugify(title) that lowercases a string and replaces runs of "
             "non-alphanumeric characters with a single hyphen. Reply with code only."},
]

Each prompt carries a kind tag that the policy step uses later. If you add adversarial prompts to the suite, the prompt injection test lab tutorial shows how to score them, and the same runner will log them without changes. Keep every prompt short, because long prompts add cost without adding signal about sampling.

Step 5: Write providers.py. Three small functions hide the differences between the three SDKs behind one signature: provider, model, prompt, temperature and max tokens in, text out. Imports happen inside each function, so the dry run never needs the vendor packages installed. Each adapter catches the vendor’s bad-request error and re-raises it as Rejected, which the runner records instead of retrying. The Google adapter checks the status code first, since not every client error is a parameter problem.

import math
import os
import random
from functools import lru_cache

class Rejected(Exception):
    """The API refused the request, for example an unsupported temperature."""

@lru_cache(maxsize=None)
def _openai():
    from openai import OpenAI
    return OpenAI()

@lru_cache(maxsize=None)
def _anthropic():
    import anthropic
    return anthropic.Anthropic()

@lru_cache(maxsize=None)
def _google():
    from google import genai
    return genai.Client()

def call_openai(model, prompt, temperature, max_tokens):
    import openai
    try:
        r = _openai().chat.completions.create(
            model=model,
            messages=[{"role": "user", "content": prompt}],
            temperature=temperature,
            max_completion_tokens=max_tokens,
        )
    except openai.BadRequestError as e:
        raise Rejected(str(e)) from e
    return r.choices[0].message.content or ""

def call_anthropic(model, prompt, temperature, max_tokens):
    import anthropic
    try:
        r = _anthropic().messages.create(
            model=model,
            max_tokens=max_tokens,
            temperature=temperature,
            messages=[{"role": "user", "content": prompt}],
        )
    except anthropic.BadRequestError as e:
        raise Rejected(str(e)) from e
    return "".join(b.text for b in r.content if b.type == "text")

def call_google(model, prompt, temperature, max_tokens):
    from google.genai import errors, types
    try:
        r = _google().models.generate_content(
            model=model,
            contents=prompt,
            config=types.GenerateContentConfig(temperature=temperature, max_output_tokens=max_tokens),
        )
    except errors.ClientError as e:
        if e.code == 400:
            raise Rejected(str(e)) from e
        raise
    return r.text or ""

def call_fake(model, prompt, temperature, max_tokens):
    logits = [3.0, 2.0, 1.5, 1.0, 0.5]
    t = max(temperature, 0.05)
    weights = [math.exp(x / t) for x in logits]
    k = random.choices(range(len(logits)), weights=weights)[0]
    if "JSON" in prompt:
        if random.random() < 0.04 * temperature:
            return '{"name": "Priya Nair", "city": "Leeds"'
        return '{"name": "Priya Nair", "city": "Leeds", "year": %d}' % (2019 if k < 4 else 2018)
    return f"Answer variant {k}: " + " ".join(prompt.split()[:6])

DISPATCH = {"openai": call_openai, "anthropic": call_anthropic, "google": call_google, "fake": call_fake}

def generate(provider, model, prompt, temperature, max_tokens):
    return DISPATCH[provider](model, prompt, temperature, max_tokens)

The fake provider deserves a second look. It draws from five canned variants using the same softmax logic that real samplers use, so low temperatures concentrate on one variant and high temperatures spread out. It also corrupts the JSON output a few percent of the time at higher temperatures. That makes the dry run a faithful rehearsal of what the report will look like, though its numbers say nothing about real models.

Steps 6 to 8: Smoke Test, Pilot Run and Full Sweep #

Step 6: Run a smoke test. One call per model at temperature 0 proves that keys, model IDs and SDK calls all work before you commit to hundreds of requests. Save this as smoke.py.

import sys

import providers
from config import MAX_TOKENS, active_models

for key, m in active_models().items():
    text = providers.generate(m["provider"], m["model"], "Reply with the single word: ready", 0.0, MAX_TOKENS)
    print(f"{key:8} {m['model']:20} -> {text.strip()[:40]!r}")

Run it in dry mode first, then for real. The dry run prints one line per simulator, and the real run should print one line per vendor with a short reply.

$ DRY_RUN=1 python3 smoke.py
sim-a    sim-a                -> 'Answer variant 0: Reply with the single '
sim-b    sim-b                -> 'Answer variant 0: Reply with the single '

$ python3 smoke.py
gpt      gpt-6.2-sol          -> 'ready'
claude   (your Haiku 5.5 ID)  -> 'ready'
gemini   gemini-4-hydrogen    -> 'ready'

Step 7: Write runner.py. The runner loops over models, prompts, temperatures and trials, and appends one JSON line per call. It records the model ID, the Python version and the latency next to each output. Because it checks the file for finished combinations before each call, an interrupted run resumes where it stopped. A rejected request writes a single record and skips the remaining trials for that cell, so one unsupported temperature does not burn through your quota.

import json
import pathlib
import platform
import time

import providers
from config import MAX_TOKENS, TEMPERATURES, TRIALS, active_models
from prompts import PROMPTS

OUT = pathlib.Path("results/runs.jsonl")

def done_keys():
    keys = set()
    if OUT.exists():
        for line in OUT.read_text().splitlines():
            r = json.loads(line)
            keys.add((r["model_key"], r["prompt_id"], r["temperature"], r["trial"]))
    return keys

def with_retry(fn, attempts=4):
    for i in range(attempts):
        try:
            return fn()
        except providers.Rejected:
            raise
        except Exception:
            if i == attempts - 1:
                raise
            time.sleep(2 ** i)

def main():
    OUT.parent.mkdir(exist_ok=True)
    seen = done_keys()
    models = active_models()
    with OUT.open("a") as f:
        for mkey, m in models.items():
            for p in PROMPTS:
                for temp in TEMPERATURES:
                    for trial in range(TRIALS):
                        key = (mkey, p["id"], temp, trial)
                        if key in seen:
                            continue
                        rec = {"model_key": mkey, "model": m["model"], "prompt_id": p["id"],
                               "temperature": temp, "trial": trial, "python": platform.python_version()}
                        t0 = time.time()
                        try:
                            rec["output"] = with_retry(lambda: providers.generate(
                                m["provider"], m["model"], p["text"], temp, MAX_TOKENS))
                        except providers.Rejected as e:
                            rec["rejected"] = str(e)[:300]
                            rec["output"] = ""
                        rec["latency_s"] = round(time.time() - t0, 3)
                        f.write(json.dumps(rec) + "\n")
                        f.flush()
                        if "rejected" in rec:
                            break
    print("done:", OUT)

if __name__ == "__main__":
    main()

Start with a pilot. Run it with three trials, count the lines and check for rejections. The same logic applies in hardware testing, where the Quest 3 battery life test repeats a drain run several times because one measurement proves nothing about a device. A pilot catches setup mistakes cheaply.

$ TRIALS=3 python3 runner.py
done: results/runs.jsonl
$ wc -l results/runs.jsonl
162 results/runs.jsonl
$ grep -c rejected results/runs.jsonl
0

Step 8: Run the full sweep. Raise the trial count to ten and run again. Because the runner resumes, the pilot’s trials 0 through 2 stay in the file and only trials 3 through 9 are added. Start the job inside tmux or with nohup so a closed terminal does not kill it. Expect the file to end at 540 lines, plus any single rejection records.

$ TRIALS=10 nohup python3 runner.py > sweep.log 2>&1 &
$ tail -f sweep.log
done: results/runs.jsonl
$ wc -l results/runs.jsonl
540 results/runs.jsonl

If a nonzero rejection count shows up, open the file and read the rejected field. It holds the first 300 characters of the vendor’s error message, which usually names the offending parameter. Decide then whether to drop that temperature for the model or change the request, as covered in the troubleshooting section.

Steps 9 to 11: Score Variance, Build the Report and Set a Policy #

Step 9: Write metrics.py. Four numbers describe each cell. Exact match is the share of outputs that equal the most common output after whitespace and case are normalized. Distinct is the count of unique outputs. Similarity is the mean pairwise ratio from Python’s difflib across all output pairs. JSON OK is the share of replies that parse and contain the required keys, with code fences stripped first. Exact match is the strict metric and similarity is the forgiving one, and you need both because they fail in opposite ways.

import collections
import difflib
import itertools
import json
import re
import statistics

from prompts import PROMPTS

KINDS = {p["id"]: p for p in PROMPTS}

def norm(s):
    return " ".join(s.split()).strip().lower()

def similarity(outs):
    pairs = list(itertools.combinations(outs, 2))
    if not pairs:
        return 1.0
    return statistics.mean(difflib.SequenceMatcher(None, a, b).ratio() for a, b in pairs)

def json_ok(text, keys):
    text = re.sub(r"^```(?:json)?|```$", "", text.strip(), flags=re.M).strip()
    try:
        data = json.loads(text)
    except ValueError:
        return False
    return isinstance(data, dict) and all(k in data for k in keys)

def load(path="results/runs.jsonl"):
    groups = collections.defaultdict(list)
    with open(path) as f:
        for line in f:
            r = json.loads(line)
            groups[(r["model_key"], r["prompt_id"], r["temperature"])].append(r)
    return groups

def summarize(groups):
    rows = []
    for (mkey, pid, temp), recs in sorted(groups.items()):
        if any("rejected" in r for r in recs):
            rows.append({"model": mkey, "prompt": pid, "temp": temp, "n": 0, "status": "rejected"})
            continue
        outs = [norm(r["output"]) for r in recs]
        modal = collections.Counter(outs).most_common(1)[0][1]
        row = {"model": mkey, "prompt": pid, "temp": temp, "n": len(outs), "status": "ok",
               "exact": round(modal / len(outs), 2), "distinct": len(set(outs)),
               "sim": round(similarity(outs), 3),
               "len": round(statistics.mean(len(o) for o in outs), 1),
               "empty": sum(1 for o in outs if not o)}
        p = KINDS[pid]
        if p["kind"] == "json":
            row["json_ok"] = round(sum(json_ok(r["output"], p["keys"]) for r in recs) / len(recs), 2)
        rows.append(row)
    return rows

Two edge cases deserve a mention. When every output in a cell is empty, the modal share is 1.0 and the cell looks perfectly stable, so the empty count is part of the summary and you should read it before trusting a high exact-match rate. When a cell has only one distinct output, similarity is 1.0 by construction. In both situations the numbers are correct, and the interpretation is what needs care. A cell that is stable because it is broken is worse than a cell that varies.

Step 10: Write report.py. The report turns the metrics into a CSV for spreadsheets and a Markdown table for reading. Rejected cells show up as rows labeled rejected rather than disappearing, so nobody mistakes a missing row for a stable one.

import csv
import pathlib

from metrics import load, summarize

rows = summarize(load())
pathlib.Path("results").mkdir(exist_ok=True)
fields = ["model", "prompt", "temp", "n", "status", "exact", "distinct", "sim", "len", "empty", "json_ok"]
with open("results/summary.csv", "w", newline="") as f:
    w = csv.DictWriter(f, fieldnames=fields, extrasaction="ignore")
    w.writeheader()
    w.writerows(rows)

lines = ["| model | prompt | temp | exact | distinct | sim | json_ok |", "|---|---|---|---|---|---|---|"]
for r in rows:
    if r["status"] != "ok":
        lines.append(f"| {r['model']} | {r['prompt']} | {r['temp']} | rejected | | | |")
        continue
    lines.append(f"| {r['model']} | {r['prompt']} | {r['temp']} | {r['exact']} | {r['distinct']} | {r['sim']} | {r.get('json_ok', '')} |")
pathlib.Path("results/report.md").write_text("\n".join(lines) + "\n")
print("\n".join(lines))

Step 11: Write policy.py. The policy script converts measurements into a decision. For each model and prompt it finds the highest temperature that still clears a stability floor for that kind of task. Short answers and JSON need an exact-match rate of at least 0.9. Code and summaries need a similarity of at least 0.9. Creative prompts have no floor, so they get the highest temperature tested. JSON prompts must also keep a validity rate of at least 0.99.

import json

from metrics import KINDS, load, summarize

FLOORS = {"short": ("exact", 0.9), "json": ("exact", 0.9), "code": ("sim", 0.9), "long": ("sim", 0.9), "creative": None}
JSON_FLOOR = 0.99

best = {}
for r in summarize(load()):
    if r["status"] != "ok":
        continue
    key = f"{r['model']}:{r['prompt']}"
    best.setdefault(key, 0.0)
    rule = FLOORS[KINDS[r["prompt"]]["kind"]]
    ok = rule is None or r[rule[0]] >= rule[1]
    ok = ok and r.get("json_ok", 1.0) >= JSON_FLOOR
    if ok and r["temp"] > best[key]:
        best[key] = r["temp"]

json.dump(best, open("results/policy.json", "w"), indent=2, sort_keys=True)
print(json.dumps(best, indent=2, sort_keys=True))

Those floors are starting points, not laws. A payment-extraction step may need 0.99 and a brainstorming step may accept anything. Edit the FLOORS table to match what a bad answer costs you, and rerun the script. The output is a JSON file your application can load at startup, so temperature becomes configuration backed by evidence instead of a number someone typed once.

Step 12: Add a Stability Gate to CI #

A policy file goes stale the day a vendor updates a model. The last step turns the temperature-0 results into a test, so a regression fails a build instead of surprising a customer. The gate checks only the fact and JSON prompts, where a stable answer is a reasonable demand, and requires a similarity of at least 0.95 for each model.

import pytest

from metrics import load, summarize

ROWS = [r for r in summarize(load()) if r["status"] == "ok" and r["temp"] == 0.0 and r["prompt"] in ("fact", "json")]

@pytest.mark.parametrize("row", ROWS, ids=lambda r: f"{r['model']}-{r['prompt']}")
def test_temperature_zero_is_stable(row):
    assert row["sim"] >= 0.95
bash
$ python3 -m pytest -q test_stability.py
....                                                                     [100%]
4 passed in 0.11s

Schedule the harness nightly or on any change to a model ID, and commit the summary CSV so diffs show drift over time. Rerun the full sweep whenever a vendor announces a new snapshot. Vendors rotate model identifiers and routing rules, so a model name that worked last week may point at different weights today.

When the gate fails, resist the urge to lower the threshold. Look at the rows first. A drop at temperature 0 on the JSON prompt usually means a format regression, which matters more than any wording change. A drop on the fact prompt suggests the model started hedging or adding explanations. Both deserve a human look before the floor moves.

Reading the Output Without Fooling Yourself #

This excerpt comes from the offline simulator with ten trials per cell. The numbers show the shape of a real report, and they say nothing about GPT-6.2 Sol, Claude Haiku 5.5 or Gemini 4 Hydrogen. Your own LLM temperature run will fill in the real values.

Model Prompt Temp Exact Distinct Sim JSON OK
sim-a fact 0.0 1.0 1 1.0
sim-a fact 0.7 0.9 2 0.996
sim-a fact 1.0 0.5 4 0.986
sim-a json 0.0 1.0 1 1.0 1.0
sim-a json 0.7 1.0 1 1.0 1.0
sim-a json 1.0 0.8 3 0.964 0.9
sim-a naming 1.0 0.3 4 0.983

Look at the fact rows first. Exact match falls from 1.0 to 0.5 as temperature rises, but similarity barely moves, from 1.0 to 0.986. The simulator’s variants share most of their characters, which is also true of real answers that differ by a single word. If you judged stability by similarity alone, you would call every setting safe. Exact match exposes the change, and that is why the report carries both.

The JSON rows show the other failure. At 1.0 the validity rate drops to 0.9, meaning one reply in ten would crash a parser. A similarity of 0.964 hides that completely. For structured output, validity is the number that counts, and a single broken reply in ten is an outage if your code does not retry.

Now apply the policy logic to a concrete case. Suppose a classifier prompt shows exact match of 1.0 at 0 and 0.9 at 0.7, with a drop to 0.6 at 1.0. The highest setting that clears a 0.9 floor is 0.7, so the policy picks it. Whether to use it is a separate decision. If the 0.7 setting buys nothing your users can see, take 0 and the extra predictability. Temperature has no free gains on tasks with one right answer, so the policy script gives you a ceiling, not a recommendation to run at it.

Remember that ten trials is a small sample. An exact-match rate of 0.9 could plausibly be 0.6 or 0.99 on the next ten. Hardware reviewers face the same problem when they compare thermals, which is why a case fan airflow test repeats runs to separate real differences from run-to-run noise. Use the bootstrap snippet in the advanced section to put a confidence interval on any cell that drives a decision.

Common Pitfalls That Skew a Temperature Test #

  • Judging from one run. A single response at temperature 0 tells you nothing about variance. Ten is the floor for screening and thirty is better for any cell that decides a production setting.
  • Trusting similarity alone. Shared boilerplate inflates the score. Report exact match next to it, and add a validity check wherever the output has a format.
  • Starving the token budget. Reasoning and thinking models spend part of the limit on hidden tokens. A cap that is too low returns empty text that looks like perfect stability. The report counts empty outputs for this reason.
  • Changing two things at once. Moving temperature and top_p together, or switching thinking levels midway, makes the results uninterpretable. Change one variable per sweep.
  • Comparing models with different defaults. Gemini 4 Hydrogen defaults to a high thinking level. Another vendor’s default may be different, so a fair comparison pins the equivalent setting on each side or labels the difference.
  • Skipping the log metadata. Without the model ID, date and Python version beside each output, you cannot tell a real regression from a silent model update. The runner records them for you.
  • Testing only easy prompts. If every prompt has one obvious answer, even high temperatures look stable. Include borderline and open-ended prompts so the dial has something to move.
  • Running trials in parallel on a shared cache. Some platforms cache identical requests, which can return the same answer ten times and fake a perfect score. Keep the loop sequential or confirm the vendor does not cache sampled output.

Troubleshooting #

  • The API returns a 400 error about temperature. The runner logs it as a rejection and moves on. Read the rejected field, then remove that temperature for that model in config.py or leave the rejection in the report as the finding.
  • Outputs are empty for one model. Raise MAX_TOKENS. Thinking models can use the whole limit on reasoning before writing a word. Check the empty column in the CSV to spot it.
  • You get 429 rate-limit errors. The retry loop backs off for one, two and four seconds. If errors continue, add a short sleep between calls or lower your request rate in the vendor dashboard.
  • The script exits with a message to set MODEL_CLAUDE. The harness refuses to guess the Claude model ID. Copy it from the Claude Haiku 5.5 overview page and export it.
  • The API says the model was not found. Check for typos and for retired aliases. Vendors rotate names during busy release periods, so confirm the exact ID on the vendor’s current model page.
  • Authentication fails. Confirm the three key variables are exported in the same shell that runs Python. Google’s client reads GEMINI_API_KEY, and a stray space or quote around the value breaks all three.
  • ImportError on google.genai. Install google-genai, not the older google-generativeai package. They are different libraries and only the first provides the genai client used here.
  • JSON OK shows 0.0 for a model that looks fine. Print one raw output. Models sometimes add a sentence before the JSON, which the parser rejects. Tighten the prompt or loosen the parser, but do it for every model.
  • A rerun duplicates rows. It should not, because finished combinations are skipped. If it does, the temperature types may differ between runs, such as 0 and 0.0. Delete results/runs.jsonl and start clean.
  • pytest reports no tests or skips everything. The results file is missing or the rows list is empty, usually because the sweep has not run yet. Run the runner first, then the report.
  • Every model looks stable at every temperature. Your prompts are too easy, or the vendor ignores the parameter. Add a borderline prompt and check the raw outputs for real differences.
  • Results shift from one day to the next. The vendor may have swapped the model snapshot or changed routing. Compare the logged model IDs and dates, and rerun the pilot before blaming your code.

Advanced Tips for Deeper Temperature Testing #

Put a confidence interval on a cell. The bootstrap resamples your ten outputs thousands of times and shows how much the exact-match rate could move. Cells with wide intervals need more trials before they drive a decision.

import random
import statistics

from metrics import load, norm

def exact_ci(outputs, reps=2000):
    outs = [norm(o) for o in outputs]
    stats = []
    for _ in range(reps):
        sample = random.choices(outs, k=len(outs))
        stats.append(max(sample.count(x) for x in set(sample)) / len(sample))
    stats.sort()
    return stats[int(0.025 * reps)], statistics.mean(stats), stats[int(0.975 * reps)]

groups = load()
for key in [("sim-a", "fact", 1.0)]:
    lo, mid, hi = exact_ci([r["output"] for r in groups[key]])
    print(key, f"exact match {mid:.2f} (95% CI {lo:.2f} to {hi:.2f})")
bash
$ python3 bootstrap.py
('sim-a', 'fact', 1.0) exact match 0.54 (95% CI 0.30 to 0.80)

An interval from 0.30 to 0.80 says ten trials cannot distinguish a coin flip from a fairly stable model. Raise TRIALS to thirty for that cell and the band narrows. This single habit prevents the most common mistake in prompt tuning, which is celebrating a difference that sampling noise produced.

Run the sweep against a local model

Any server that speaks the OpenAI chat format works with the OpenAI adapter. Point the OPENAI_BASE_URL variable at it and set MODEL_GPT to the served model name. If you want to serve an open-weight model with vLLM, you can run unlimited trials at no per-token cost, which makes thirty or a hundred trials per cell practical. The harness does not change at all.

Add an adversarial dimension

Temperature interacts with safety behavior. A model that refuses an injected instruction at 0 may comply once in twenty tries at 1.0. Adding injection prompts to the suite turns this harness into a repeatability test for defenses. A Claude vs ChatGPT injection test shows how to build such prompts and score refusals, and the same variance metrics apply.

Use an LLM judge for meaning. Exact match and difflib treat two correct paraphrases as different. For summaries, a second model can score whether two outputs say the same thing. Keep the judge at temperature 0 and a fixed model ID, and spot-check its verdicts by hand.

Test the thinking level separately. Run the same sweep at two thinking levels on Gemini 4 Hydrogen and compare. The thinking level can move variance as much as temperature does, so measure it instead of assuming. Treat the pair as a grid and record both values in each log line.

Track cost per stable answer. Multiply tokens by price for each cell and divide by the exact-match rate. A cheaper model that needs two retries to reach a valid output can cost more than a pricier model that gets it right once.

The Complete Project at a Glance #

Everything above fits in ten files. The tree below is the finished layout, and the run script chains the steps in the right order so a full evaluation is one command after setup.

temp_lab/
  config.py          models, temperatures, trial count, dry-run switch
  prompts.py         six-prompt suite with kind tags
  providers.py       OpenAI, Anthropic, Google adapters plus simulator
  smoke.py           one call per model before the sweep
  runner.py          resumable sweep, writes results/runs.jsonl
  metrics.py         exact match, distinct, similarity, JSON validity
  report.py          results/summary.csv and results/report.md
  policy.py          results/policy.json, best temperature per task
  bootstrap.py       confidence intervals for any cell
  test_stability.py  pytest gate for temperature 0
  run_all.sh         chains every step
  results/
bash
#!/bin/sh
set -e
python3 smoke.py
TRIALS=3 python3 runner.py
python3 report.py > /dev/null
TRIALS=10 python3 runner.py
python3 report.py
python3 policy.py
python3 -m pytest -q test_stability.py

Run it first with DRY_RUN=1 to confirm every script works, then delete results/runs.jsonl so simulator rows do not mix with real ones. Run it again without the switch for the real sweep. The result is a CSV of every measurement, a Markdown table you can paste into a pull request, a policy file your app can load and a test that guards it.

Keep the results folder under version control, or at least archive each run with its date. A history of summary files turns into the most useful artifact in the project, because it shows exactly when a vendor changed behavior. That history answers questions like whether a regression began on a particular Tuesday, which no single run can.

Picking an LLM Temperature by Task Type #

Once the sweep finishes, let the policy file decide, and use these defaults only as a first guess before data arrives.

  • Extraction and classification: start at 0 and raise it only if the report shows no loss in exact match.
  • Structured JSON output: use the highest temperature that keeps validity at 0.99 or better, and add a retry for the rest.
  • Code generation: stay low. Similar code can still differ in ways that break tests, so check the diff behavior and not just the score.
  • Summaries and rewrites: a moderate value usually gives natural wording without drifting off the facts.
  • Naming and brainstorming: go high and generate several candidates, because variance is the feature here.
  • Reasoning models: tune the thinking level before temperature. If a vendor ignores or rejects the parameter, that tells you where the real control lies.

None of those rules replaces a measurement on your own prompts. A support-ticket classifier and a legal-clause extractor can behave differently on the same model at the same setting. Related model tutorials and test harnesses live in the AI and machine learning archive, and the same runner pattern extends to latency, refusal rate and cost per correct answer.

FAQ #

What does temperature 0 do in an LLM? It tells the sampler to pick the highest-probability token at each step instead of drawing from the distribution. Output becomes far more repeatable, though not guaranteed identical, because serving details can still flip near-ties.

Is temperature 0 fully deterministic? Not reliably. Batching, hardware differences and floating-point ordering can change which token wins a close call. Measure it with a sweep like the one above and treat any exact-match rate below 1.0 as real.

What LLM temperature should I use for JSON extraction? Start at 0 and test upward. Choose the highest value that keeps the validity rate at or above your floor, such as 0.99, and add a retry on parse failure for the remainder.

Does temperature work the same on GPT-6.2 Sol, Claude Haiku 5.5 and Gemini 4 Hydrogen? The official pages for these models do not say it does. Run the harness on each one, and treat a rejected value or a flat variance curve as a result worth recording.

How many trials do I need per cell? Ten works as a screen. For a cell that sets a production default, use thirty or more and report a bootstrap interval so the decision rests on more than a lucky streak.

Should I change temperature and top_p together? Vendors commonly advise against it, because the two interact. Change one per sweep and keep the other at its default so the results stay interpretable.

How often should I rerun the test? Run it nightly or whenever a model ID changes. Vendors rotate models and routing, so a stability result is only as fresh as its last run.

── more in #large-language-models 4 stories · sorted by recency
── more on @claude haiku 5.5 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/llm-temperature-test…] indexed:0 read:33min 2026-12-03 · —