Agent Assurance for your AI Deployment

Test how your agents actually behave across workflows, tools, and actions. Catch failures and vulnerabilities before they ship.

npm install -g @testmuai/rook@latest

Start Free Trial
AI TestingTesting

LLM Testing: What It Is and How to Test LLM Applications

LLM testing checks that an LLM app gives correct, grounded, safe answers after every change. Learn the test types, metrics, a CI regression gate and tools.

Last Updated on:

LLM testing is the practice of checking that an application built on a large language model gives correct, grounded, safe and well-formed answers, and keeps doing so after every prompt, model or retrieval change. Because the same input can produce different wording, tests score each response against criteria instead of matching one expected string.

A test suite combines automated scoring, human review, regression runs and production monitoring, and it decides whether a chatbot, coding assistant, enterprise search tool or AI agent is ready to ship as trustworthy AI. The automated half is AI evals, which score outputs against a fixed dataset, and LLM test automation shows the same checks at code level.

Overview

LLM testing sends fixed inputs through an LLM application and scores each response on correctness, grounding, safety and format, then reruns the suite whenever the prompt, model or retrieval layer changes. A release passes when the suite meets its thresholds and no case that passed last time now fails.

Can LLM testing be automated?

  • Deterministic checks: Fully automated. Valid JSON, required fields, length limits and required facts return the same verdict on every run, so an LLM test suite runs them first in every CI job.
  • Semantic checks: Automated with reference metrics or an LLM judge, which score relevance, faithfulness to retrieved sources and tone when a correct answer can be worded many ways.
  • Human review: Not automated. Reviewers grade reasoning and high-stakes answers, and their grades calibrate the LLM judge before its scores are allowed to gate a release.

How do you add LLM tests to a CI pipeline?

  • Golden dataset: A fixed, reviewed set of prompts with acceptance criteria. Every build is scored against it, so a prompt, model or retrieval change is compared case by case with the last release.
  • Regression gate: A CI step that fails the build when a case that passed in the last release now fails, or when the pass rate drops below the agreed threshold.

Can the same testing strategy be used for every LLM application?

  • RAG assistants: No, the strategy follows the application. A RAG assistant needs retrieval and grounding checks, such as whether each answer stays within the documents it retrieved.
  • Tool-calling agents: An agent that calls tools or writes data is tested on the effect, not the reply. TestMu AI's Agent Assurance, which tests AI agents from the terminal with Rook CLI, checks each criterion against what the run changed.

How LLM Testing Works

Each LLM test pairs one input with acceptance criteria written before the run. The harness runs the input through the application, records the response and any tool calls, and marks each criterion pass or fail. The suite's pass rate then decides the release.

Exact-match assertions break here because LLM output is probabilistic: wording varies with the prompt, model version, temperature and context, so a correct answer rarely repeats character for character. The assertion patterns that survive that variation are covered in testing non-deterministic AI outputs.

The system under test is also larger than the model. Prompts, retrieval (RAG), external APIs, function calling, memory and agents all shape the answer, so a customer support chatbot, for example, is tested on whether it:

  • Reads the user's intent correctly.
  • Retrieves the right article from its knowledge base.
  • Says it does not know instead of inventing an answer.
  • Stays inside safety rules and company policy.
  • Keeps the same quality after a prompt update or model upgrade.

Model choice is one of the variables a suite settles, and SLM vs LLM compares where smaller models hold up on your own requests. Models that return a typed decision instead of text, such as Jev, the System One model from TypeSafe AI, are tested on whether the confidence threshold behind each decision is set correctly.

LLM Testing vs Traditional Software Testing

Traditional software testing asserts that a known input returns one expected output, while LLM testing scores a response that can vary and asks whether it is correct, grounded and safe rather than identical. LLM evaluation is the scoring layer inside that work: it measures output quality, and testing turns those scores into release decisions.

AspectTraditional software testingLLM testingLLM evaluation
Output under testOne deterministic resultA response that varies between runsModel or application output
Pass conditionExact match with the expected valueCriteria met and thresholds heldA score on each metric
Typical checksUnit, integration and end-to-end assertionsFormat, facts, grounding, safety, regressionsCorrectness, relevance, faithfulness
Runs whenThe code changesCode, prompt, model or data changes, and in productionModel selection, development and sampled traffic
Question it answersDoes it return the right value?Can this build ship?How good is the output?

