All lessons in AI Engineering: From Foundation Models to Evaluated Applications

Sampling, Context Windows, and Uncertainty

Design repeated trials and explain why fluent outputs can still be incorrect.

60 minutes · Free lesson

What you will learn

  • Distinguish token-selection variability from missing evidence and application failures.
  • Design repeated trials that report both successful calls and consistently successful tasks.
  • Allocate a context budget and make a reproducibility claim with explicit limits.

You ask the support assistant the same question three times. Twice it cites the right policy; once it confidently invents an exception. Reducing a sampling setting changes the wording but does not remove every error. To improve the application, you need to understand which variation comes from decoding, which comes from changing inputs, and which reflects a consistently wrong interpretation.

The previous lesson separated training from inference. Here you examine the choices and limits inside an inference request, then design a small repeated-trial experiment. The separate P03 practice turns these ideas into evaluation records. Every distribution and result in this lesson is invented teaching data; none is a measured property of a commercial model.

From token scores to a response

At each generation step, a language model computes scores for candidate next tokens. A decoding procedure selects a token, adds it to the sequence, and continues until a stopping condition is reached. One early choice can change the context for later choices, so output variability is more complicated than swapping a few adjectives in an otherwise fixed answer.

A greedy choice selects a highest-scoring token at each step. A sampled choice can select other tokens with nonzero probability. Neither procedure directly verifies whether the resulting response is true. If the highest-scoring continuation contains a wrong policy assumption, consistently choosing it produces a repeatable error.

Temperature is a common control on how sharply scores are converted into a distribution. For positive temperature, dividing logits by a smaller value before normalization typically concentrates probability on high-scoring candidates. A larger value typically spreads it more broadly. Supported values, defaults, and interactions vary by model and endpoint, so use the documented configuration rather than assuming one universal scale.

Top-k filtering retains a specified number of high-ranking candidates. Top-p filtering retains a set whose cumulative probability reaches a specified threshold, under the implementation's rule. These techniques constrain candidate selection. They are not factuality scores and do not make unsupported facts safe to use.

For a toy distribution with probabilities 0.60, 0.25, 0.10, and 0.05, retaining the two highest candidates leaves probability mass 0.85. Renormalization gives probabilities 0.60 / 0.85, approximately 0.706, and 0.25 / 0.85, approximately 0.294. The second candidate can still be selected. A retained candidate is not certified correct simply because filtering preserved it.

Do not change several decoding controls at once when diagnosing variability. Fix the prompt, context, model version, and other settings; then vary one control and record the actual behavior. If the endpoint ignores or rejects a setting, record that fact. A configuration file alone is not evidence that the provider applied every requested value.

Separate variability from uncertainty

Variability means outputs differ across calls. Uncertainty concerns how much confidence you can place in a conclusion given available evidence. They are related but distinct. A system can vary in wording while preserving the same correct decision, or repeat one unsupported answer with perfect consistency.

A model's statement that it is 95% confident is generated text unless your application has defined and validated a separate calibration procedure. Do not treat that number as a measured probability of correctness. Similarly, a token probability describes a token choice under a model and context, not automatically the probability that a whole factual claim is true.

For the support assistant, classify uncertainty by cause. A delivery date may be missing from the user input. A damage exception may be absent from the policy. Two supplied policy versions may conflict. The retrieved passage may be irrelevant. Each cause suggests a different response: ask a question, escalate, resolve the source version, or improve retrieval.

ObservationPlausible causeFirst check
Different wording, same correct decisionHarmless surface variationGrade meaning and evidence, not exact prose
Alternating eligibility decisionsUnstable interpretation or changing evidenceFreeze inputs and inspect decision criteria
Same wrong rule every timeSystematic missing or misused evidenceCompare supplied policy with expected rule
Truncated answerOutput or context limitInspect stop reason and configured limits
Missing resultTransport or runtime failureInspect timeout and failure records

Some tasks allow several acceptable answers. If a customer asks what to do next, either a clear request for the delivery date or a link to a form collecting that date may satisfy the contract. Your grader should recognize that flexibility. Exact string equality can falsely label harmless wording changes as failures.

Other outputs require exactness. An order identifier, currency amount, or action status should not vary freely. Use schema validation, trusted lookups, and explicit calculations where possible. Reserve semantic grading for dimensions that actually need it. This produces a clearer experiment than asking one broad model judge whether the answer looks good.

Treat the context window as a constrained input

A context window is a capacity limit on information represented for a model request under the model's accounting rules. It is not unlimited memory. Your application chooses what history and evidence to include, and some endpoints impose separate input and output limits. Verify the rules for the selected interface.

When a conversation grows, copying every earlier message eventually becomes impractical. Older messages may include resolved questions, obsolete policy, irrelevant details, or instructions that should not govern the current task. A deliberate context policy selects what is still useful and authorized. Blindly keeping everything can increase cost while making the answer harder to evaluate.

A summary can reduce size, but it can also lose qualifications or introduce unsupported statements. Treat a summary as a derived artifact with provenance. Preserve exact facts that drive decisions, such as the verified order ID and the policy version. If a summary says a refund was approved, verify that against recorded action state rather than trusting prose.

Truncation needs a documented priority rule. For the support assistant, preserve the active user question, authoritative task instructions, the relevant policy condition and exception, and current verified order facts. Remove irrelevant earlier conversation before dropping the exception that changes eligibility. If required evidence still does not fit, ask a narrower question or return an explicit inability to complete the task within the current request.

Context position can also affect results. Test whether a critical clause remains usable when placed near the beginning, middle, and end of a longer packet. These are experiments on your system, not a claim that one placement universally works best. The point is to discover whether your context assembly is brittle under realistic changes.

Keep capacity tests separate from task tests. A request may be accepted by an endpoint yet produce a wrong answer. Another may be rejected before generation because its input is too large. Report both outcomes, since the remedies differ. Increasing a limit can address rejection without fixing evidence use.

Design repeated trials around the user task

A repeated-trial evaluation runs the same defined task more than once under a recorded configuration. It reveals instability that one call can hide. Keep all attempts, including parse failures, timeouts, and refusals. Do not keep rerunning until a pleasing response appears and then report only that response.

Decide what one trial means. For a simple policy answer, a trial may be one request. For a workflow with clarification, a trial may include several turns and a final state. Reset synthetic state between independent trials unless persistence is explicitly part of the task being tested. Otherwise the second attempt may inherit a ticket created by the first.

Two useful summaries answer different questions. Call-level success measures successful attempts divided by total attempts. All-trials success measures the fraction of tasks that succeed on every scheduled repeat. The latter is stricter and can expose tasks whose average success looks acceptable but whose behavior is unreliable.

Worked example

Compare average success with dependable task completion

  1. Evaluate four synthetic policy questions, each with five independent attempts. Task A succeeds five times, B five times, C four times, and D twice.
  2. Total successful attempts are 5 + 5 + 4 + 2 = 16 out of 20. Call-level success is 16 / 20 = 80%.
  3. Only A and B succeed on all five attempts. All-trials task success is 2 / 4 = 50%.
  4. C succeeds on 4 / 5 = 80% of its attempts; D succeeds on 2 / 5 = 40%. These task-level results identify where to inspect failures.
  5. Suppose one of D's failed attempts timed out. It remains a failed scheduled attempt in the denominator. Report it as a runtime failure rather than deleting it.
  6. If you choose one successful answer from each task, the selected examples make success appear to be 4 / 4 = 100%. That number describes selection, not the observed reliability of the application.
  7. The twenty attempts are a small diagnostic set. Repeats of four tasks do not provide the same coverage as twenty distinct representative tasks; expand both task diversity and repeated measurements deliberately.

Do not assume attempts are statistically independent merely because they are separate HTTP calls. They share prompts, task difficulty, infrastructure, and potentially model-side behavior. For a simple classroom report, show raw task-by-trial results and avoid elaborate confidence claims. More advanced statistical work must account for the sampling design and unit of analysis.

Critical failures deserve their own count. One unauthorized action among twenty attempts is not made acceptable by a high average score. Repeated trials help you discover such failures, but observing zero does not prove the true failure probability is zero. Describe exactly what was tested and the limits of that evidence.

Record reproducibility and recover from failures

A reproducible evaluation record includes the task ID, evidence version, prompt or application revision, model identifier, supported generation settings, trial number, timestamp, outcome, and relevant timing. Record the response or an approved redacted artifact where appropriate. Do not place API keys or unrelated customer information in the log.

If the provider supports a seed, record it when used, but do not promise identical outputs across different model versions, hardware, or provider implementations. A seed is one control among several. Exact reproducibility and meaningful comparability are separate goals; a well-documented comparison can still be useful when outputs are not bit-for-bit identical.

For a failure, preserve the smallest useful reproduction. Keep the question, necessary authorized evidence, configuration, and expected outcome. Remove irrelevant private details. Ask whether the failure persists with the same context, whether a deterministic check can catch it, and whether the user receives a useful fallback.

Recovery should match the failure class. A malformed output might be rejected and retried once under an explicit budget. Missing facts require clarification, not repeated guessing. A transport timeout requires an uncertainty-aware retry policy, especially if an action may already have completed. Later lessons handle action idempotency; here, recognize that another call is not a universal repair.

Use the local reference's default demo mode to distinguish software determinism from model behavior. Its fixed workflow can produce repeatable responses without sampling because it does not make a model call. That is valuable for testing API boundaries. It is not evidence that an external model will behave identically. When running live trials, label them separately and record the provider configuration.

A sensible experiment sheet has one row per scheduled attempt and no blank unexplained outcomes. Add a short interpretation: which failure dominates, what one change you propose, and which existing cases could regress. This keeps the next iteration tied to evidence instead of to whichever output was most memorable.

Exercise

Five tasks are each run four times. Their success counts are 4, 3, 4, 1, and 4. Calculate call-level success and all-trials task success. Explain why they differ.

Check your answer

Successful calls total 4 + 3 + 4 + 1 + 4 = 16 of 20, so call-level success is 80%. Three tasks succeed on every repeat, so all-trials task success is 3 / 5 = 60%. The first metric averages attempts; the second asks whether each task was consistently successful across its scheduled attempts. Neither alone explains the cause of the failures.

Exercise

A hypothetical request allows 10,000 combined tokens. Instructions and schema use 1,000, the current question 200, output reserve 1,300, and required evidence 3,000. A 500-token margin is required. How much history fits? What should happen if history currently uses 5,500 tokens?

Check your answer

History can use 10,000 − 1,000 − 200 − 1,300 − 3,000 − 500 = 4,000 tokens. Remove or deliberately summarize at least 1,500 tokens of history. Preserve verified decision facts and required policy evidence. Do not silently delete an exception or reduce the output reserve without checking whether the task remains feasible.

Exercise

An assistant returns the same unsupported refund promise in ten attempts with a low-variability configuration. A teammate proposes making the configuration even less variable. Explain a better diagnostic and the appropriate user-facing behavior while investigating.

Check your answer

The repeated promise indicates a systematic error under the tested inputs, not a problem solved merely by reducing variation. Check whether the refund policy was supplied, whether the instruction permits unsupported promises, and whether action claims are validated against actual state. The application should avoid promising a refund, explain the evidence limit, and route to the approved support process until a tested repair exists.

Audit confidence against observed correctness

Language Models (Mostly) Know What They Know studies model self-evaluation and reports limitations when transferring calibration to new tasks. Treat a confidence estimate as a hypothesis to test on your workload. Fluent wording, a high token probability, and a correct business decision are different observations.

Group outputs by declared confidence and compare each group's average forecast with labeled outcomes. Keep the grouping rule fixed before inspecting the result. A tiny group can produce a dramatic gap by chance, so report its size and gather more independent cases before setting an automated action threshold.

Worked example

Read a small reliability table

  1. In a synthetic evaluation, 20 answers assigned confidence 0.9 contain 14 correct answers. Observed accuracy is 14 / 20 = 0.70.
  2. Another 20 answers assigned confidence 0.6 contain 12 correct answers: 0.60 observed accuracy.
  3. The first group is overconfident by 0.20 on this sample; the second matches its average forecast.
  4. Routing all 0.9 answers directly to customers would still send six incorrect answers in this sample.
  5. Review the high-confidence errors by task type. A pooled score can hide a systematic failure on one policy exception.

Exercise

You change the corpus and begin serving a new language. Can yesterday's confidence threshold retain its old interpretation without checking outcomes?

Check your answer

No. The task distribution and evidence have changed. Collect labeled cases for the new conditions, inspect calibration and task success separately, and retain a fallback while the threshold lacks supporting evidence.

Sources and further reading

Summary

Decoding controls influence token selection, not the truth of an answer. Distinguish harmless wording variation, unstable decisions, missing evidence, and runtime failures. Budget context deliberately and record every scheduled trial. Report both average success and task-level consistency, with explicit limits on reproducibility and on what a small experiment can establish.

Next action

Continue to Model Interfaces and Application Contracts. Bring the repeated-trial record design to P03, Build an Evaluation Harness, where you will preserve task, trial, configuration, and failure information in runnable checks.

Choose another lesson