QA Interview Hub · Knowledge base · Quizzes · Українська

AI

How to test an LLM agent

Why an LLM is not tested like regular code

An LLM is not tested by comparing exact text: it is non-deterministic and free text has no single correct answer. Test the properties of an answer (format, the right tool called, no forbidden words) and measure the success rate on a set of examples. Safety rules require 100 %. The logic around the model (parsing, routing, errors) is tested conventionally with a mocked model.

AI for QA · Testing AI

A test with toBe fails although the bot answered correctly, in other words. What should you check now?

For the request "Cancel order 1042" the bot answered "Your order 1042 has been successfully cancelled", while the test expected "Order 1042 has been cancelled." and failed. The team fixes the expected string, and the next day the bot words it differently again. There is a flip side too: a wrong answer that happens to match the template passes. The usual logic "input → expected string" does not work with an LLM, and this lesson explains why and what to put in its place.

How it works and why. A classic test fixes an input and compares with an expected value. With an LLM this breaks for three reasons.

  • Non-determinism. The same input gives different but equally correct answers. Even zero temperature does not guarantee identical text (see the lesson on generation parameters). String equality does not work;
  • The oracle problem. For free text there is no single "correct" answer, so it is unclear what to compare with;
  • Implicit dependencies. Behaviour is changed by the model version, the prompt, the parameters, RAG data and tool results. None of these changes looks like broken code, so a regression is not visible in a diff.

Two shifts follow. First: check the properties of an answer, not the exact text. Second: measure the success rate over a set of examples, not "passed or not" on one run.

Exact text or properties

Typical

Exact text

toBe with one string. It fails on a correct answer in other words and passes on a wrong one that happened to match.

Better

Properties on a sample

We check that the tool was called, the phrase promises nothing extra and the format is valid. We measure the success rate over repeats.

Figure 1. Properties answer "is the behaviour right", while exact text only answers "does the string match".

Example: from a brittle test to a sampled one. The initial version:

const res = await bot.reply('Cancel order 1042');
expect(res.text).toBe('Order 1042 has been cancelled.');

It fails on a synonym and does not catch a wrong answer that matched. The fixed test checks what matters to the business: whether the cancellation tool was called with the right number and whether the bot promised nothing extra. It runs the case several times:

const RUNS = 20;
let passed = 0;
for (let i = 0; i < RUNS; i++) {
  const res = await bot.reply('Cancel order 1042');
  const calledTool = res.toolCalls.some(
    (c) => c.name === 'cancel_order' && c.args.orderId === 1042,
  );
  const noFalsePromise = !/we will refund|refunded/i.test(res.text);
  if (calledTool && noFalsePromise) passed++;
}
// the threshold comes from a baseline, not by eye
expect(passed / RUNS).toBeGreaterThanOrEqual(0.9);

There are three kinds of checks. Deterministic where possible: valid JSON by a schema, required fields, the right tool called with the right arguments, the state in the database changed, no forbidden words, length within bounds. Semantic for free text: similarity by embeddings to a reference, fact checking against a reference text, LLM-as-judge (see the lesson “Eval set, metrics and LLM-as-judge”). Statistical: the success rate over repeats or over a set, a comparison of the average score between versions. A threshold, like 0.9 in the example, comes from a baseline and from risk. Over twenty repeats the noise is noticeable, so a difference of a few percent needs more runs. Safety rules (do not disclose foreign data, do not perform a forbidden action) require 100%, not "most of the time".

A test pyramid for LLM features

E2E with the real modela few critical scenariosEval set, real modelsuccess rate on examplesUnit with a mocked modelparsing, routes, errors, limits
Figure 2. The base stays deterministic: most of the logic around the model is tested without the model.

The pyramid stays. The most numerous are fast deterministic tests with a mocked model: parsing the answer, routing by category, handling errors and limits, building the context (see the lesson on the context window). Fewer are eval sets with a real model. Fewer still are end-to-end scenarios. The model mock returns answers known in advance, including bad ones: a cut-off, a refusal, broken JSON, an empty answer, because that is what the surrounding code breaks on.

Limits and alternatives. Properties do not replace a person: style, tone and relevance are hard to reduce to a check, and here a judge with a rubric and a sampled manual review help. A test over repeats is slow and paid, so it does not run on every commit (see the lesson on evals in CI). There is also a cautious way for critical answers: do not rely on generation, take the text from a template and use the model only to pick the template or extract fields.

Common mistakes.

  • An expected string in toBe. Consequence: it fails on correct answers and lets wrong matches through.
  • "Treating" an unstable test by rerunning until green. Consequence: the real failure rate is hidden.
  • One run per case. Consequence: a regression cannot be told from noise.
  • Mocking the model everywhere. Consequence: nobody checks the behaviour of the real model.
  • Taking a threshold by eye. Consequence: the threshold is either noisy or catches nothing.

Check yourself

A test requires the answer to contain the word "cancelled". The bot answered "The order was not cancelled because it has already shipped". What is wrong with the test?

Answer

The test checks a word match, not behaviour. The word "cancelled" is present in the negation, and the right check is whether the cancellation tool was called and whether the order state changed. Text checks complement checking the action and do not replace it.

A case passes in 18 of 20 runs. Is that acceptable?

Answer

It depends on the risk. For answer style 90% may be fine, for a safety rule it is 2 violations out of twenty, which is unacceptable. The threshold is set per kind of check and baseline, and 20 runs give only a rough estimate.

Which part of the logic around an LLM can be tested without the model?

Answer

Everything that does not depend on the answer content: parsing and validating the output, routing by category, building and trimming the context, handling errors, timeouts and limits. The model mock returns answers known in advance, including broken ones.

In an interview. Junior: An LLM is non-deterministic, so a test does not compare exact text but checks the properties of an answer: format, the needed tool, absence of forbidden words. Middle/Senior: Tests with a real model measure the success rate on a set and compare it with a baseline, while safety rules require 100%. I cover a large part of the logic around the model with deterministic tests with a mocked model, including broken answers. I do semantic checks with a judge with a rubric calibrated on human labels.

Eval set, metrics and LLM-as-judge

An eval is an automated run of a set of examples through the system with scoring, working as regression tests for LLM features. A golden dataset is built from real logs, known bugs and negative cases. Free text is scored by an LLM-as-judge with a narrow rubric, on a different model; the judge is calibrated on human labels by the share of bad answers it rejects. Results are read per category.

AI for QA · Testing AI

A new prompt "looks better" on three examples. How do you prove it on a hundred examples instead of the same three?

A developer changed the system prompt, glanced at three answers, and they became neater. Someone thinks this is better, while on real requests the share of errors might have grown. Without a set of examples and metrics every such change stays an opinion. The lesson covers evals, the golden dataset, metrics and a judge that can score free text.

How it works and why. An eval (evaluation) is an automated run of a set of examples through the system with scoring of the results. It plays the role of regression tests for LLM features: a change of prompt, model or RAG is compared with a baseline on the same set. The components: a set of examples, running the system with a pinned configuration, scoring, a report.

An eval run from set to report

Golden datasetinput, expected behaviour, tagsSystem: model + prompt pinnedversions in the run reportScoring: checks and a judgerubric, binary scalesReport against the baselinepass rate by category, cost
Figure 1. The model and prompt are pinned and go into the report, so the difference between two runs can be explained.

Golden dataset. A curated set of cases: input, expected behaviour (not necessarily exact text) and tags (category, difficulty). Sources: real logs and tickets (anonymised), edge cases, known bugs (every found bug becomes a case), synthetic examples generated by a model and checked by a person. The set also covers negative scenarios: refusals, ambiguous requests, attempts to bypass rules, questions with no answer in the base. Part of the examples is kept apart from those used to tune the prompt, otherwise the metric reflects fitting, not quality.

LLM-as-judge. For free text the score is given by another model according to a rubric. To make it usable, some practices are followed. One narrow rubric per score instead of "rate the quality". A binary or short scale. Ask for the explanation before the verdict. Assign a different model as the judge than the tested one, because a model tends to prefer its own answers (self-preference). Pin the versions of the judge and its prompt. Set temperature zero where the model accepts it, and it does not guarantee identical scores. Account for the tendency to prefer longer answers and a certain position in a pairwise comparison.

A vague scale or a narrow rubric

Typical

Rate the quality from 1 to 10

The scale is vague, the score depends on the mood of the prompt and the answer length. Two scores cannot be compared.

Better

A narrow rubric with reasoning

One question per score: does the answer rely only on the provided documents. A short explanation first, then yes or no.

Figure 2. A narrow question with reasoning gives a score that can be checked and calibrated.

Example: a rubric and judge calibration. A rubric for checking that an answer of a RAG bot relies only on documents:

You grade an assistant answer.
Documents: {{docs}}
Answer: {{answer}}

Does every claim in the answer rely only on the documents?
First explain briefly, then give a verdict.
Reply as JSON: {"reason": "...", "grounded": true|false}

The judge can be wrong too, so it is calibrated: a sample of answers is labelled by hand (acceptable or not) and compared with the judge verdicts.

// human[i] and judge[i]: is answer i acceptable
function calibrate(human: boolean[], judge: boolean[]) {
  const agree = human.filter((h, i) => h === judge[i]).length / human.length;
  const badIdx = human.flatMap((h, i) => (h ? [] : [i]));
  // share of bad answers that the judge also called bad
  const caught = badIdx.filter((i) => !judge[i]).length / badIdx.length;
  return { agree, caught };
}

agree shows overall agreement, but for quality caught matters more: what share of bad answers the judge actually rejected. A judge that agrees with people 95% of the time but lets half of the defects through is unfit for regression control. If agreement is low, change the rubric, add examples to the judge prompt or take another model, then calibrate again. Calibration is repeated when the judge model changes.

Metrics. Pass rate by category and tag, not one average, because an average hides a failure in one category. The refusal rate (and refusals where they are inappropriate). Average and p95 of tokens, cost and latency per case. Unstable cases: those that do not always pass. Every change of prompt, model or RAG is compared with the baseline on the same set, taking the noise of repeats into account.

Limits and alternatives. A judge does not replace people: it is a fast cheap filter, while hard and disputed cases stay with manual labelling. An eval measures what is in the set: new kinds of requests are absent from it, so the set is topped up from production (see the lesson on evals in CI). For small tasks with a clear correct output (classification, field extraction) a judge is not needed: an exact comparison is enough.

Common mistakes.

  • A "1 to 10" score with no rubric. Consequence: unstable, incomparable scores.
  • A judge of the same model as the tested one. Consequence: inflated scores for its own answers.
  • Not calibrating the judge. Consequence: the metric looks good while defects pass.
  • Tuning the prompt to the cases of the set. Consequence: the metric grows, real quality does not.
  • One average over the whole set. Consequence: a failure in one category is invisible.

Check yourself

A judge agrees with people 90% of the time, but of 20 labelled bad answers it called only 11 bad. Is it fit as regression control?

Answer

No. Overall agreement is high because most answers are good, but the judge misses 9 of 20 defects (45%). For quality control the share of caught defects matters. The rubric or the judge is changed and calibrated again.

The pass rate on the set rose from 84 to 87%, but in the "refusals" category it fell. What do you do?

Answer

Look by category, not at the average. A drop in the "refusals" category may be a safety regression that the average hid. The decision is made by the risk of the category, not by the overall number.

Why is the judge not the same model that answers?

Answer

A model tends to prefer its own style and wording (self-preference), so scores are inflated. Take another model with a pinned version and calibrate it on human labels.

In an interview. Junior: An eval is an automatic run of a set of examples through the system with scoring. LLM-as-judge scores free text by a rubric. Middle/Senior: I build the set from real logs, known bugs and negative cases, and make the judge a narrow rubric with reasoning before the verdict, on another model, calibrated on human labels by looking at the share of caught defects. I read results by category, and compare every change with a baseline on the same set.

Testing an agent: tools, trajectory, outcome