Types of LLM Testing

The common types of LLM testing are unit, functional and integration, regression, performance, security, bias and fairness, prompt, and human and evaluator testing. Each targets a different failure, so a production suite mixes several.

Unit Testing

Unit testing checks one prompt-response pair or one isolated capability under controlled conditions, such as valid JSON, the right label, a word limit, or exactly three bullets in a summary with no extra commentary. Score outputs whose wording can vary with rules, similarity checks or a rubric rather than exact strings.

Functional And Integration Testing

Functional testing checks that the model does the intended task from the user's side: it understands the request, follows instructions and gives the right kind of answer. Integration testing checks the chain around it, so for a support bot that classifies a request, retrieves a help article and replies, a functional test confirms the reply and an integration test confirms each step ran correctly in sequence.

Regression Testing

Regression testing reruns a saved set of important prompts after a model upgrade, prompt edit, retrieval change or tool update, and compares the results with known-good outputs or score thresholds. It catches the trade-off where a prompt fix helps one use case and breaks accuracy or formatting in another, and step 6 below shows a gate that does it in CI.

Performance Testing

Performance testing measures latency, throughput, resource use and cost per request under load, and checks that answer quality holds as traffic grows. A support assistant that answers well one-to-one can still slow down or cost too much when hundreds of users arrive at once.

Security Testing

Security testing checks whether the application can be manipulated through prompt injection, jailbreaks, data exfiltration, unsafe tool use or adversarial inputs, which matters most when the model can call tools or read private data. Prompt injection testing goes deep on that one attack class, red teaming LLMs covers full attack campaigns, and LLM security maps the risks to the OWASP Top 10 for LLM applications.

Bias And Fairness Testing

Bias and fairness testing sends paired prompts that differ only in a demographic reference, such as gender, age, language or region, and compares the quality, tone and decisions of the answers. A systematic gap is a defect, most of all in public-facing systems and anywhere a recommendation affects people.

Prompt Testing

Prompt testing runs prompt versions with different wording, role instructions, constraints and tool-use instructions on the same inputs to find the one that gives the most accurate, well-formatted output. It improves quality without changing the model, and because a prompt change can shift behavior elsewhere, it runs alongside regression testing; prompt evaluation covers comparing versions side by side.

Human And Evaluator Testing

Human reviewers grade what rules miss, such as usefulness, naturalness, safety nuance and reasoning quality, while evaluator testing applies the same rubric at scale with heuristics or LLM-as-a-judge scoring. Use people to calibrate the judge and to grade high-stakes cases, and the judge for speed and repeatability.

Note

Note: TestMu AI Agent Testing runs test scenarios against chat, voice, phone, image and video agents before they reach real users. Try it free.

Key Metrics Used in LLM Testing

LLM testing metrics fall into five groups: task quality, safety and bias, grounding, human and judge scores, and system performance and cost. Pick the few in each group that map to a release risk and give each one a threshold.

GroupWhat it checksExample metrics
Task qualityWhether the answer is right and solves the taskAccuracy, F1, answer relevance, instruction following, ROUGE, BLEU, BERTScore
Safety and biasWhether the output is safe, fair and trueHallucination rate, toxicity, bias scores, policy violations, data leakage
Grounding (RAG)Whether claims come from the supplied contextFaithfulness, context precision, context recall, citation accuracy
Human and judge scoresQualities that rules cannot measureHelpfulness, pairwise preference, tone, rated on a rubric
Performance and costWhether it runs well at production loadLatency, time to first token, throughput, cost per request, error rate

Published hallucination figures use different denominators, and the guide to the AI hallucination rate shows how to put them on one scale. The grounding metrics have formulas in RAG evaluation metrics and groundedness, and public model scores are compared in LLM benchmarks.

Latency, cost and error rate show whether an app runs well, not whether its answers are accurate or safe, so pair every performance threshold with a quality one. The free Agent Testing Certification by TestMu AI covers testing AI agents and conversational bots for reliability, safety and real-world accuracy, including the Agent Testing platform, Agent Assurance and Rook CLI.

Get certified in Agent Testing for free with TestMu AI

How to Test LLM Applications Step by Step

To test an LLM application, define what a good answer is, build a dataset that reflects real use, choose metrics, automate the scoring, add human review, gate every release on regressions in CI, and keep scoring production traffic.

