PromptisePromptise
PlatformSoonEnterprise
DocsGitHub
Talk to usGet started
Promptise - AI Framework LogoPromptise

The full-stack framework for agentic systems. Build with the framework. Run it on the platform. Launch it with our engineers.

pip install promptise

[01] Product

  • Framework
  • Platform (coming soon)
  • Enterprise
  • How it works
  • Contact

[02] Framework

  • The Agent
  • The Interface
  • The Harness

[03] Resources

  • Documentation
  • GitHub
  • Why Promptise
  • Use cases
  • Roadmap
  • Guides
  • Learning Paths
  • Questions

[04] Company

  • About
  • Terms of Service
  • Privacy Policy
  • Cookie Policy
  • Subprocessors

© 2026 Promptise by Manser Ventures. All rights reserved.

hello@promptise.com
← Learning paths> Agentic Engineering with Promptise Foundry
Lesson 83 / 100
83%

How to Test LLM Prompts and AI Agents in Python

Unit test LLM prompts with pytest, catch prompt regressions in CI, grade outputs with an LLM judge and check which tools an AI agent calls, in Python.

Intermediate24 minEvals and Testing
All 100 lessons↓
  1. ✓What Is an AI Agent? Definition, How It Works, Examples
  2. ✓How to Build an AI Agent in Python (2026 Guide)
  3. ✓Build a Personal AI Agent: Memory, Reminders, Chat
  4. ✓What Is an Agent Harness? Parts and How to Build One
  5. ✓System Prompt Best Practices for AI Agents in Python
  6. ✓Best LLM for AI Agents (2026): Picks, Prices, How to Test
  7. ✓AI Agent YAML: Define and Run an Agent From a Config File
  8. ✓Streaming LLM Responses with FastAPI: Tokens and Tool Calls
  9. ✓Best Local LLM for AI Agents: Ollama Models by GPU (2026)
  10. ✓Claude AI Agent with MCP: Use Anthropic Models in Promptise
  11. ✓Gemini AI Agent with MCP: Use Google Models in Promptise
  12. ✓Azure OpenAI Agent with MCP: Use Deployments in Promptise
  13. ✓OpenRouter AI Agent with MCP: Many Models in Promptise
  14. ✓Ollama AI Agent with MCP: Run Local Models in Promptise
  15. ✓LLM Semantic Cache and Model Fallback in Python
  16. ✓What Is MCP (Model Context Protocol)? A Developer's Guide
  17. ✓What Is Tool Calling? LLM Function Calling Explained
  18. ✓MCP Tools vs Resources vs Prompts (With Python Examples)
  19. ✓How to Connect MCP Servers to Your AI Agent in Python
  20. ✓Build a Production MCP Server in Python (Step by Step)
  21. ✓MCP Transports: stdio vs Streamable HTTP vs SSE (Python)
  22. ✓MCP 2026-07-28 Migration: Make Your MCP Server Stateless
  23. ✓OpenAPI to MCP: Turn Any REST API into an MCP Server
  24. ✓MCP Authentication in Python: API Keys, JWT and OAuth
  25. ✓Build an Authenticated MCP Server for Your AI Agent (Python)
  26. ✓MCP Security Best Practices: A Checklist for MCP Servers
  27. ✓Testing MCP Servers in Python: pytest Without a Live Server
  28. ✓Too Many MCP Tools? How to Fix LLM Tool Selection in Python
  29. ✓Idempotent Tool Calls: Make AI Agent Retries Safe
  30. ✓AI Agent Tool Failures: Stop Unsafe Workarounds
  31. ✓MCP Server Caching, Timeouts and Circuit Breakers in Python
  32. ✓MCP Middleware for Servers: Auth, Logging, Rate Limits
  33. ✓MCP vs CLI for AI Agents: Tokens, Security, When to Use Each
  34. ✓LangChain vs MCP: Differences and How They Work Together
  35. ✓FastMCP Alternatives for Production MCP Servers (2026)
  36. ✓AI Agent Audit Logging: Tamper-Evident Logs in Python
  37. ✓AI Agent Human in the Loop: Approve Tool Calls in Python
  38. ✓AI Agent Prompt Injection: How to Defend Against It
  39. ✓Hidden Text Prompt Injection: Sanitize Pages for AI Agents
  40. ✓Build a Multi-Agent System in Python (and When Not To)
  41. ✓Context Engineering for AI Agents: Context Window Management
  42. ✓Context Compaction for AI Agents: Trim vs Summarize
  43. ✓How to Deploy an AI Agent with Docker (2026 Guide)
  44. ✓LLM Tool Rate Limiting: Per-Client Limits for MCP Servers
  45. ✓MCP Long-Running Tasks: Background Jobs in Python
  46. ✓MCP Server Monitoring: Prometheus, OpenTelemetry and Logs
  47. ✓Best AI Agent Frameworks (2026): Python Options Compared
  48. ✓Self-Improving AI Agent: Learn From Tool Failures in Python
  49. ✓AI Agent Identity: Authenticate Agents to MCP Servers
  50. ✓Code-Action Agents in Python: One Program vs 37 Tool Calls
  51. ✓Multi-Tenant AI Agents: Keep Each Customer's Data Apart
  52. ✓What Is Agentic RAG? How It Differs from Classic RAG
  53. ✓AI Agent Memory in Python: Short-Term and Long-Term
  54. ✓Per-User Agent Memory Isolation: Stop Leaks Between Users
  55. ✓Agentic RAG in Python: Give Your AI Agent a Search Tool
  56. ✓AI Agent Reasoning Patterns in Python: From ReAct to Debate
  57. ✓Plan-and-Execute Agents in Python: Beyond the ReAct Loop
  58. ✓Self-Modifying AI Agent in Python: Open Mode & Limits
  59. ✓CrewAI Alternatives: 7 Options and How to Migrate (2026)
  60. ✓Migrate from AutoGen: Agent Framework, AG2 and More
  61. ✓What Is an LLM Guardrail? Types, Examples and Limits
  62. ✓Best LLM Guardrails Tools (2026): 9 Platforms Compared
  63. ✓AI Agent Guardrails in Python: Block Injection, Redact PII
  64. ✓NeMo Guardrails vs Guardrails AI: Which to Choose (2026)
  65. ✓AI-Based PII Detection and Redaction Tools for LLM Apps
  66. ✓Stop Secrets Leaking Into LLM Logs and Traces
  67. ✓AI Agent Code Execution Sandbox: Run LLM Code Safely
  68. ✓AI Agent Network Egress: Limit Where Agents Can Connect
  69. ✓AutoGen Docker Task Isolation: Secure the Code Executor
  70. ✓SPIFFE for AI Agents: Workload Identity Without API Keys
  71. ✓On-Behalf-Of Auth for AI Agents: Act as Each User
  72. ✓AI Agent Production Checklist: What to Check Before Launch
  73. ✓Approval Fatigue: Auto-Approve Safe AI Agent Actions
  74. ✓What Is Human in the Loop AI? Approvals for AI Agents
  75. ✓AI Agent Notifications: Webhook and Slack Alerts in Python
  76. ✓AI Agent Observability: Trace Tool Calls, Tokens and Cost
  77. ✓Best AI Agent Observability Tools (2026), Compared
  78. ✓AI Agent Stuck in a Loop? How to Detect and Stop It
  79. ✓How to Run, Debug and Deploy an AI Agent in Python
  80. ✓AI Agent Cost Tracking: Tokens and Cost per Run and User
  81. ✓How to Evaluate AI Agents: Evals, LLM Judges and pass^k
  82. ✓AI Agent Cost Control: Budgets That Stop Runaway Spend
  83. 83How to Test LLM Prompts and AI Agents in Python
  84. 84AI Agent Evals in CI: Run Them on Every Pull Request
  85. 85What Is an Agentic Runtime? AI Agent Runtimes Explained
  86. 86Autonomous AI Agent Runtime: Budgets, Crash Recovery, API
  87. 87Event-Driven AI Agents: Webhook, Cron and File Triggers
  88. 88AI Agent Cron Jobs: Run an Agent on a Schedule
  89. 89AI Agent Webhook Trigger: Run an Agent on HTTP Events
  90. 90AI Agent File Watcher: Process New Files Automatically
  91. 91Custom AI Agent Triggers: Wake an Agent From Any Source
  92. 92AI Agent Event Filters: Skip Runs Before the LLM
  93. 93AI Agent Retries and a Dead Letter Queue for Failed Runs
  94. 94Run Multiple AI Agents: One Runtime, Many Processes
  95. 95AI Agent Manifest: Declare a Long-Running Agent in YAML
  96. 96AI Agent CLI: Start, Stop and Inspect Running Agents
  97. 97AI Agent Monitoring Dashboard in the Terminal
  98. 98Multi-Agent Event Bus: Chain Agents With Events
  99. 99Distributed AI Agents: Run Agents Across Many Machines
  100. 100Pause and Resume an AI Agent: Lifecycle States Explained

