Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
GimmeJob
Sign in
Generative AI & LLM · Chapter 09 / 20

Generative AI & LLM

Why LLM testing is different

Testing software that uses a large language model (LLM) breaks several assumptions that classic test design relies on. The same input can produce different outputs. A wrong answer looks as fluent and confident as a right one. The expected result is often not a single value but a space of acceptable answers. And the behaviour can change without any change to your code, because the model, the prompt, the retrieved data or the provider's infrastructure changed.

This chapter defines the problem precisely. It introduces the kinds of test oracles that work for generative output, the quality characteristics you will measure, and the lifecycle in which LLM testing happens. Later evaluation and testing chapters build on these definitions.

Prerequisites: Generative AI and LLM overview, How LLMs generate text, and basic software-testing concepts (test basis, test oracle, test levels) from QA fundamentals, and enough Python to read short scripts.

What we mean by an LLM system

A large language model is a neural network trained to predict the next token of text. In this course "the model" always means that component: a set of weights served behind an API, either by a provider or by your own infrastructure.

An LLM system (or LLM application) is the software built around one or more model calls. It includes prompts, context assembly, retrieval, tools, output parsing, guardrails, user interface, logging and the data the system reads. An LLM feature is one user-facing capability of that system, for example "answer questions about the return policy".

User and business outcome        (did the customer get a correct, safe answer?)
          ▲
Product feature                  (support assistant answers refund questions)
          ▲
LLM application                  (prompt templates, retrieval, tools, parsing, guardrails, UI)
          ▲
Model                            (weights, decoding, provider-side system behaviour)
          ▲
Training data and training process

Each layer has its own testers and its own questions:

LayerTypical questionWho usually answers itTypical evidence
ModelHow capable is this model at reasoning, coding or a language?Model provider, research teamsPublic benchmarks, model cards, red-team reports
ApplicationDoes our prompt, retrieval and parsing produce correct output for our inputs?Product engineering and QAEvaluation datasets, scorers, unit and integration tests
FeatureDoes the feature meet its acceptance criteria and risk limits?QA, product ownerAcceptance criteria with thresholds, regression results
OutcomeAre users actually helped, and is anyone harmed?Product, analytics, QAProduction monitoring, feedback, incident data

Most testers work on the application and feature layers. You rarely control model weights, but you control almost everything else: which model and version you call, the prompts, the data you retrieve, the tools you expose, how you validate output and how you monitor production. That is where most defects live and where this course focuses.

How LLM features differ from conventional features

The table compares a conventional feature, such as a price calculator, with an LLM feature, such as an assistant that answers price questions in natural language.

DimensionConventional featureLLM feature
SpecificationPrecise rules: "discount is 10% above 100 EUR"Open-ended intent: "answer helpfully and correctly"
Output spaceSmall and structured: a numberPractically infinite: any text
DeterminismSame input, same outputSame input can give different outputs
Typical failureException, wrong number, crashPlausible, fluent, wrong or unsafe answer
What can change behaviourCode and configurationCode, prompt, model version, retrieved data, tools, provider infrastructure
Input coverageEquivalence partitions of a small input spaceSemantic space of all ways users phrase things
Cost of a test runUsually negligibleReal money and seconds per call

Three consequences follow, and they shape the rest of the course:

  • Exact expected values rarely work. You need other kinds of oracles (next section).
  • One run is a sample, not a verdict. You must run cases repeatedly and reason about rates (see Statistics for evaluation).
  • Behaviour can drift with no code change. You must pin and record versions and keep testing in production (see Production quality).

The test oracle problem

A test oracle is the source you use to decide whether an observed result is correct. In a classic test the oracle is usually an expected value written in the test: assert total == 90.0.

For generative output this breaks down. Ask a model to summarize a two-page support ticket and there are thousands of correct summaries. There is no single string to compare against, and a summary can be partly right: four correct facts and one invented one. This is the oracle problem, long known in software testing research for programs whose correct output is hard to compute, and it is the central problem of LLM testing.

LLM testing replaces the single expected value with a combination of weaker oracles. Each one checks part of the correctness, and together they give useful confidence.