Step 1: Define Clear Testing Objectives

Write down what success means for this application before writing any test: a support bot may put factual accuracy and consistency first, a content tool fluency and tone. Turn each goal into a measurable criterion, such as a correctness threshold, a latency budget or a cost ceiling per request.

Step 2: Build a Representative Evaluation Dataset

Start from real user requests, then add edge cases, ambiguous prompts, adversarial inputs and domain-specific scenarios. Keep a reviewed core as a golden dataset of prompts with trusted reference answers or expected behaviors, so every later run is compared with the same baseline. For RAG, the comparison of public datasets for training and evaluating RAG models shows which held-out sets test skills such as multi-hop reasoning.

Step 3: Pick Metrics That Match Each Risk

Combine metrics, because no single one covers an LLM application: correctness for facts, answer relevancy for intent, faithfulness for grounding in retrieved context, and context precision and recall for retrieval quality. Add latency, token use and cost per request, plus toxicity and bias wherever users see the output.

Step 4: Automate Evaluations

Run the suite automatically whenever a prompt, model, retrieval pipeline or feature changes, so hundreds of cases are scored the same way each time and regressions show up before release. Put the deterministic checks first, since they are fast and need no model call, and send only what passes them to slower judge scoring; the guide on how to scalably test LLMs covers running evaluations at volume.

Step 5: Combine Automated and Human Evaluation

Automated scores are fast and repeatable but miss tone, empathy and the quality of reasoning, so review a sample of outputs by hand on a schedule, weighted toward high-stakes cases. Score a shared sample with both the reviewers and any LLM judge, and trust the judge only where the two agree.

Step 6: Gate Every Release on Regressions in CI

Rerun the same dataset after every significant change and compare each case with the last release, so a drop in accuracy, a new hallucination or a broken format blocks the build instead of reaching users. A small gate script is enough to start: it reads the replies the CI job saved from the candidate build, applies each case's checks from the golden dataset, and exits non-zero when a case that passed in the last release now fails.

# llm_gate.py: score saved replies, fail CI on a regression
import json, sys

def load(path):
    with open(path) as f:
        return [json.loads(line) for line in f if line.strip()]

def check(case, raw):
    try:
        answer = json.loads(raw)["answer"].lower()
    except (ValueError, KeyError, TypeError):
        return "not JSON with an answer field"
    for text in case.get("must_include", []):
        if text.lower() not in answer:
            return f"missing: {text}"
    for text in case.get("must_not_include", []):
        if text.lower() in answer:
            return f"forbidden: {text}"
    return None

golden = load("golden.jsonl")
replies = {r["id"]: r["output"] for r in load("replies.jsonl")}
with open("baseline.json") as f:
    baseline = json.load(f)  # last release: {"id": true}

passed, regressions = 0, []
for case in golden:
    problem = check(case, replies.get(case["id"], ""))
    note = f" ({problem})" if problem else ""
    print(("FAIL " if problem else "PASS ") + case["id"] + note)
    if problem is None:
        passed += 1
    elif baseline.get(case["id"]):
        regressions.append(case["id"])

rate = passed / len(golden)
print(f"pass rate {rate:.0%}, regressions {len(regressions)}")
sys.exit(1 if regressions or rate < 0.9 else 0)

On four sample support-bot cases, where cancel-plan passed in the last release and its new reply drops the required phrase, the gate prints:

$ python llm_gate.py
PASS refund-window
FAIL cancel-plan (missing: billing page)
PASS eu-shipping
FAIL order-status (not JSON with an answer field)
pass rate 50%, regressions 1
$ echo $?
1

The exit code 1 fails the CI job. The order-status case also failed in the last release, so it lowers the pass rate without counting as a regression. Phrase checks suit facts that must appear word for word, such as a refund window; where meaning matters more than wording, replace check() with a judge score.

For features built on OpenAI models, the OpenAI CLI can run the prompts from a CI job and fail the build when a response comes back malformed or the API call errors.

Step 7: Monitor Production Performance

Keep scoring after release: sample live traffic and track correctness, answer relevancy, faithfulness, hallucination rate, latency, toxicity and cost per request, because real users send requests no dataset predicted. Add each new failure to the golden dataset so the next regression run covers it, and see LLM observability for the tracing and dashboards that collect those signals.

