Skip to article content
FrontendXLesson 03 / 20

Sampling parameters and determinism

Build LLM-backed product features end to end against a deterministic local mock: form well-formed chat requests, structure prompts and validated JSON outputs, stream and retry safely, ground answers in retrieved sources, call tools inside bounded agent loops, defend against prompt injection, and evaluate quality with reproducible checks instead of one-off demos. No API keys and no network calls are used anywhere in the course.

beginner · about 35 minutes · 4 exercises

  • Predict
  • Explain
  • Implement

What you will be able to do

#
  • Trace cumulative sampling over a fixed candidate table and predict the selected token for any given random value.
  • Explain what temperature and top_p change about the next-token distribution and what they do not change.
  • Normalize untrusted request parameters into a valid, total parameter set with clamping and defaults.

Overview

#

Generation is sampling, not lookup

Given a prompt, a language model produces a probability distribution over the next token, then samples from it. That sampling step is why the same prompt can produce different replies. The parameters on a chat request exist to control that step, and choosing them deliberately is a core AI engineering skill.

Temperature reshapes the distribution

Temperature rescales the distribution before sampling. Low temperature sharpens it (the top candidate dominates); high temperature flattens it (alternatives become more likely). The exact numbers below are an invented mock table for a prompt that asks for a capital city, not real model logits, but the shape is what matters:

TemperatureParisLyonNice
0.20.900.070.03
1.00.620.230.15

At temperature 0 the mock always returns the argmax, Paris. At temperature 1.0 all three candidates are plausible. To make sampling reproducible without a network, this course separates the distribution from the randomness: sampleFrom(candidates, r) takes the random number r as an explicit input, so you can hand-trace exactly which candidate wins for any r.

snippet.javascript
function sampleFrom(candidates, r) {
  let cumulative = 0;
  for (const c of candidates) {
    cumulative += c.p;
    if (r <= cumulative) return c.token;
  }
  return candidates[candidates.length - 1].token;
}

const t1 = [
  { token: "Paris", p: 0.62 },
  { token: "Lyon", p: 0.23 },
  { token: "Nice", p: 0.15 }
];
// sampleFrom(t1, 0.42) -> "Paris"   (0.42 <= 0.62)
// sampleFrom(t1, 0.73) -> "Lyon"    (0.62 < 0.73 <= 0.85)
// sampleFrom(t1, 0.90) -> "Nice"    (0.85 < 0.90 <= 1.00)

top_p (nucleus sampling) is a complementary control: instead of scaling the distribution, it keeps the smallest set of top candidates whose probabilities sum to at least p and samples only from that set. Temperature and top_p are usually tuned together, and most teams fix one and adjust the other.

Length and stopping

maxOutputTokens hard-caps generation. When the cap is hit, the response does not error: it returns truncated text with a finish reason such as length instead of stop. Production code must check the finish reason, because a silently truncated JSON payload is a downstream parse bug waiting to happen (lesson 5). Stop sequences are strings that end generation early, useful when a model tends to keep talking after the answer.

Determinism, reproducibility and honesty about both

Three statements with different truth values:

  1. Temperature 0 removes sampling randomness. True by definition of the sampling step.
  2. Temperature 0 guarantees byte-identical outputs across calls. False in general. Real serving stacks batch requests and run on parallel hardware, so even near-deterministic settings can occasionally differ; some providers expose a seed parameter that narrows but does not always eliminate this.
  3. Deterministic outputs are correct outputs. False. A model can be confidently wrong at temperature 0. Reproducibility helps debugging and testing; it says nothing about accuracy.

The practical policy: use temperature 0 (plus a seed when supported) for extraction, classification, structured output and anything a test suite depends on; use higher temperature for brainstorming and copy variants; and never rely on determinism you have not measured. Lesson 13 turns "never rely on unmeasured determinism" into an evaluation habit.

Defaults are a product decision

A request without explicit parameters inherits the provider's defaults, which can change. Serious teams pin parameters in a config module and treat changes to them like any other production change: reviewed, evaluated, and rolled out deliberately. The exercise below builds that config boundary as a small, total function: every input maps to a valid parameter set, with no exceptions thrown for out-of-range values.