Oracle typeWhat it checksExampleStrengthWeakness
Property (specified constraint)Rules every correct output must satisfyOutput is valid JSON; mentions the order ID; under 80 wordsCheap, deterministic, preciseOnly partial: a valid output can still be wrong
Reference-basedCloseness to a known good answer or its factsAnswer contains the fact "30-day return window"Works well for factual tasksNeeds labelled references; wording varies
Model-based (LLM-as-a-judge)A second model grades against a rubric"Is every claim supported by the policy text? PASS or FAIL"Scales semantic judgementThe judge is itself a model and must be validated
Human judgementExperts label outputsSupport lead marks answers acceptable or notGround truth for subjective criteriaSlow, expensive, can be inconsistent
Metamorphic relationHow outputs must relate across changed inputsA paraphrased question must yield the same factsNo need to know the right answerDetects inconsistency, not correctness
Differential (comparative)Output compared with another versionNew prompt vs current prompt, judged pairwiseDirectly answers "is it better?"Says nothing about absolute quality

Worked example: property oracles for one answer

Suppose the requirement is: "Answers about returns must state the 30-day return window, must not promise more than the policy allows, must stay under 80 words and must link to the returns page." Each clause becomes a property check. None of them proves that an answer is good, but each one catches a class of bad answers cheaply.

Python
editable · browser sandbox
Result
Run the code to see the result.

Output:

answer 1: PASS
answer 2: FAIL: does not state the 30-day return window; promises more than the policy allows; does not link to the returns page
answer 3: FAIL: longer than 80 words

Notice what the checks cannot do. An answer that says "within 30 days of purchase" when the policy says "of delivery" passes all four checks and is still wrong. Catching that needs a reference-based or model-based oracle that compares the answer with the policy text. Real evaluation suites layer several oracle types for exactly this reason.

Sources of variability

When an LLM feature gives a different result today than yesterday, one of these sources is responsible:

SourceMechanismTest design consequence
SamplingThe model samples tokens from a probability distribution; with temperature above 0 different runs pick different tokensRun each case several times and measure rates
Inference non-determinismEven with temperature 0, GPU arithmetic, batching and hardware differences can change resultsNever assume a fixed output, even for "deterministic" settings
Model versionThe provider releases a new snapshot, or an alias such as "latest" movesPin exact model versions; re-run the suite before switching
Prompt and configurationSomeone edits a prompt, a parameter or a tool descriptionVersion prompts like code and evaluate every change
Retrieved contextThe document index changes, so retrieval returns different chunksRecord retrieved IDs in traces; freeze context for regression tests
Tools and external dataAPIs return different data over timeUse fakes and recorded responses in tests
Conversation stateEarlier turns, memory or user profile change the contextTest multi-turn scenarios and state boundaries explicitly

Model drift is not hypothetical. A widely cited 2023 study measured the same API model versions three months apart and found large changes in behaviour on several tasks (Chen, Zaharia and Zou). Providers now offer pinned snapshots precisely so that you can control when a change reaches you.

Diagnosing a change with no deployment

When an answer changes although nobody deployed code, compare the traces of a good run and a bad run field by field:

Evidence in the tracesWhat a difference means
Same input, answers alternate on re-runsSampling variability: measure the rate instead of judging one run
Different model version or serving fingerprintProvider update or a moved model alias
Different retrieved chunk IDsThe document index changed
Different prompt versionA prompt was changed outside the code release, for example in a prompt-management tool
Different conversation history or user profileState-dependent behaviour
Different tool resultsAn external system returned other data

Every row needs traces that record versions and context, which is why Production quality treats tracing as a testing prerequisite.

Why one passing run is weak evidence

If a feature is correct with probability p on each independent run, the probability that k manual tries all look correct is p to the power k. The script below shows how easily a flawed feature survives a quick manual check, and how the observed pass rate only settles near the true rate after many runs.

Python
editable · browser sandbox
Result
Run the code to see the result.

Output:

feature correct 95% of the time -> 3 tries all pass with probability 0.86
feature correct 95% of the time -> 5 tries all pass with probability 0.77
feature correct 90% of the time -> 3 tries all pass with probability 0.73
feature correct 90% of the time -> 5 tries all pass with probability 0.59
feature correct 70% of the time -> 3 tries all pass with probability 0.34
feature correct 70% of the time -> 5 tries all pass with probability 0.17
   10 runs: observed pass rate 1.000
  100 runs: observed pass rate 0.900
 1000 runs: observed pass rate 0.894
10000 runs: observed pass rate 0.904

A feature that fails one time in ten passes five manual tries more often than not, and in this simulation even ten runs showed a perfect score. Quality claims about LLM features are statements about rates, and rates need samples. The next subsection shows how many runs such claims need, and Statistics for evaluation shows how to put error bars on them and compare versions.

How many runs reveal a rare failure?

The same arithmetic answers a planning question: how many independent runs are needed to see a failure at least once? If a feature fails with probability q per run, the chance of seeing no failure in n runs is (1 − q)^n. Requiring at least a 95% chance of seeing a failure gives n ≥ log(0.05) / log(1 − q).

Python
editable · browser sandbox
Result
Run the code to see the result.

Output:

failure rate 20%: need 14 runs
failure rate 5%: need 59 runs
failure rate 1%: need 299 runs
80%-correct feature passes 4 manual checks with probability 0.41

Rare failures need many runs to appear even once. This is why evaluation datasets have hundreds of cases and why production monitoring is necessary.

Quality characteristics of LLM features

To test something you first have to say what "good" means. The characteristics below are the ones you will measure throughout this course. They extend the classic software quality model of ISO/IEC 25010; ISO/IEC 25059 adapts that model to AI systems.

CharacteristicQuestion it answersExample failureTypical evidence
Task success (correctness)Did the output accomplish the task correctly?Wrong refund amount computedReference checks, judges, human labels
Faithfulness (groundedness)Is every claim supported by the provided sources?Answer cites a policy clause that does not existClaim-level judge against retrieved context
RelevanceDoes the output address what was asked?Correct facts about shipping when the user asked about returnsRelevance judge, human review
CompletenessIs everything required present?Omits the exception for discounted itemsChecklist of expected facts
Format complianceDoes output follow the required structure?JSON with a missing fieldSchema validation
Consistency and robustnessIs behaviour stable across paraphrases, typos and noise?Different answers to two phrasings of one questionMetamorphic tests, repeated runs
SafetyDoes the system avoid harmful content and actions?Gives dangerous instructionsSafety classifiers, red-team datasets
SecurityDoes it resist manipulation and protect data?Follows instructions hidden in a retrieved web pagePrompt-injection tests, leakage tests
FairnessIs quality equal across user groups?Lower-quality answers for non-English namesCounterfactual tests by group
PrivacyIs personal data handled correctly?Reveals another customer's addressLeakage tests, PII scanners
LatencyIs it fast enough for the use case?12 seconds to first token in a chatTime to first token, p95 latency
CostIs it affordable at expected volume?Prompt grows to 9,000 tokens per requestToken accounting per request and per task

Not every feature needs every characteristic. A code-review assistant used by engineers may tolerate 10 seconds of latency but not invented APIs. A public chat widget must be fast and safe first.

From a vague requirement to testable criteria

Requirements for LLM features usually arrive vague: "The assistant should give helpful answers about refunds." This cannot be tested as written. The process below turns it into criteria that can.

1. Users and tasks      Who asks what, in which language, with what goal?
        ↓
2. Risks                What happens if the answer is wrong, unsafe, slow or leaks data?
        ↓
3. Characteristics      Which quality characteristics matter for these risks?
        ↓
4. Criteria             Measurable statement + measurement method + threshold + priority
        ↓
5. Evidence plan        Which data, scorers and reviews will produce the measurements?

Worked example: the refund assistant

Step 1, users and tasks. Customers of the fictional shoe store Stride ask about returns and refunds in English and Ukrainian. They want to know whether they can return an item, by when, and how.

Step 2, risks. A wrong "yes" creates a promise the company must honour or a customer conflict. A wrong "no" loses a sale. Answers that reveal another customer's order are a privacy incident. Slow answers make people abandon the chat.

Step 3, characteristics. Faithfulness to the policy, correct abstention when the policy does not cover a case, format, language, privacy and latency.

Step 4, criteria.

IDCriterionMeasurementThresholdPriority
R1Every policy statement is supported by the current policy documentFaithfulness judge validated against 100 human labelsAt least 97% of evaluation cases passCritical
R2When the policy does not cover the question, the assistant says it cannot confirm and offers a human agentAbstention check on 40 out-of-policy questionsAt least 95%High
R3Answer is at most 120 words and links to the returns pageDeterministic checks100%Medium
R4Answer language matches the question languageScript-based language checkAt least 99%High
R5No answer contains another customer's personal dataLeakage test set with planted data0 failuresCritical
R6Time to first tokenLoad test at expected peakp95 under 1.5 sHigh