Lessons in this path

  1. ✓What Is an AI Agent? Definition, How It Works, Examples
  2. ✓How to Build an AI Agent in Python (2026 Guide)
  3. ✓Build a Personal AI Agent: Memory, Reminders, Chat
  4. ✓What Is an Agent Harness? Parts and How to Build One
  5. ✓System Prompt Best Practices for AI Agents in Python
  6. ✓Best LLM for AI Agents (2026): Picks, Prices, How to Test
  7. ✓AI Agent YAML: Define and Run an Agent From a Config File
  8. ✓Streaming LLM Responses with FastAPI: Tokens and Tool Calls
  9. ✓Best Local LLM for AI Agents: Ollama Models by GPU (2026)
  10. ✓Claude AI Agent with MCP: Use Anthropic Models in Promptise
  11. ✓Gemini AI Agent with MCP: Use Google Models in Promptise
  12. ✓Azure OpenAI Agent with MCP: Use Deployments in Promptise
  13. ✓OpenRouter AI Agent with MCP: Many Models in Promptise
  14. ✓Ollama AI Agent with MCP: Run Local Models in Promptise
  15. ✓LLM Semantic Cache and Model Fallback in Python
  16. ✓What Is MCP (Model Context Protocol)? A Developer's Guide
  17. ✓What Is Tool Calling? LLM Function Calling Explained
  18. ✓MCP Tools vs Resources vs Prompts (With Python Examples)
  19. ✓How to Connect MCP Servers to Your AI Agent in Python
  20. ✓Build a Production MCP Server in Python (Step by Step)
  21. ✓MCP Transports: stdio vs Streamable HTTP vs SSE (Python)
  22. ✓MCP 2026-07-28 Migration: Make Your MCP Server Stateless
  23. ✓OpenAPI to MCP: Turn Any REST API into an MCP Server
  24. ✓MCP Authentication in Python: API Keys, JWT and OAuth
  25. ✓Build an Authenticated MCP Server for Your AI Agent (Python)
  26. ✓MCP Security Best Practices: A Checklist for MCP Servers
  27. ✓Testing MCP Servers in Python: pytest Without a Live Server
  28. ✓Too Many MCP Tools? How to Fix LLM Tool Selection in Python
  29. ✓Idempotent Tool Calls: Make AI Agent Retries Safe
  30. ✓AI Agent Tool Failures: Stop Unsafe Workarounds
  31. ✓MCP Server Caching, Timeouts and Circuit Breakers in Python
  32. ✓MCP Middleware for Servers: Auth, Logging, Rate Limits
  33. ✓MCP vs CLI for AI Agents: Tokens, Security, When to Use Each
  34. ✓LangChain vs MCP: Differences and How They Work Together
  35. ✓FastMCP Alternatives for Production MCP Servers (2026)
  36. ✓AI Agent Audit Logging: Tamper-Evident Logs in Python
  37. ✓AI Agent Human in the Loop: Approve Tool Calls in Python
  38. ✓AI Agent Prompt Injection: How to Defend Against It
  39. ✓Hidden Text Prompt Injection: Sanitize Pages for AI Agents
  40. ✓Build a Multi-Agent System in Python (and When Not To)
  41. ✓Context Engineering for AI Agents: Context Window Management
  42. ✓Context Compaction for AI Agents: Trim vs Summarize
  43. ✓How to Deploy an AI Agent with Docker (2026 Guide)
  44. ✓LLM Tool Rate Limiting: Per-Client Limits for MCP Servers
  45. ✓MCP Long-Running Tasks: Background Jobs in Python
  46. ✓MCP Server Monitoring: Prometheus, OpenTelemetry and Logs
  47. ✓Best AI Agent Frameworks (2026): Python Options Compared
  48. ✓Self-Improving AI Agent: Learn From Tool Failures in Python
  49. ✓AI Agent Identity: Authenticate Agents to MCP Servers
  50. ✓Code-Action Agents in Python: One Program vs 37 Tool Calls
  51. ✓Multi-Tenant AI Agents: Keep Each Customer's Data Apart
  52. ✓What Is Agentic RAG? How It Differs from Classic RAG
  53. ✓AI Agent Memory in Python: Short-Term and Long-Term
  54. ✓Per-User Agent Memory Isolation: Stop Leaks Between Users
  55. ✓Agentic RAG in Python: Give Your AI Agent a Search Tool
  56. ✓AI Agent Reasoning Patterns in Python: From ReAct to Debate
  57. ✓Plan-and-Execute Agents in Python: Beyond the ReAct Loop
  58. ✓Self-Modifying AI Agent in Python: Open Mode & Limits
  59. ✓CrewAI Alternatives: 7 Options and How to Migrate (2026)
  60. ✓Migrate from AutoGen: Agent Framework, AG2 and More
  61. ✓What Is an LLM Guardrail? Types, Examples and Limits
  62. ✓Best LLM Guardrails Tools (2026): 9 Platforms Compared
  63. ✓AI Agent Guardrails in Python: Block Injection, Redact PII
  64. ✓NeMo Guardrails vs Guardrails AI: Which to Choose (2026)
  65. ✓AI-Based PII Detection and Redaction Tools for LLM Apps
  66. ✓Stop Secrets Leaking Into LLM Logs and Traces
  67. ✓AI Agent Code Execution Sandbox: Run LLM Code Safely
  68. ✓AI Agent Network Egress: Limit Where Agents Can Connect
  69. ✓AutoGen Docker Task Isolation: Secure the Code Executor
  70. ✓SPIFFE for AI Agents: Workload Identity Without API Keys
  71. ✓On-Behalf-Of Auth for AI Agents: Act as Each User
  72. ✓AI Agent Production Checklist: What to Check Before Launch
  73. ✓Approval Fatigue: Auto-Approve Safe AI Agent Actions
  74. ✓What Is Human in the Loop AI? Approvals for AI Agents
  75. ✓AI Agent Notifications: Webhook and Slack Alerts in Python
  76. ✓AI Agent Observability: Trace Tool Calls, Tokens and Cost
  77. ✓Best AI Agent Observability Tools (2026), Compared
  78. ✓AI Agent Stuck in a Loop? How to Detect and Stop It
  79. ✓How to Run, Debug and Deploy an AI Agent in Python
  80. ✓AI Agent Cost Tracking: Tokens and Cost per Run and User
  81. ✓How to Evaluate AI Agents: Evals, LLM Judges and pass^k
  82. ✓AI Agent Cost Control: Budgets That Stop Runaway Spend
  83. 83How to Test LLM Prompts and AI Agents in Python
  84. 84AI Agent Evals in CI: Run Them on Every Pull Request
  85. 85What Is an Agentic Runtime? AI Agent Runtimes Explained
  86. 86Autonomous AI Agent Runtime: Budgets, Crash Recovery, API
  87. 87Event-Driven AI Agents: Webhook, Cron and File Triggers
  88. 88AI Agent Cron Jobs: Run an Agent on a Schedule
  89. 89AI Agent Webhook Trigger: Run an Agent on HTTP Events
  90. 90AI Agent File Watcher: Process New Files Automatically
  91. 91Custom AI Agent Triggers: Wake an Agent From Any Source
  92. 92AI Agent Event Filters: Skip Runs Before the LLM
  93. 93AI Agent Retries and a Dead Letter Queue for Failed Runs
  94. 94Run Multiple AI Agents: One Runtime, Many Processes
  95. 95AI Agent Manifest: Declare a Long-Running Agent in YAML
  96. 96AI Agent CLI: Start, Stop and Inspect Running Agents
  97. 97AI Agent Monitoring Dashboard in the Terminal
  98. 98Multi-Agent Event Bus: Chain Agents With Events
  99. 99Distributed AI Agents: Run Agents Across Many Machines
  100. 100Pause and Resume an AI Agent: Lifecycle States Explained
← Path overview

You changed one line in a prompt, and something three features away broke. Nobody noticed for a week. Testing LLM prompts fixes that, but not the way you test normal code: the same input can give a different answer on the next run, and "correct" is sometimes a judgement call. In this guide you'll build a pytest suite for a prompt that turns support emails into tickets: free unit tests with a mocked model, regression tests against the real model, a second model that grades what code can't, and tests for an AI agent's tool calls. You'll also learn to find the cases that fail only sometimes, and to compare prompt versions before you ship one. Every snippet runs on Promptise Foundry 1.9.0 with openai:gpt-5-mini, and every output is what it printed.

[01]

How do you test LLM prompts?

Treat the prompt as a function with a typed result, and test it in layers. Unit tests mock the model and check your own code: parsing, validation and guards. They're free and run on every push. Regression tests run a fixed set of real inputs with known answers through the real model and assert on the fields, with plain code. For what code can't check, such as whether a summary invents facts, a second model grades the output.

With Promptise Foundry, a prompt is a decorated Python function. Its docstring is the template, and its return type is what you get back:

Pythonticket_prompt.py
1
2
3
4
5
6
7
8
@prompt(model="openai:gpt-5-mini")
async def extract_ticket(email: str) -> Ticket:
    """You triage email for an online shop's support team.
    Read the email and fill in a ticket.

    Email:
    {email}
    """

Because the result is a typed object, a regression test is ordinary pytest:

Pythontest_ticket_llm.py
@pytest.mark.parametrize("case", CASES, ids=[c["id"] for c in CASES])
async def test_extracts_the_right_fields(case):
    ticket = await ticket_for(case)
    for field, expected in case["expect"].items():
        assert getattr(ticket, field) == expected, f"{field} was {getattr(ticket, field)!r}"

The rest of this guide builds the whole suite around those two pieces, then points the same approach at an agent.


[02]

How do the test layers fit together?

Each layer answers a different question, at a different price. Run the cheap ones all the time and the expensive ones when they can tell you something new.

Rendering diagram…

Layer

What it catches

Promptise piece

When to run it

Cost

Unit tests

Parsing, schema, guards, prompt text

PromptTestCase, mock_llm

Every push

Free, under a second

Golden cases

Wrong fields from the real model

@prompt with a typed result

When a prompt or model changes

One model call per case

LLM judge

Summaries that invent facts

A second @prompt

In the same run

A few judge calls per case

Repeated runs

Cases that pass only sometimes

registry, a small script

Before you ship a prompt version

The golden cases, several times over

Agent scenarios

Wrong tool, wrong order, a forbidden call

build_agent, MCP TestClient

When a prompt or tool changes

A few agent runs


[03]

What you need

  • Python 3.10 or newer.

  • Promptise Foundry, pytest and pytest-asyncio. This guide uses pytest 9.1.1 and pytest-asyncio 1.4.0; pydantic comes with Promptise.

  • An API key for a model provider. The examples use OpenAI's gpt-5-mini; other providers work by changing the model string, as listed in Models & Providers.

>_Terminal
pip install promptise pytest pytest-asyncio
export OPENAI_API_KEY="sk-..."

[04]

How to build a prompt regression suite, step by step

The prompt reads a support email and fills in a ticket: who wrote it, which order, what kind of problem, how urgent, and a one-line summary. It's small enough to read in one go and has the same failure modes as a big one.

Step 01

Write the prompt as a typed function

@prompt turns a function into a prompt. The docstring is the template, the arguments fill {email}, and the return type tells Promptise what to send back. For a pydantic model, Promptise adds the model's JSON schema to the prompt and parses the answer into a Ticket, so a malformed answer fails loudly instead of flowing on as a dict.

Pythonticket_prompt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from typing import Literal

from pydantic import BaseModel, Field

from promptise.prompts import prompt
from promptise.prompts.registry import version


class Ticket(BaseModel):
    customer_email: str
    order_id: str | None = Field(description='The order ID, for example "A-1042", or null if the email has none.')
    category: Literal["refund", "shipping", "account", "other"]
    urgency: Literal["low", "normal", "high"]
    summary: str = Field(description="One sentence a support agent can read at a glance.")


@version("1.0.0")
@prompt(model="openai:gpt-5-mini")
async def extract_ticket(email: str) -> Ticket:
    """You triage email for an online shop's support team.
    Read the email and fill in a ticket.

    Email:
    {email}
    """

@version("1.0.0") registers this prompt in Promptise's prompt registry. You'll use it in Step 6 to compare versions side by side. To see the exact text the model receives, call extract_ticket.render(email="..."); it builds the prompt, schema included, without calling the model.

Step 02

Collect real cases with known answers

A regression suite is only as good as its cases. Take them from real traffic, and keep the awkward ones: the customer who types the order ID in lowercase, the email forwarded by a colleague, the one in German. Each case says which fields a correct ticket must have:

Pythoncases.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
CASES = [
    {
        "id": "broken-item",
        "email": "From: dana@example.com\nSubject: Broken mug\n\n"
        "Hi, my order A-1001 arrived today and the mug is broken. I'd like my money back please.",
        "expect": {"customer_email": "dana@example.com", "order_id": "A-1001", "category": "refund"},
    },
    {
        "id": "late-delivery",
        "email": "From: tom@example.com\nSubject: Where is my lamp?\n\n"
        "I ordered a desk lamp two weeks ago, order A-1077, and it still hasn't arrived. "
        "The tracking page hasn't changed in six days.",
        "expect": {"customer_email": "tom@example.com", "order_id": "A-1077", "category": "shipping"},
    },
    {
        "id": "password-reset",
        "email": "From: lee@example.com\nSubject: Can't log in\n\n"
        "I forgot my password and the reset link you emailed me has expired. How do I get back into my account?",
        "expect": {"customer_email": "lee@example.com", "order_id": None, "category": "account"},
    },
    {
        "id": "lowercase-order-id",
        "email": "From: priya@example.com\nSubject: wrong size\n\n"
        "hey, got order a1042 yesterday but the shoes are a size too small. can i return them for a refund?",
        "expect": {"customer_email": "priya@example.com", "order_id": "A-1042", "category": "refund"},
    },
    {
        "id": "two-orders",
        "email": "From: sam@example.com\nSubject: Refund for A-1200\n\n"
        "Hi, the jacket from order A-1200 doesn't fit, so I'd like a refund for it. "
        "My other order, A-1188, arrived fine, thanks!",
        "expect": {"customer_email": "sam@example.com", "order_id": "A-1200", "category": "refund"},
    },
    {
        "id": "forwarded",
        "email": "From: frontdesk@shop.example\nSubject: Fwd: package\n\n"
        "Forwarding this from a customer who called in.\n\n"
        "---------- Forwarded message ----------\n"
        "From: mira@example.com\n"
        "My package for order A-1110 says delivered but it's not here.",
        "expect": {"customer_email": "mira@example.com", "order_id": "A-1110", "category": "shipping"},
    },
    {
        "id": "german",
        "email": "From: jonas@example.de\nSubject: Paket nicht angekommen\n\n"
        "Hallo, meine Bestellung A-1234 sollte letzte Woche ankommen, aber das Paket ist immer noch nicht da. "
        "Können Sie bitte nachsehen, wo es ist?",
        "expect": {"customer_email": "jonas@example.de", "order_id": "A-1234", "category": "shipping"},
    },
    {
        "id": "no-order",
        "email": "From: alex@example.com\nSubject: Gift cards?\n\n"
        "Do you sell gift cards, and can they also be used in your shop in town?",
        "expect": {"customer_email": "alex@example.com", "order_id": None, "category": "other"},
    },
]

Only assert on fields with one right answer. urgency is left out on purpose: two careful people could disagree about it, and a test that fails on a judgement call teaches you to ignore failures.

Step 03

Check fields with code and summaries with a judge

The summary is free text, so no assert == can check it. A second model can: give it the email, the summary and a short rubric, and ask for a verdict. That's what people mean by LLM as a judge. Promptise doesn't ship a judge for prompts, but a judge is just another prompt:

Pythonjudge.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from promptise.prompts import prompt


@prompt(model="openai:gpt-5-mini")
async def grade_summary(email: str, summary: str) -> str:
    """You review ticket summaries written for a support team.
    A summary is faithful when every fact in it is stated in the email
    and it names the customer's main problem. Wording may differ.

    Answer PASS or FAIL on the first line, then one sentence explaining why.

    Email:
    {email}

    Summary:
    {summary}
    """


def is_faithful(verdict: str) -> bool:
    return verdict.strip().upper().startswith("PASS")

Keep the verdict plain text. A judge that returns a pydantic model now and then answers with the shape of the JSON schema instead of a verdict, and the parse error crashes the test run. PASS or FAIL on one line can't go wrong that way, and the reason is still there for you to read.

Now the test file. Fields are checked with code. The summary goes to the judge three times, and the majority wins, because the judge is a model too and wobbles. The last test checks the judge itself: given a summary with an invented fact, it has to say FAIL.

Pythontest_ticket_llm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import asyncio

import pytest

from cases import CASES
from judge import grade_summary, is_faithful
from ticket_prompt import extract_ticket

pytestmark = pytest.mark.llm

_tickets = {}


async def ticket_for(case):
    """Extract each case once, so both tests below share one model call."""
    if case["id"] not in _tickets:
        _tickets[case["id"]] = await extract_ticket(case["email"])
    return _tickets[case["id"]]


@pytest.mark.parametrize("case", CASES, ids=[c["id"] for c in CASES])
async def test_extracts_the_right_fields(case):
    ticket = await ticket_for(case)
    for field, expected in case["expect"].items():
        assert getattr(ticket, field) == expected, f"{field} was {getattr(ticket, field)!r}"


@pytest.mark.parametrize("case", CASES, ids=[c["id"] for c in CASES])
async def test_summary_is_faithful(case):
    ticket = await ticket_for(case)
    # The judge is a model too. Ask it three times and go with the majority.
    verdicts = await asyncio.gather(*(grade_summary(email=case["email"], summary=ticket.summary) for _ in range(3)))
    assert sum(is_faithful(v) for v in verdicts) >= 2, f"{ticket.summary!r}: {verdicts}"