Continue with ai-engineering-tokens-context-and-cost to see where sampling randomness, token budgets and cost intersect.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Implement

    Implement sampleFrom(candidates, r). candidates is an array of { token, p } whose probabilities sum to 1. Walk the array accumulating p; return the first token where r <= cumulative. If no candidate matches (floating-point slack), return the last token.

    starter.javascript
    function sampleFrom(candidates, r) {
      // Walk candidates accumulating p; return the first token where
      // r <= cumulative. Fall back to the last token.
    }

    Reveal the reference answer
    reference.javascript
    function sampleFrom(candidates, r) {
      let cumulative = 0;
      for (const c of candidates) {
        cumulative += c.p;
        if (r <= cumulative) return c.token;
      }
      return candidates[candidates.length - 1].token;
    }

    Authored expected output: Lyon

    Sampling from a categorical distribution reduces to a cumulative walk: pick the first boundary that exceeds the random value. Making r an explicit argument is what lets you test the sampler deterministically.

  2. Exercise 2Predict

    Using the temperature 1.0 table (Paris 0.62, Lyon 0.23, Nice 0.15) and the boundary rule r <= cumulative, predict the four logged tokens for r values 0.42, 0.73, 0.9 and 0.62.

    starter.javascript
    const t1 = [
      { token: "Paris", p: 0.62 },
      { token: "Lyon", p: 0.23 },
      { token: "Nice", p: 0.15 }
    ];
    
    for (const r of [0.42, 0.73, 0.9, 0.62]) {
      console.log(sampleFrom(t1, r));
    }

    Reveal the reference answer
    reference.javascript
    // Predicted output:
    //
    // Paris
    // Lyon
    // Nice
    // Paris
    //
    // Trace: cumulative boundaries are 0.62, 0.85, then 1.00 (last-token
    // fallback). 0.42 <= 0.62 -> Paris. 0.73 <= 0.85 -> Lyon. 0.9 <= 1.00 ->
    // Nice. 0.62 <= 0.62 hits the first boundary exactly, and the stated rule
    // is r <= cumulative, so Paris.

    Authored expected output: Paris Lyon Nice Paris

    Boundaries are 0.62, 0.85 and 1.00. r=0.42 lands in Paris, 0.73 in Lyon, 0.9 in Nice, and 0.62 hits the first boundary exactly, which the <= rule assigns to Paris. Boundary rules must be stated explicitly or edge cases become ambiguity.

  3. Exercise 3Implement

    Implement normalizeParams(params) that returns a total, valid parameter object: temperature defaults to 0 and clamps to [0, 2]; topP defaults to 1 and clamps to [0, 1]; maxOutputTokens defaults to 300, is floored to an integer and clamps to a minimum of 1; stream defaults to false. Missing or invalid fields must never throw.

    starter.javascript
    function normalizeParams(params) {
      // Return { temperature, topP, maxOutputTokens, stream } with:
      // temperature: default 0, clamped to [0, 2]
      // topP: default 1, clamped to [0, 1]
      // maxOutputTokens: default 300, floored, minimum 1
      // stream: default false
      // Never throw for missing or out-of-range input.
    }

    Reveal the reference answer
    reference.javascript
    function clamp(n, min, max) {
      return Math.min(max, Math.max(min, n));
    }
    
    function normalizeParams(params) {
      const p = params || {};
      const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
      return {
        temperature: clamp(num(p.temperature) ?? 0, 0, 2),
        topP: clamp(num(p.topP) ?? 1, 0, 1),
        maxOutputTokens: Math.max(1, Math.floor(num(p.maxOutputTokens) ?? 300)),
        stream: p.stream === true
      };
    }
    
    console.log(JSON.stringify(normalizeParams({ temperature: 3.5, maxOutputTokens: 12.7 })));

    Authored expected output: {"temperature":2,"topP":1,"maxOutputTokens":12,"stream":false}

    normalizeParams({ temperature: 3.5, maxOutputTokens: 12.7 }) clamps temperature to 2, keeps topP at its default 1, floors 12.7 to 12, and defaults stream to false. A total normalization function at the boundary keeps bad input from reaching the provider.

  4. Exercise 4Explain

    Knowledge check: which change most directly makes model outputs reproducible for a test suite?

    starter.text
    // Choose the correct option.

    Reveal the reference answer
    reference.text
    Setting temperature to 0 and using a fixed seed where the provider supports one. This removes sampling randomness, though serving-stack effects can still cause rare differences, so tests should tolerate or detect them rather than assume byte-identical output.

    Authored expected output: Temperature 0 with a fixed seed where supported

    The other options change length, delivery or context, not the sampling step that produces variability.

Common misconceptions

#
  • Myth: temperature 0 guarantees byte-identical outputs on every call. Fact: it removes sampling randomness, but serving-stack nondeterminism can still cause occasional differences; measure rather than assume.
  • Myth: temperature and top_p are the same knob with two names. Fact: temperature rescales the distribution, top_p truncates it to a nucleus; they are complementary and usually tuned together.
  • Myth: hitting maxOutputTokens raises an error. Fact: generation stops and the response returns truncated text with a finish reason such as length; callers must check it.

Follow-up practice

#
  • ai-engineering-tokens-context-and-cost

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.