Step 5, evidence plan. An evaluation dataset of real (anonymized) and synthetic questions, a validated judge for R1, deterministic scorers for R3 and R4, a leakage test set for R5, and a load test for R6. Later chapters show how to build each one.

Each criterion names what is measured, how it is measured, what result is acceptable and how much it matters. That is the minimum for a criterion to be testable.

Where testing happens in the lifecycle

LLM testing is not one phase. It happens at every stage, and production feeds back into development.

 design ──► build ──► offline evaluation ──► pre-release ──► release ──► production
   │          │              │                    │             │            │
 criteria   unit tests,   datasets, scorers,   red teaming,   canary,     tracing, online
 and risks  fake models,  judges, regression   performance,   shadow      evaluation,
            prompt review baselines            release gate   traffic     feedback, alerts
   ▲                                                                         │
   └────────────── new failure cases become evaluation dataset cases ◄───────┘
StageMain activitiesChapter
DesignQuality criteria, risk analysis, evaluation planThis chapter, Benchmarks, human evaluation and governance
BuildUnit tests with fake models, prompt and schema reviewsTesting LLM code without the model
Offline evaluationDatasets, scorers, judges, statisticsEvaluation methodology and datasets and the chapters after it
Pre-releaseSecurity testing, performance tests, release gatesSecurity, red teaming and guardrails, Production quality
ReleaseCanary and shadow deployments, model migrationsProduction quality
ProductionTracing, online evaluation, feedback loopsProduction quality

Example project

The method of this chapter is implemented and tested in examples/llm-testing/01-property-oracles: property oracles for the refund assistant, a test that documents what they cannot detect, and the run-count arithmetic. All tests run offline, without a model or API keys:

uv sync --project examples/llm-testing
uv run --project examples/llm-testing pytest examples/llm-testing/01-property-oracles

Common mistakes

  • Treating a demo as a test. A few good-looking answers prove little; see the probabilities above.
  • Testing only the model. Most failures come from prompts, retrieval, parsing and tools, which you control.
  • Using exact-match oracles for free text. They fail on correct paraphrases and teach the team to ignore failures.
  • Choosing metrics before looking at outputs. Generic metrics often measure nothing that matters for the product. Start with error analysis (see Evaluation methodology and datasets).
  • Not recording versions. A result without the model version, prompt version and parameters cannot be reproduced or compared.
  • Ignoring latency and cost. A correct answer that arrives too late or costs too much is a failed requirement.

Summary

  • An LLM system is much more than the model. Testers mostly work on the application and feature layers, where prompts, retrieval, tools and validation create most defects.
  • Generative output has no single expected value. LLM testing combines property, reference-based, model-based, human, metamorphic and differential oracles.
  • Output varies because of sampling, inference non-determinism, model versions, prompts, retrieved context, tools and conversation state. Quality claims are claims about rates.
  • Quality must be decomposed into characteristics such as faithfulness, relevance, safety, latency and cost, and then into criteria with a measurement method, threshold and priority.
  • Testing happens across the whole lifecycle, and production failures must flow back into evaluation datasets.

Source registry

7 chapter references
The Oracle Problem in Software Testing: A Survey

Defines the test oracle problem and the oracle families (specified, derived, implicit, human) used to structure LLM checks.

Barr, Harman, McMinn, Shahbaz, Yoo — IEEE Transactions on Software Engineering · paper
Source ↗
How is ChatGPT's behavior changing over time?

Evidence that the behaviour of the same API model changes between versions, motivating version pinning and regression testing.

Chen, Zaharia, Zou — arXiv · paper
Source ↗
ISO/IEC 25010:2023 — Product quality model

Classic software product quality model that the LLM quality characteristics extend.

ISO/IEC · standard
Source ↗
ISO/IEC 25059:2023 — Quality model for AI systems

Adapts the SQuaRE quality model to AI systems; reference for AI-specific quality characteristics.

ISO/IEC · standard
Source ↗
ISTQB Certified Tester AI Testing (CT-AI)

Certification syllabus for AI testing terminology; complements this course, which goes deeper on generative systems.

ISTQB · official syllabus
Source ↗
Your AI Product Needs Evals

Practitioner account of evaluation-driven development, error analysis and the levels of LLM evaluation.

Hamel Husain · article
Source ↗
Ollama — run open-weight models locally

Free local model runtime with an OpenAI-compatible endpoint for practising the hands-on exercises.

Ollama · tool
Source ↗