LLM Testing Frameworks and Tools

Common LLM testing frameworks include DeepEval, Ragas, Promptfoo and TruLens, which are open source, and LangSmith, LangChain's platform for tracing and evaluation. Choose by architecture: a RAG pipeline needs retrieval metrics, a prompt-heavy app needs side-by-side prompt comparison, and an agent needs a trace of every step.

FrameworkWhat it isTypical use
DeepEvalOpen-source (Apache 2.0) evaluation framework from the founders of Confident AI, described as similar to Pytest but for unit testing LLM appsLLM test cases inside a Python test suite
RagasOpen-source (Apache 2.0) toolkit for evaluating LLM applicationsRAG metrics such as faithfulness and context precision
PromptfooOpen-source (MIT) CLI and library for evaluating and red-teaming LLM appsComparing prompts across models, adversarial prompt sets
TruLensOpen-source (MIT) evaluation and tracking for LLM experiments and AI agents, with OpenTelemetry-native tracingScoring each step of an agent or RAG trace
LangSmithLangChain's observability and evaluation platform, working with many frameworks and model providersTracing production runs and building evaluation datasets from them

A separate reference shows how Ragas metrics such as faithfulness and context precision are calculated, and the roundup of the best LLM evaluation tools compares these and other options by architecture and privacy needs. In the TestMu Conf 2026 session Testing What Matters: Evaluating LLM Relevancy with DeepEval, Monika Sharma shows how to measure relevancy, the failure where an answer sounds fluent and confident but misses what the user asked.

Youtube thumbnail

These frameworks score outputs, traces and retrieval at the model and pipeline layer. Once the LLM ships inside a product, the test has to reach it the way users do: TestMu AI's Agent Testing connects to chat, voice, phone, image and video agents through that same channel.

On chat, voice and phone agents it runs 15+ specialized AI testing agents, each probing a different failure mode, and scores every conversation on metrics such as Intent Recognition Accuracy and Hallucination Detection. Each run ends in a Green, Yellow or Red production-readiness verdict with transcripts of the failing scenarios, so an eval framework hardens the model layer during development and Agent Testing checks the application layer before release.

Common Challenges in LLM Testing

The hardest parts of LLM testing are output that varies between runs, hallucinations, prompt sensitivity, long-context drift, adversarial attacks, and the cost of evaluating at scale.

ChallengeWhy it breaks testsHow to handle it
Non-deterministic outputThe same prompt returns different wording, so exact-match assertions fail on correct answersScore meaning with correctness, relevancy and faithfulness instead of string equality
HallucinationsFabricated facts read as fluent and confident, the failure known as AI hallucinationCheck answers against trusted sources, and for RAG require grounding in the retrieved context
Prompt sensitivitySmall wording changes shift accuracy or formatTest prompt variants and rerun the regression suite after every prompt or model update
Context limitsLong conversations lose earlier context or instructionsInclude multi-turn and long-context cases in the dataset
Adversarial attacksInjections and jailbreaks bypass safety rules or expose sensitive dataRun adversarial cases and red-team campaigns before each release
Cost, latency and model driftLarge evaluation runs are expensive, and model updates change behaviorRun deterministic checks first, sample judge scoring, and monitor key metrics in production

Real-World LLM Testing Use Cases

What a suite checks depends on the application: a chatbot is tested on intent and conversation, a RAG app on retrieval and grounding, a coding assistant on code correctness, and an agent on the actions it takes.

  • AI chatbots and virtual assistants - Response accuracy, intent recognition, hallucination checks and safety, plus multi-turn tests that confirm the bot keeps context and follows instructions across a conversation.
  • RAG applications - Whether retrieval returns the relevant documents and the answer reflects them, measured with faithfulness, context precision, context recall and answer relevancy.
  • AI coding assistants - Code correctness, syntax validity, logical accuracy and security flaws in generated code, across the languages and frameworks the assistant supports.
  • AI agents - Whether the agent picks the right tools, completes the task, recovers from failures and reaches the right outcome across a multi-step workflow, not only whether its final message reads well. AI agent testing and AI agent evaluation cover both sides in depth.
  • Content generation - Factual accuracy, grammar, tone, brand alignment, originality and compliance with content guidelines.
  • Enterprise knowledge assistants - Retrieval quality, factual correctness, citation accuracy and access control, so confidential documents never reach users without permission.
  • Healthcare and finance - Higher bars for factual accuracy, bias, explainability and compliance with industry regulation before anything reaches production.