async def test_the_judge_catches_an_invented_fact():
    verdict = await grade_summary(
        email=CASES[0]["email"],
        summary="The customer wants to exchange the broken mug for a teapot.",
    )
    assert not is_faithful(verdict)

pytestmark = pytest.mark.llm tags every test in the file. That one marker is what lets CI run the free tests on every push and the paid ones only when they matter.

Step 04

Configure pytest for real model calls

Two small files make the suite behave. pytest.ini declares the marker and runs async tests automatically:

Textpytest.ini
1
2
3
4
5
6
7
8
[pytest]
asyncio_mode = auto
# One event loop for the whole run. The OpenAI client is shared between calls,
# and a new loop per test leaves it bound to a closed one.
asyncio_default_test_loop_scope = session
asyncio_default_fixture_loop_scope = session
markers =
    llm: calls a real model, so it is slow and costs money

The loop scope matters more than it looks. pytest-asyncio gives each test a fresh event loop by default, while LangChain, which Promptise uses to call models, caches one HTTP client for the whole process. The first test works and the next ones fail with RuntimeError: Event loop is closed. One loop per session avoids it.

conftest.py adds up the tokens of every model call and prints the cost at the end of the run:

Pythonconftest.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import pytest
from langchain_core.callbacks import get_usage_metadata_callback

# USD per million tokens for openai:gpt-5-mini. Check your provider's current prices.
PRICE_INPUT = 0.25
PRICE_OUTPUT = 2.00
totals = {"input": 0, "output": 0}


@pytest.fixture(autouse=True)
def count_tokens():
    """Add up the tokens of every model call a test makes."""
    with get_usage_metadata_callback() as usage:
        yield
    for model_usage in usage.usage_metadata.values():
        totals["input"] += model_usage["input_tokens"]
        totals["output"] += model_usage["output_tokens"]


def pytest_terminal_summary(terminalreporter):
    if totals["input"]:
        cost = (totals["input"] * PRICE_INPUT + totals["output"] * PRICE_OUTPUT) / 1_000_000
        terminalreporter.write_line(
            f"LLM usage: {totals['input']} input + {totals['output']} output tokens = ${cost:.4f}"
        )

The prices are OpenAI's list prices for gpt-5-mini at the time of writing. Promptise's own stats (extract_ticket.last_stats) also have input_tokens and output_tokens, but only for the last call of one prompt. The usage callback adds up every model call a test makes, the judge's included.

Step 05

Run it and read the failures

>_Terminal
pytest -m llm
Output
collected 27 items / 7 deselected / 20 selected

test_agent.py ...                                                        [ 15%]
test_ticket_llm.py ...F.............                                     [100%]

=================================== FAILURES ===================================
______________ test_extracts_the_right_fields[lowercase-order-id] ______________
…
E           AssertionError: order_id was 'A1042'
E           assert 'A1042' == 'A-1042'
…
LLM usage: 7426 input + 9307 output tokens = $0.0205
=========================== short test summary info ============================
FAILED test_ticket_llm.py::test_extracts_the_right_fields[lowercase-order-id]
============ 1 failed, 19 passed, 7 deselected in 104.81s (0:01:44) ============

The three test_agent.py tests are the agent scenarios from later in this guide; they share the llm marker. Of the other seventeen, one failed:

  • The order ID came back half fixed. The customer wrote a1042, and the model returned A1042. Your order system stores A-1042, so A1042 won't match anything. The schema said "for example A-1042", and the model took that as a hint, not a rule.

  • Every summary passed, and the judge still caught the invented teapot.

Run it again without changing anything, and the result can change: the order ID case passes some runs and fails others. That isn't a broken test. It's the most important thing to understand about testing LLM prompts: one run tells you a case can fail, not how often.

Step 06

Measure how often each case passes

To know how often a case fails, run it several times and count. This script does that for any registered version of the prompt, checking fields and asking the judge once per run:

Pythonrepeat.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
"""Run every case several times against one prompt version and count the passes."""
import asyncio
import sys
from collections import Counter

from langchain_core.callbacks import get_usage_metadata_callback

import ticket_prompt  # noqa: F401  registers extract_ticket 2.1.0
import ticket_prompt_v1  # noqa: F401  registers extract_ticket 1.0.0
import ticket_prompt_v2  # noqa: F401  registers extract_ticket 2.0.0
from cases import CASES
from judge import grade_summary, is_faithful
from promptise.prompts.registry import registry

PRICE_INPUT, PRICE_OUTPUT = 0.25, 2.00  # USD per million tokens for openai:gpt-5-mini
limit = asyncio.Semaphore(8)


async def run_once(extract, case):
    async with limit:
        try:
            ticket = await extract(case["email"])
        except Exception as error:
            return type(error).__name__, False
        wrong = [f"{f}={getattr(ticket, f)!r}" for f, v in case["expect"].items() if getattr(ticket, f) != v]
        verdict = await grade_summary(email=case["email"], summary=ticket.summary)
        return (", ".join(wrong) or "ok"), is_faithful(verdict)


async def main(ver: str, runs: int):
    extract = registry.get("extract_ticket", ver)
    with get_usage_metadata_callback() as usage:
        results = await asyncio.gather(*(run_once(extract, c) for c in CASES for _ in range(runs)))
    print(f"extract_ticket {ver}, {runs} runs per case")
    for i, case in enumerate(CASES):
        mine = results[i * runs : (i + 1) * runs]
        fields = sum(r == "ok" for r, _ in mine)
        judge = sum(faithful for _, faithful in mine)
        misses = Counter(r for r, _ in mine if r != "ok")
        print(f"  {case['id']:<20} fields {fields:>2}/{runs}  judge {judge:>2}/{runs}  {dict(misses) or ''}")
    tokens = next(iter(usage.usage_metadata.values()))
    cost = (tokens["input_tokens"] * PRICE_INPUT + tokens["output_tokens"] * PRICE_OUTPUT) / 1_000_000
    print(f"{tokens['input_tokens']} input + {tokens['output_tokens']} output tokens = ${cost:.4f}, "
          f"${cost / runs:.4f} per pass over all {len(CASES)} cases")


asyncio.run(main(sys.argv[1], int(sys.argv[2])))

The script imports every version you keep. Save the prompt from Step 1 as ticket_prompt_v1.py, so registry.get("extract_ticket", "1.0.0") can fetch it by version while ticket_prompt.py moves on. Here it is, five runs per case:

>_Terminal
python repeat.py 1.0.0 5
Output
extract_ticket 1.0.0, 5 runs per case
  broken-item          fields  5/5  judge  5/5  
  late-delivery        fields  5/5  judge  5/5  
  password-reset       fields  5/5  judge  5/5  
  lowercase-order-id   fields  3/5  judge  5/5  {"order_id='A1042'": 2}
  two-orders           fields  5/5  judge  5/5  
  forwarded            fields  5/5  judge  5/5  
  german               fields  5/5  judge  5/5  
  no-order             fields  5/5  judge  5/5  
19129 input + 21169 output tokens = $0.0471, $0.0094 per pass over all 8 cases

Read it per case:

  • The order ID is a real bug. It's a case that passes some runs and fails others, which is exactly the kind a single CI run lets through.

  • The misses column tells you what to fix. Every miss is the same wrong spelling, A1042, so the fix is a rule about the format, not a new example.

  • Every answer parsed. All replies were valid tickets. Keep that in mind for the next step.

Repeated runs cost the golden cases several times over, which is still cheap enough to do before every prompt change you ship.

Step 07

Fix the prompt and compare versions

The first attempt at a fix, version 2.0.0, adds a rule for order IDs, a pattern on the field so a wrong ID fails validation, and a summary that also says what the customer wants:

Pythonticket_prompt_v2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from typing import Literal

from pydantic import BaseModel, Field

from promptise.prompts import prompt
from promptise.prompts.registry import version


class Ticket(BaseModel):
    customer_email: str
    order_id: str | None = Field(
        pattern=r"^A-\d{4}$",
        description='The order ID, for example "A-1042", or null if the email has none.',
    )
    category: Literal["refund", "shipping", "account", "other"]
    urgency: Literal["low", "normal", "high"]
    summary: str = Field(description="One sentence: the customer's problem and what they want us to do.")


@version("2.0.0")
@prompt(model="openai:gpt-5-mini")
async def extract_ticket(email: str) -> Ticket:
    """You triage email for an online shop's support team.
    Read the email and fill in a ticket.

    Rules:
    - Write order IDs the way our system stores them: a capital A, a hyphen and
      four digits, such as A-1234, even when the customer writes a1234 or #A1234.

    Email:
    {email}
    """

It makes things worse:

>_Terminal
python repeat.py 2.0.0 5
Output
extract_ticket 2.0.0, 5 runs per case
  broken-item          fields  3/5  judge  3/5  {'ValidationError': 2}
  late-delivery        fields  5/5  judge  1/5  
  password-reset       fields  3/5  judge  3/5  {'ValidationError': 2}
  lowercase-order-id   fields  3/5  judge  3/5  {'ValidationError': 2}
  two-orders           fields  3/5  judge  3/5  {'ValidationError': 2}
  forwarded            fields  5/5  judge  0/5  
  german               fields  2/5  judge  2/5  {'ValidationError': 3}
  no-order             fields  0/5  judge  0/5  {'ValidationError': 5}
19756 input + 27611 output tokens = $0.0602, $0.0120 per pass over all 8 cases

Two regressions, both caught before anyone shipped them:

  • Asking for "what they want us to do" made the model invent requests. Most of these emails never state one, so the model makes one up, and the judge fails the summary. That's why late-delivery and forwarded pass the fields and fail the judge.

  • Answers stopped parsing. Each ValidationError here is the model answering with the JSON schema itself, a "properties" object, instead of a ticket. Promptise asks for JSON in the prompt text rather than through the provider's structured output mode, and the longer prompt made gpt-5-mini get that wrong far more often. A run counts as a judge failure when extraction crashed, which is why those columns drop together.

Version 2.1.0 keeps the order ID rule and the pattern, asks for a summary built only from the email, and says plainly where the fields go. It also adds a guard, which you'll test in the next step:

Pythonticket_prompt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from typing import Literal

from pydantic import BaseModel, Field

from promptise.prompts import prompt
from promptise.prompts.guards import GuardError, guard, output_validator
from promptise.prompts.registry import version


class Ticket(BaseModel):
    customer_email: str
    order_id: str | None = Field(
        pattern=r"^A-\d{4}$",
        description='The order ID, for example "A-1042", or null if the email has none.',
    )
    category: Literal["refund", "shipping", "account", "other"]
    urgency: Literal["low", "normal", "high"]
    summary: str = Field(description="One sentence: the customer's problem, using only facts from the email.")


def not_our_own_address(ticket: Ticket) -> Ticket:
    """A forwarded email belongs to the customer, never to our own staff."""
    if ticket.customer_email.endswith("@shop.example"):
        raise GuardError(f"customer_email is our own address: {ticket.customer_email}", guard_name="own_address")
    return ticket


@version("2.1.0")
@prompt(model="openai:gpt-5-mini")
@guard(output_validator(not_our_own_address))
async def extract_ticket(email: str) -> Ticket:
    """You triage email for an online shop's support team.
    Read the email and fill in a ticket.

    Rules:
    - Write order IDs the way our system stores them: a capital A, a hyphen and
      four digits, such as A-1234, even when the customer writes a1234 or #A1234.
    - In a forwarded email, the customer is the original sender, not our staff.
    - Put the ticket's fields at the top level of your JSON, not inside "properties".

    Email:
    {email}
    """
>_Terminal
python repeat.py 2.1.0 5
Output
extract_ticket 2.1.0, 5 runs per case
  broken-item          fields  5/5  judge  5/5  
  late-delivery        fields  5/5  judge  5/5  
  password-reset       fields  5/5  judge  5/5  
  lowercase-order-id   fields  5/5  judge  5/5  
  two-orders           fields  5/5  judge  5/5  
  forwarded            fields  5/5  judge  5/5  
  german               fields  5/5  judge  5/5  
  no-order             fields  5/5  judge  5/5  
23056 input + 25780 output tokens = $0.0573, $0.0115 per pass over all 8 cases

Every field right, no parse errors, and every summary passed. The order ID rule fixed the spelling, and the "top level" rule stopped the schema echo. A clean table is the bar for shipping, not proof the prompt is perfect: five runs per case won't show a failure that happens one time in fifty.

How many runs it takes to see a failure at least once: a case that fails 50% of the time shows up within 5 runs almost always, one that fails 30% of the time needs about 9 runs for a 95% chance, and one that fails 10% of the time needs 29.
FigureHow many runs it takes to see a failure that happens only sometimes
Tip

Keep every version you compared, with its repeat.py table. When someone asks why the prompt has a line about "properties", the answer is in the 2.0.0 table.

Step 08

Lock the fix in with free unit tests

Each fix deserves a test that costs nothing to run. PromptTestCase from Promptise patches the model call, so run_prompt returns whatever string you give mock_llm, pushed through the same parsing, validation and guards as a real answer. These tests run in well under a second, with no API key:

Pythontest_ticket_unit.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import pytest
from pydantic import ValidationError

from promptise.prompts.guards import GuardError
from promptise.prompts.testing import PromptTestCase
from ticket_prompt import Ticket, extract_ticket

GOOD = (
    '{"customer_email": "dana@example.com", "order_id": "A-1001", "category": "refund", '
    '"urgency": "high", "summary": "The mug in order A-1001 arrived broken; she wants a refund."}'
)


class TestExtractTicket(PromptTestCase):
    prompt = extract_ticket

    async def test_parses_the_model_json_into_a_ticket(self):
        with self.mock_llm(GOOD):
            ticket = await self.run_prompt("any email")
        self.assert_schema(ticket, Ticket)
        assert ticket.order_id == "A-1001"

    async def test_accepts_json_inside_a_markdown_fence(self):
        with self.mock_llm(f"```json\n{GOOD}\n```"):
            ticket = await self.run_prompt("any email")
        assert ticket.category == "refund"

    async def test_rejects_an_unknown_category(self):
        with self.mock_llm(GOOD.replace('"refund"', '"complaint"')):
            with pytest.raises(ValidationError):
                await self.run_prompt("any email")

    async def test_rejects_a_malformed_order_id(self):
        with self.mock_llm(GOOD.replace("A-1001", "a1001")):
            with pytest.raises(ValidationError):
                await self.run_prompt("any email")

    async def test_refuses_our_own_address_as_the_customer(self):
        with self.mock_llm(GOOD.replace("dana@example.com", "frontdesk@shop.example")):
            with pytest.raises(GuardError) as error:
                await self.run_prompt("any email")
        assert error.value.guard_name == "own_address"

    def test_the_prompt_sends_the_schema(self):
        text = extract_ticket.render(email="any email")
        assert '"required"' in text and "customer_email" in text
>_Terminal
pytest -m "not llm"
Output
collected 27 items / 20 deselected / 7 selected

test_agent.py .                                                          [ 14%]
test_ticket_unit.py ......                                               [100%]

======================= 7 passed, 20 deselected in 0.43s =======================

What each kind of test protects:

  • The pattern turns a silent bug into a loud one. Run against version 1.0.0, test_rejects_a_malformed_order_id fails with DID NOT RAISE ValidationError: a wrong ID would have flowed into your system as data. Now it raises, and your code can retry or flag the ticket.

  • The guard runs on every call, in production too. output_validator wraps any function as an output guard. It runs after the answer is parsed, so it receives the Ticket, and a GuardError stops the bad ticket before your code sees it. Use guards for rules a schema can't express, like "never file a ticket under our own address".

  • The prompt text is tested too. render() returns the exact text the model gets, so you can assert that a rule or the schema is still there after someone edits the docstring.

If several prompts share the same rules, a PromptSuite applies its default_guards and default_constraints to every prompt in the suite, so one guard covers them all.

These tests can't tell you whether the model follows the rules. That's what the llm suite and repeat.py are for.


[05]

How do you evaluate an AI agent's tool calls?

An agent adds a new kind of failure: it can call the wrong tool, call the right one at the wrong time, or call one it should never touch. You test that by giving it a task and asserting on the tool calls it made, not on its wording.

Here is a two-tool MCP server for the agent:

Pythonshop_server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from promptise.mcp.server import MCPServer, ToolError

server = MCPServer("shop")

# A stand-in for your order system.
ORDERS = {
    "A-1001": {"item": "Ceramic mug", "total": 18.50, "status": "delivered"},
    "A-1002": {"item": "Standing desk", "total": 1240.00, "status": "in transit"},
}


@server.tool()
async def get_order(order_id: str) -> dict:
    """Look up an order: item, total in USD and delivery status."""
    order = ORDERS.get(order_id)
    if order is None:
        raise ToolError(f"There is no order {order_id}.")
    return {"order_id": order_id, **order}


@server.tool()
async def issue_refund(order_id: str, amount: float) -> dict:
    """Refund money to the customer. Only for delivered orders."""
    order = ORDERS.get(order_id)
    if order is None:
        raise ToolError(f"There is no order {order_id}.")
    if amount > order["total"]:
        raise ToolError(f"Refund {amount} is more than the order total {order['total']}.")
    return {"order_id": order_id, "amount": amount, "status": "refunded"}


if __name__ == "__main__":
    server.run()

The tests come in two kinds. The first checks the tool's own rule with Promptise's MCP TestClient, which calls the tool in memory with no model involved, so it's free and exact. The others run the real agent through three scenarios and check which tools it called, and in what order:

Pythontest_agent.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import sys

import pytest

from promptise import build_agent
from promptise.config import StdioServerSpec
from promptise.mcp.server import TestClient
from shop_server import server

SCENARIOS = [
    {
        "id": "refund-a-delivered-order",
        "ask": "Order A-1001 arrived broken. Please refund it in full.",
        "must_call": ["get_order", "issue_refund"],
        "must_not_call": [],
    },
    {
        "id": "refuse-an-order-in-transit",
        "ask": "Refund order A-1002 please, it's late.",
        "must_call": ["get_order"],
        "must_not_call": ["issue_refund"],
    },
    {
        "id": "answer-without-tools",
        "ask": "What are your opening hours?",
        "must_call": [],
        "must_not_call": ["get_order", "issue_refund"],
    },
]


def tool_calls(result):
    """Every tool call the model asked for, in order, as (name, arguments)."""
    return [
        (call["name"], call["args"])
        for message in result["messages"]
        for call in getattr(message, "tool_calls", None) or []
    ]


async def test_the_refund_tool_refuses_more_than_the_total():
    """The tool's own rules, tested without a model."""
    result = await TestClient(server).call_tool("issue_refund", {"order_id": "A-1001", "amount": 99.0})
    assert "more than the order total" in result[0].text


@pytest.fixture(scope="module")
async def agent():
    agent = await build_agent(
        model="openai:gpt-5-mini",
        servers={"shop": StdioServerSpec(command=sys.executable, args=["shop_server.py"])},
        instructions=(
            "You are a support assistant for an online shop. Look up an order before "
            "you act on it. Only refund orders that have been delivered."
        ),
    )
    yield agent
    await agent.shutdown()


@pytest.mark.llm
@pytest.mark.parametrize("scenario", SCENARIOS, ids=[s["id"] for s in SCENARIOS])
async def test_the_agent_uses_the_right_tools(agent, scenario):
    result = await agent.ainvoke({"messages": [{"role": "user", "content": scenario["ask"]}]})
    names = [name for name, _ in tool_calls(result)]
    for name in scenario["must_call"]:
        assert name in names, f"expected a call to {name}, got {names}"
    for name in scenario["must_not_call"]:
        assert name not in names, f"{name} must not be called, got {names}"
    if "issue_refund" in names:
        assert names.index("get_order") < names.index("issue_refund"), "refunded before looking up"
>_Terminal
pytest -m llm test_agent.py -q
Output
...                                                                      [100%]
LLM usage: 1500 input + 1711 output tokens = $0.0038
3 passed, 1 deselected in 24.69s

A few things make agent tests hold up:

  • Assert on actions, not words. tool_calls reads the calls the model asked for from the agent's messages. Whether it says "I've refunded" or "Your refund is on its way" doesn't matter; whether issue_refund ran does.

  • Test the refusals. The most valuable scenario is the one where the agent must not act: the desk is still in transit, so no refund.

  • Build the agent once per module. Starting the agent and its MCP server takes a moment, so the fixture shares one agent across the scenarios. Each ainvoke gets only the messages you pass it.

  • Repeat the scenarios before you ship. Agent scenarios are model runs too, so a scenario that passes once can fail on the next run. Run them several times when a prompt or tool changes.

If your tools come from an existing REST API, MCPcast's --eval option goes further: a model writes realistic tasks for the generated server and a real agent tries each one, as shown in OpenAPI to MCP: Turn Any REST API into an MCP Server.


[06]

How to run prompt regression tests in CI

Split the suite by price, using the marker:

>_Terminal
pytest -m "not llm"
pytest -m llm
  • Every push: the first command. No API key, no cost, under a second for this suite. It catches broken parsing, a deleted rule, a guard that stopped firing.

  • When a prompt, a model or a tool changes, and nightly: the second. It needs OPENAI_API_KEY as a CI secret and prints its own cost through conftest.py. Running it nightly catches the changes you didn't make: a provider updating a model behind the same name.

  • Before you ship a new prompt version: repeat.py against the old and new versions, and compare the tables.

AI agent evals in CI shows a GitHub Actions workflow that runs model tests on every pull request.

Treat infrastructure errors as their own category. A DNS outage, or an account out of credit with Error code: 429 and insufficient_quota, says nothing about your prompt. Don't let them count as a prompt failure, and don't let a retry policy hide a real one.


[07]

What to watch out for

  • Output tokens dominate the bill. A ticket is a few dozen words, yet output tokens outnumber input tokens in the runs above. gpt-5-mini reasons before it answers, and OpenAI bills reasoning tokens as output, at eight times the input price.

  • You can't switch the randomness off. The usual advice is temperature 0. For gpt-5-mini that isn't available: LangChain drops any temperature other than the default for GPT-5 reasoning models, and @prompt takes only a model string anyway. Design the suite for variation instead of hoping it away.

  • Sample size is arithmetic. A case that fails 30% of the time slips through a single run 70% of the time. To see a failure that happens one time in ten with 95% confidence, you need 29 runs, because 0.9 to the power of 29 is about 0.05. A handful of runs per case won't prove a prompt is perfect; it will show you which cases need attention.

  • Retries belong in production, not in your tests. Promptise's retry() wraps a prompt and tries again on any exception, with exponential backoff that starts at one second, so a ValidationError or GuardError in production gets a second chance. Test without it: a prompt that needs retries to pass is a prompt you're paying for two or three times.

  • Judges wobble too. A judge can fail a borderline summary on one run and pass it on the next. Asking three times and taking the majority makes a single unlucky verdict much less likely to fail the run. Keep a test that proves the judge can fail, like test_the_judge_catches_an_invented_fact, so you know it isn't passing everything. LLM as a judge vs a jury goes deeper on making judges reliable.

  • Structured output is asked for in the prompt. Promptise appends the JSON schema to the prompt text and parses the reply; it doesn't use the provider's structured output mode. Expect the occasional reply in the schema's shape, keep the "top level" instruction, and catch ValidationError where it matters.

  • There's no built-in judge or eval runner for prompts. Promptise gives you typed prompts, PromptTestCase, guards and a version registry. The judge, the cases and the repeat loop are yours, as built above. MCPcast's evaluation covers generated MCP servers only.

  • Prompt stats cover one call. last_stats has latency_ms, input_tokens and output_tokens for a prompt's last call. For a whole test run, use LangChain's usage callback, as in conftest.py, or agent observability for agents.

  • Use the inspector to see what was sent. A PromptInspector passed as @prompt(inspect=...) records a trace on every call, with the text sent to the model, the output, the latency and the guard results. @prompt(observe=True) records each call as timeline events on the prompt's own collector instead. render() shows the text without calling the model.

  • schema_strict() takes no options. schema_strict(max_retries=2) raises TypeError. schema_strict() with no arguments works, and only checks string outputs.

  • The registry is per process. @version registers into an in-memory registry when the module is imported, and registering the same name and version twice raises ValueError. It's a way to load and compare versions in code, not a store that survives a restart.


[08]

Frequently asked questions

How do you evaluate LLM output in Python?

Split it into what code can check and what it can't. Parse the output into a typed object, then assert on the fields that have one right answer, such as IDs, categories and required fields. For free text, use a second model with a short rubric as a judge, ask it more than once, and check now and then that it can fail.

Can you trust an LLM as a judge?

Partly. A judge catches invented facts that no assert can, but it's a model too, and it can pass a borderline summary on one run and fail it on the next. Keep the rubric to one or two checkable rules, return a simple PASS or FAIL, take a majority vote, and read its reasons when it fails instead of trusting the count.

How do you unit test an AI agent?

Test its tools without a model, using an in-memory client like Promptise's MCP TestClient. Then run the agent through short scenarios and assert on the tool calls it made: which tools, in what order, and which ones it must never call. Don't assert on its wording.

Should I set temperature to 0 for LLM tests?

When the model supports it, it reduces variation but doesn't remove it, and reasoning models such as gpt-5-mini only accept the default temperature. Build the suite so it holds up under variation: assert on structured fields, run each case several times before shipping, and track pass rates instead of single results.

How much does it cost to test LLM prompts?

Less than people expect, as long as you split the suite. The unit tests cost nothing, so run them on every push. The model tests cost one call per case plus the judge calls, and conftest.py prints the total at the end of every run, so you always know. With gpt-5-mini, the 20 model tests in this guide print about two cents.


[09]

Where to go next

  • Prompt Testing: PromptTestCase, mock_llm and every assertion.

  • Guards: built-in guards and how to write your own.

  • Suite & Registry: group prompts with shared guards, and version them.

  • Inspector & Observability: tracing prompt assembly, with the limits above in mind.

  • Prompt chaining: retry, fallback and other ways to compose prompts.

  • MCP server testing: more on TestClient.

  • How to Connect MCP Servers to Your AI Agent in Python: the agent and MCP basics behind the agent tests.

  • How to Evaluate AI Agents: evals, LLM judges and pass^k for whole agent runs.

  • Testing MCP Servers in Python: the full pytest suite for the tools behind an agent.

  • How to Test AI Agent Memory: recall evals for agents that remember users.

← PreviousAI Agent Cost Control: Budgets That Stop Runaway SpendNext lesson →AI Agent Evals in CI: Run Them on Every Pull Request