An agent is tested on three levels: a single tool, the model's decision (tool and arguments) and the trajectory with its outcome in the world. The outcome is database state, a ticket or an email, not only the final text. Assertions cover required steps, forbidden actions and the end state. Tool failures are reproduced with stubs, and step and cost limits are checked separately.

AI for QA · Testing AI

The agent answered "Done, the money is refunded", yet there is no refund in the database. What did the test check?

A test for a support agent checked that the final answer contains "money refunded". It was green, and there were no refunds in the database: the agent wrote a pleasant phrase and never called the tool. For a regular chat bot the text is the result, for an agent the result is a change in the world. The lesson covers how to test an agent at the level of tools, decisions and trajectory.

How it works and why. An agent is more complex than a chat: it has steps and side effects (for the structure of the loop see the lesson “Tool calling, agent and MCP”). So three levels are tested.

  1. A single tool. Ordinary tests: contract, argument validation, errors, idempotency. No model is needed here, the tests are deterministic and fast;
  2. Model decisions. Whether the right tool with the right arguments was chosen for this request (tool selection accuracy) and whether there are extra calls;
  3. Trajectory and outcome. The whole sequence of steps and the result in the world: database state, a created ticket, a sent email, not only the final text.

Three levels of testing an agent

3. Trajectory and outcomesteps, database state, limits2. Model decisionswhich tool, which arguments, extra calls1. A single toolcontract, validation, errors
Figure 1. An error at a lower level is visible cheaply and deterministically, so the top level is not spent on what a lower one catches.

The main technique: record the trajectory (a trace of all messages and calls) and assert on it and on the system state.

Text or the state of the world

Typical

Checking the final text

An assert on the phrase "Done, the money is refunded". The agent could write that without calling the tool, and the test is green.

Better

Trajectory and world state

An assert on the call sequence and on the database state: exactly one refund. The text only complements.

Figure 2. A final phrase does not prove that the action happened. The system state does.
test('refund request creates exactly one refund', async () => {
  const run = await agent.run('Refund order 1042', { seed: fixtureDb });

  // path: the needed tools, no extra ones
  expect(run.toolCalls.map((c) => c.name)).toEqual(['get_order', 'create_refund']);
  expect(run.toolCalls[1].args).toMatchObject({ orderId: 1042 });

  // the outcome in the world, not just text
  expect(await db.refunds.count({ orderId: 1042 })).toBe(1);

  // limits: steps and budget
  expect(run.steps).toBeLessThanOrEqual(6);
  expect(run.usage.totalTokens).toBeLessThan(8000);
});

The test has three layers. The path: the needed tools, no extra ones. The outcome: exactly one refund in the database. The limits: steps and tokens within bounds. It does not require an exact phrase, because the phrase may change.

Example: a tool failure. The most interesting agent defects show up on failures. The tool performed the action, but the response was lost to a timeout, and the model, not seeing the result, may repeat the call (the duplicate email story is analysed in the lesson on tool calling). For the check we replace the tool with a stub that performs the action and then throws a timeout:

test('a lost tool response does not create a second refund', async () => {
  // the tool runs, but its response is lost to a timeout
  const tools = fakeTools({ create_refund: timeoutAfterSuccess() });

  const run = await agent.run('Refund order 1042', { tools, seed: fixtureDb });

  expect(await db.refunds.count({ orderId: 1042 })).toBe(1);
  expect(run.status).not.toBe('step_limit');
});

The test checks not texts but invariants: exactly one refund and the agent did not loop. This is how resilience to failures is checked: a tool returned an error or a timeout, an empty response, data in an unexpected format. The agent must neither loop, nor invent a result, nor quietly ignore the error.

Practices.

  • Mock the outside world (tools, APIs, time) for fast stable runs, and keep a small separate set with real integrations in a sandbox;
  • Do not require a single path if several are correct: check the mandatory steps, forbidden actions and the final state;
  • Record / replay: recorded model answers give deterministic regressions of the agent logic with no model cost;
  • Side effects: idempotency, human confirmation of dangerous actions, tool rights by the principle of least privilege;
  • Multi-step dialogues: loss of context, contradictory clarifications, a change of intent;
  • Limits: max steps, tokens, time, cost and behaviour when they are reached (the agent stops honestly and does not pretend it finished).

Limits and alternatives. Rigid asserts on the call sequence are brittle if the agent has several correct paths: a test "it must be exactly these two tools" is overly strict. Then check the set of mandatory steps and prohibitions. Tests with a real model are non-deterministic, so they run over repeats and measure the success rate (see the lesson on evals). To judge the quality of reasoning and the wording of the result, add a judge with a rubric, and keep the action check deterministic.

Common mistakes.

  • Asserting only the answer text. Consequence: an agent that did nothing passes.
  • Requiring a single sequence of tools. Consequence: the test fails on a correct alternative path.
  • Not testing tool failures. Consequence: loops and invented results are found by users.
  • Real integrations in every test. Consequence: slow, expensive, side effects in real systems.
  • Not checking limits. Consequence: an infinite loop is noticed on the bill.

Check yourself

A test expects the call order get_order, create_refund. After an update the agent starts by calling get_customer, and the result is the same. What do you do with the test?

Answer

This is a correct alternative path, not a regression. Rewrite the test: the mandatory steps (create_refund after get_order), forbidden actions and the final state in the database, without a rigid order of extra helper calls. Otherwise the test will cry wolf on every legal change.

Why does the stub in the tool failure test perform the action and only then throw a timeout, instead of throwing the error at once?

Answer

Because the real risk is that the action happened and the response got lost. Then a retry creates a duplicate. If the error is thrown before the action, this case is not reproduced and the test does not check idempotency.

The agent reached the step limit and answered "Done". What should the test check?

Answer

The completion status (limit, not success) and the absence or rollback of partial side effects. The agent must stop honestly: say that it did not finish, not pretend success.

In an interview. Junior: An agent is tested at levels: a single tool, the model choice of tool and the result in the system. The final text is not enough. Middle/Senior: I record the trajectory and assert on mandatory steps, forbidden actions and the final state, not on a single path. I reproduce tool failures, including a lost response after a performed action, with stubs, and check limits on steps, tokens and cost separately. Fast runs go on a mocked world and recorded answers, the real model on repeats in the set.

Evals in CI and production monitoring

In CI, fast tests with a mocked model run on every commit, while an eval with the real model runs less often. A subset runs on PRs that touch the prompt or model, and the full set overnight. A quality gate compares per-category pass rate with a baseline within a tolerance. In production you need traces, online scoring, canary releases and alerts, and incidents go back into the golden dataset.

AI for QA · Testing AI

The model was updated on Friday, complaints piled up on Monday and CI was green. What did it not see?

The vendor quietly updated the model behind an alias, while CI ran only unit tests with a mocked model and stayed green. Real users saw a change of tone and more refusals on Monday. Testing an LLM system does not end at release: behaviour drifts with model updates, data changes and new kinds of requests. The lesson covers what to run in CI and what to watch in production.

How it works and why. Different checks have different cost and speed, so they are laid out in layers, like a test pyramid. Fast deterministic ones stay on every commit. Expensive eval runs with a real model run less often and selectively. What the set does not see is caught by monitoring in production.

Layers of checking from commit to production

Every commitunit with a mocked modelPR touching prompt, model, tools, RAGeval subset + quality gateNightly runfull set, repeats, costProductiontraces, judge sampling, alertsIncident → new casethe golden dataset grows
Figure 1. Every real incident flows back into the golden dataset, so the set grows with the system.

In CI.

  • Every commit. A fast layer with no network: unit tests of parsing, routing, schemas, error handling and context building with a mocked model;
  • A PR touching the prompt, model, tools or RAG. An eval set with a real model. It is expensive and slow, so a subset (smaller and representative) goes on a PR, and the full set with repeats runs at night;
  • Quality gate. The pass rate not below a floor, not worse than the baseline by more than an allowed margin, plus cost and latency limits;
  • Pinned versions. The model and prompts in configuration, so a difference can be explained. For non-determinism, each case is run several times with a tolerance (not retry until the first green).

Example: a quality gate. The baseline is stored in the repository next to the set and is updated deliberately, not automatically. A script on a PR compares the current run with it:

const base = JSON.parse(readFileSync('eval/baseline.json', 'utf8'));
const cur = await runEval({ subset: 'pr' });
const problems: string[] = [];

// an absolute floor and an allowed drop from the baseline
if (cur.passRate < 0.9) problems.push('pass rate below 0.9');
if (cur.passRate < base.passRate - 0.03) problems.push('pass rate regressed');

for (const [cat, rate] of Object.entries(cur.byCategory)) {
  if (rate < base.byCategory[cat] - 0.1) problems.push('category dropped: ' + cat);
}
// cost and speed limits
if (cur.p95Tokens > base.p95Tokens * 1.3) problems.push('p95 tokens grew');

if (problems.length) {
  console.error(problems.join('\n'));
  process.exit(1);
}

The numbers in the example (0.9, 0.03, 0.1, 1.3) are illustrative: tolerances are chosen from real spread. For that, the baseline is run several times to see how much the result fluctuates with no changes at all. A tolerance below this noise gives false red builds, one that is too wide lets a regression through. A separate check per category is needed because an average hides the failure of one of them, and for safety rules the tolerance is zero.

In production. An eval sees only known cases, so production needs other tools as well.

Offline eval and online monitoring

Offline

Eval in CI

Catches regressions on known cases before release. Controlled and reproducible, but sees only what is already in the set.

Online

Production monitoring

Sees real requests, drift and new scenarios. Less controlled, since there is no reference, so it relies on a judge, feedback and alerts.

Figure 2. They complement, not replace each other: offline gives control, online gives reality.
  • Observability. Log (carefully with personal data) the prompt, model version, tool calls, tokens, latency, cost; a trace for every request;
  • Online scoring. A sample of real dialogues goes through a judge with the same rubric as in the eval. User feedback (answer ratings) and escalations to a person are added;
  • Canary release and A/B. A new model or prompt first gets a small share of traffic, and results are compared with the baseline version;
  • Alerts. A jump in cost, in the refusal rate, in tool errors, in answer length, a change in the distribution of request topics;
  • A closed loop. Every real incident becomes a new case in the golden dataset so that it does not repeat.

Limits and alternatives. Monitoring with no reference is weaker than an eval: the judge can be wrong, and user feedback gives a partial and delayed picture. So online scoring is calibrated and samples for manual review are taken regularly. Logs with personal data need a retention and masking policy, especially if requests reach third-party services. If a vendor announces a model version retirement, it is a planned event: the eval on the new version runs before switching, not after.

Common mistakes.

  • An eval with a real model on every commit. Consequence: slow, expensive, the build is noisy from non-determinism.
  • A gate with only an absolute floor. Consequence: gradual degradation above the floor is invisible until it crosses the line.
  • Updating the baseline automatically. Consequence: a regression becomes the new normal.
  • No traces in production. Consequence: an incident cannot be reproduced.
  • Not returning incidents to the set. Consequence: the same defects repeat.

Check yourself

The vendor updated the model behind an alias on Friday. Which mechanisms should have prevented this or caught the change before the users?

Answer

A pinned model identifier, so the update does not happen without a decision, and a nightly eval on the current configuration together with production monitoring that notices a change in the refusal rate or tone. The difference between runs can be explained because versions are recorded in the report.

The quality gate often turns red with no code changes. What is the likely cause and what do you do?

Answer

The tolerance is smaller than the natural noise of non-determinism. Run the baseline several times, measure the spread and set the tolerance with that in mind, and add repeats for critical cases.

Why does a PR run a subset of the eval and the full set runs at night?

Answer

A full run with a real model is expensive and slow, and its delay would block development. A subset catches most obvious regressions, while the nightly run checks everything with repeats.

In an interview. Junior: In CI fast tests with a mocked model run on every commit, while evals with a real model run less often. In production we log and watch metrics. Middle/Senior: The quality gate compares the pass rate by category with a baseline within a tolerance measured on the noise of repeats, plus cost and latency limits. In production there are traces, judge sampling, canary releases and alerts, and every incident goes back into the golden dataset. Model and prompt versions are pinned so a difference can be explained.