For the conversational surface, chatbot testing covers the test types and case templates, and the guide on how to test a chatbot walks from mapping intents to writing test cases and choosing metrics.

Testing Tool-Calling LLM Applications With Agent Assurance

When an LLM application calls tools, writes files or updates records, the test has to check the effect, because a reply saying the task is done proves nothing alone. TestMu AI's Agent Assurance is built for agents that act: it reads your codebase to learn what the agent does, writes a test suite, invokes the agent for real, and checks each criterion against what the run changed rather than what the agent reported.

  • Scenarios from the agent's own code - Discovery reads manifests, prompts, tool tables and MCP servers, then writes functional and adversarial scenarios, including the prompt injection, data exfiltration and policy violation attempts that security testing looks for.
  • Evidence over claims - Tool calls are checked against the agent's declared tools, and changed files, produced artifacts and records confirmed by read-only checks are the evidence, so a false completion claim meets what really happened.
  • A pass rate that shows its gap - Each criterion ends as Pass, Fail or Unable to Verify. Unable to Verify stays out of the pass rate and is reported beside it, as the share of criteria that could not be verified, which this guide calls the assurance gap.
  • Run-over-run regression checks - A rerun shows the pass-rate change between the last two runs and which scenarios newly fail or were fixed, and the JSON report gives a CI job the run totals to gate on.

Agent Assurance runs in your terminal as Rook CLI, the rook command, and needs a TestMu AI account with an Agent Assurance plan or the 14-day free trial. The npm route needs Node.js 20 or newer:

npm install -g @testmuai/rook@latest

Claude Code can drive it too. Install the skill (Node.js 22 or newer), open Claude Code in the agent's repository, and type /rook with the test you want; Claude Code's usual approvals still apply to each command it proposes.

npx @testmuai/rook-skill@latest install --agent claude-code

A bounded first request for an agent that files tickets could read:

/rook Test the ticketing agent in this repository, which opens, updates, and closes tickets through an API tool. Use the staging profile, propose up to three scenarios, including a request it should refuse to act on, and show me the possible writes before invoking the target.

The Claude Code setup guide covers the skill and the CLI install together.

Start a 14-day free trial of Agent Assurance by TestMu AI, with 4,000 credits, to test how your AI agents behave across workflows, tools, and actions

Conclusion

Start with a golden dataset built from real user prompts, give each case a written pass criterion, and run the gate in CI on every prompt, model and retrieval change. If the application calls tools or writes data, install Rook CLI with the Rook CLI install guide and point its first suite at a staging copy of the agent.

Author

...

Anubhav Singhmaar

Blogs: 49

  • Linkedin

Anubhav Singhmaar is an AI Product Manager at TestMu AI driving Kane CLI, the command-line tool that brings browser automation to the terminal, turning natural-language flows into runs in a real Chrome browser that return pass or fail with shareable proof. He owns the roadmap and prioritization and works with engineering to ship developer-facing features. Before TestMu AI, he spent over four years at Sprinklr owning enterprise voice AI across APAC and EMEA. A mechanical engineer turned product manager, he grounds guidance in real QA workflows.

Reviewer

...

Samyak Goyal

Reviewer

  • Linkedin

Samyak Goyal is a Senior Member of Technical Staff at TestMu AI engineering Kane CLI, the command-line tool that runs browser automation from the terminal, where a flow described in natural language executes in a real Chrome browser and returns pass or fail with shareable proof. He is a backend engineer with 4+ years of experience, previously an SDE at Innovaccer, where he built APIs, introduced Kafka, and cut deployment from weeks to hours. Samyak also builds multi-agent systems, skill-orchestration frameworks, and a personal copilot that indexes 200+ microservice repositories.

Add to Google preferred sources

Summarise with AI

Copied to Clipboard!
...

3000+ Browsers. One Platform.

See exactly how your site performs everywhere.

Try it free
...

Write Tests in Plain English with KaneAI

Create, debug, and evolve tests using natural language.

Try for free

LLM Testing FAQs

Did you find this page helpful?

More Related Learning Hubs

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests