Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 22 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,25 @@
# Changelog

## 0.9.0 (2026-11-06)

### Features

- **`--cassette-mode=record-missing`**: records only the cassettes that do not exist yet and replays the rest.
- **`iter_request_texts`**: every text a request sent the model, with where it sits, for any provider. See [README "Checking What the Model Was Sent"](README.md#checking-what-the-model-was-sent).
- **`assert_no_credential_urls`**: fails when a URL sent to the model carries a token, key, or signature. Values are never printed.
- **Cassette drift**: `drift="warn"` or `"fail"` also compares replayed tool results, message roles, and parameters with the recording. Off by default. See [README "Stale Cassette Detection"](README.md#stale-cassette-detection).

### Bug Fixes

- **`--cassette-report` leaves out files that are not cassettes.**
- **Failures point at the test**: pytest no longer shows agentverify's own frames when an assertion or a cassette fails, and `assert_all` indents each failure under its number.

### Documentation

- **A shorter README**: the details move to [docs/cassettes.md](docs/cassettes.md), [docs/tool-results.md](docs/tool-results.md), and the [API reference](docs/reference.md), which indexes every public name.
- **Expiry settings apply through the `cassette` fixture**, not to an `LLMCassetteRecorder` created directly.
- **The Strands example uses `strands.vended_tools.http_request`**, as the official sample now does (strands-agents-tools 0.9 removed its own), on a re-recorded cassette.

## 0.8.0 (2026-10-30)

### Features
Expand Down Expand Up @@ -56,7 +76,7 @@
### Features

- **Async agents**: the async clients of Anthropic, Gemini, and LiteLLM are recorded and replayed, as OpenAI's already were.
- **OpenAI Responses API** is recorded and replayed, so the OpenAI Agents SDK works on its default model. See [README "OpenAI Responses API"](README.md#openai-responses-api).
- **OpenAI Responses API** is recorded and replayed, so the OpenAI Agents SDK works on its default model. See [README "OpenAI Responses API"](docs/cassettes.md#openai-responses-api).
- **Multi-agent handoff assertions**: `assert_handoffs`, `assert_no_handoff`, and `assert_step(agent=...)`, via `ExecutionResult.handoffs` and `Step.agent`. See [README "Multi-Agent Handoffs"](README.md#multi-agent-handoffs).

### Bug Fixes
Expand All @@ -79,7 +99,7 @@

### Bug Fixes

- **Replay no longer reaches the real API.** Calls a cassette cannot replay, such as streaming, the Responses API, embeddings, or async Anthropic and Gemini clients, now raise `CassetteUnsupportedCallError` instead of calling the provider. See [README "Recorded and Unsupported Calls"](README.md#recorded-and-unsupported-calls).
- **Replay no longer reaches the real API.** Calls a cassette cannot replay, such as streaming, the Responses API, embeddings, or async Anthropic and Gemini clients, now raise `CassetteUnsupportedCallError` instead of calling the provider. See [README "Recorded and Unsupported Calls"](docs/cassettes.md#recorded-and-unsupported-calls).
- **Credentials passed as call arguments are redacted from cassettes**, such as `api_key=` or an `x-api-key` header. Default patterns also cover Google, Bedrock, AWS temporary, and GitHub keys. See [README "Cassette Sanitization"](README.md#cassette-sanitization).
- **OpenAI Agents SDK tool failures are detected**, so `assert_no_tool_errors` and `assert_tool_invocation_succeeded` no longer pass on them.

Expand Down
361 changes: 74 additions & 287 deletions README.md

Large diffs are not rendered by default.

8 changes: 8 additions & 0 deletions agentverify/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,16 @@
)
from agentverify.cassette.recorder import CassetteMode, LLMCassetteRecorder
from agentverify.cassette.sanitize import DEFAULT_PATTERNS, SanitizePattern
from agentverify.cassette.texts import iter_request_texts
from agentverify.credentials import assert_no_credential_urls
from agentverify.cassette.tools import cassette_tool
from agentverify.errors import (
CassetteDriftError,
CassetteExpiredError,
CassetteMissingRequestError,
CassetteRequestMismatchError,
CassetteToolMismatchError,
CredentialURLError,
CassetteUnsupportedCallError,
HandoffError,
RetryBudgetError,
Expand Down Expand Up @@ -110,12 +114,16 @@
# Cassette
"LLMCassetteRecorder",
"CassetteMode",
"CassetteDriftError",
"CassetteExpiredError",
"CassetteMissingRequestError",
"CassetteRequestMismatchError",
"CassetteUnsupportedCallError",
"CassetteToolMismatchError",
"CredentialURLError",
"cassette_tool",
"iter_request_texts",
"assert_no_credential_urls",
"SanitizePattern",
"DEFAULT_PATTERNS",
# Mocking
Expand Down
25 changes: 25 additions & 0 deletions agentverify/assertions.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""Assertion engine for agentverify.

Provides assertion functions for verifying tool call sequences, cost/token budgets, safety guardrails, and batch assertion execution.

Each assertion sets ``__tracebackhide__``, so pytest shows a failure at the test's own line rather than inside agentverify.
"""

from __future__ import annotations
Expand Down Expand Up @@ -68,6 +70,7 @@ def assert_tool_calls(
Raises:
ToolCallSequenceError: When a mismatch is detected.
"""
__tracebackhide__ = True
actual = result.tool_calls

if order == OrderMode.EXACT:
Expand All @@ -86,6 +89,7 @@ def _assert_exact(
partial_args: bool,
) -> None:
"""EXACT mode: same length and same tool calls at each position."""
__tracebackhide__ = True
if len(expected) != len(actual):
# first_mismatch_index is the first position that differs,
# or min(len(expected), len(actual)) if one list is shorter.
Expand Down Expand Up @@ -118,6 +122,7 @@ def _assert_in_order(

Uses a two-pointer approach: walk through actual looking for each expected element in order.
"""
__tracebackhide__ = True
if not expected:
return

Expand All @@ -143,6 +148,7 @@ def _assert_any_order(
partial_args: bool,
) -> None:
"""ANY_ORDER mode: all expected tool calls must exist in actual."""
__tracebackhide__ = True
for i, exp_tc in enumerate(expected):
found = any(
_tool_call_matches(exp_tc, act_tc, partial_args)
Expand Down Expand Up @@ -173,6 +179,7 @@ def assert_cost(
Raises:
CostBudgetError: When budget is exceeded or when strict=True and the required data is missing.
"""
__tracebackhide__ = True
if max_tokens is not None:
if result.token_usage is not None:
actual_tokens = result.token_usage.total_tokens
Expand Down Expand Up @@ -222,6 +229,7 @@ def assert_latency(
Raises:
LatencyBudgetError: When latency exceeds the threshold or when strict=True and duration_ms is None.
"""
__tracebackhide__ = True
if result.duration_ms is not None:
if result.duration_ms > max_ms:
raise LatencyBudgetError(
Expand Down Expand Up @@ -254,6 +262,7 @@ def assert_tool_calls_allowed(
ToolPolicyError: When a call is to a tool not in *allowed*, or its arguments miss the conditions.
ValueError: When *allowed* holds a schema keyword this assertion does not check.
"""
__tracebackhide__ = True
from agentverify._schema import check_schema, violations as schema_violations
from agentverify.errors import ToolPolicyError

Expand Down Expand Up @@ -292,6 +301,7 @@ def assert_no_tool_call(
Raises:
SafetyRuleViolationError: When forbidden tool calls are detected.
"""
__tracebackhide__ = True
forbidden_set = set(forbidden_tools)
violations: list[dict] = []

Expand Down Expand Up @@ -357,6 +367,7 @@ def assert_final_output(
Raises:
FinalOutputError: When the final output does not meet expectations.
"""
__tracebackhide__ = True
if contains is None and equals is None and matches is None:
raise ValueError(
"assert_final_output requires at least one of: contains, equals, matches"
Expand Down Expand Up @@ -414,6 +425,7 @@ def assert_all(
Raises:
MultipleAssertionError: When one or more assertions fail.
"""
__tracebackhide__ = True
errors: list[AgentVerifyError] = []

for assertion in assertions:
Expand Down Expand Up @@ -493,6 +505,7 @@ def assert_step(
ToolCallSequenceError: the step's tool calls don't match.
StepAgentError: the step's agent doesn't match.
"""
__tracebackhide__ = True
if agent is not None and expected_tool is None and expected_tools is None:
resolved_step = _resolve_step(result, step, name)
_assert_step_agent(resolved_step, agent)
Expand Down Expand Up @@ -522,13 +535,15 @@ def assert_step(


def _assert_step_agent(step_obj: Any, agent: Any) -> None:
__tracebackhide__ = True
from agentverify.errors import StepAgentError

if not _agent_matches(agent, step_obj.agent):
raise StepAgentError(step=step_obj.index, expected=agent, actual=step_obj.agent)


def _assert_step_exact(step_obj, expected, actual, partial_args) -> None:
__tracebackhide__ = True
if len(expected) != len(actual):
mismatch = min(len(expected), len(actual))
for i in range(mismatch):
Expand All @@ -554,6 +569,7 @@ def _assert_step_exact(step_obj, expected, actual, partial_args) -> None:


def _assert_step_in_order(step_obj, expected, actual, partial_args) -> None:
__tracebackhide__ = True
if not expected:
return
exp_idx = 0
Expand All @@ -573,6 +589,7 @@ def _assert_step_in_order(step_obj, expected, actual, partial_args) -> None:


def _assert_step_any_order(step_obj, expected, actual, partial_args) -> None:
__tracebackhide__ = True
for i, exp_tc in enumerate(expected):
if not any(_tool_call_matches(exp_tc, a, partial_args) for a in actual):
raise ToolCallSequenceError(
Expand All @@ -597,6 +614,7 @@ def assert_step_output(

Exactly one of ``step`` or ``name`` must be provided. At least one of ``contains``, ``equals``, or ``matches`` must be provided. ``contains`` and ``case_sensitive`` behave as in :func:`assert_final_output`.
"""
__tracebackhide__ = True
from agentverify.errors import StepOutputError

if contains is None and equals is None and matches is None:
Expand Down Expand Up @@ -664,6 +682,7 @@ def assert_step_uses_result_from(
depends_on: Step that should produce data. Same specifier rules.
via: One of ``"tool_result"``, ``"output"``, or ``"any"``. Restricts which channel of produced values is checked.
"""
__tracebackhide__ = True
from agentverify.errors import StepDependencyError

if via not in ("tool_result", "output", "any"):
Expand Down Expand Up @@ -905,6 +924,7 @@ def assert_tool_invocation_succeeded(
Raises:
ToolInvocationError: When any tool result at the step is a known error.
"""
__tracebackhide__ = True
resolved = _resolve_step(result, step, name)
violations: list[dict] = []
for i in range(len(resolved.tool_results)):
Expand All @@ -931,6 +951,7 @@ def assert_no_tool_errors(result: ExecutionResult) -> None:
Raises:
ToolInvocationError: When any tool result in the run is a known error.
"""
__tracebackhide__ = True
violations: list[dict] = []
for resolved in result.steps:
for i in range(len(resolved.tool_results)):
Expand Down Expand Up @@ -974,6 +995,7 @@ def assert_tool_result_matches(
Raises:
ToolResultMatchError: When no tool result matches, or the step has no tool results to match against.
"""
__tracebackhide__ = True
if (contains is None) == (matches is None):
raise ValueError(
"assert_tool_result_matches requires exactly one of: contains, matches"
Expand Down Expand Up @@ -1043,6 +1065,7 @@ def assert_retry_count(
Raises:
RetryBudgetError: When the observed retry count exceeds ``max``.
"""
__tracebackhide__ = True
if not isinstance(max, int) or isinstance(max, bool) or max < 0:
raise ValueError(
f"assert_retry_count requires max to be a non-negative int, got {max!r}"
Expand Down Expand Up @@ -1104,6 +1127,7 @@ def assert_handoffs(
Raises:
HandoffError: When the handoffs do not match.
"""
__tracebackhide__ = True
actual = result.handoffs
if order == OrderMode.EXACT:
ok = len(expected) == len(actual) and all(_handoff_matches(e, a) for e, a in zip(expected, actual))
Expand All @@ -1128,6 +1152,7 @@ def assert_no_handoff(
Raises:
HandoffError: When a matching handoff happened.
"""
__tracebackhide__ = True
if to_agent is None and from_agent is None:
raise ValueError("assert_no_handoff requires at least one of: to_agent, from_agent")
found = [
Expand Down
4 changes: 4 additions & 0 deletions agentverify/cassette/adapters/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from dataclasses import dataclass, field, fields, replace
from typing import TYPE_CHECKING, Any, Callable, Generator

from agentverify.errors import _own_error
from agentverify.models import TokenUsage

if TYPE_CHECKING:
Expand Down Expand Up @@ -543,6 +544,7 @@ def _replay_or_miss(
replayed: Callable[[NormalizedResponse], Any] | None,
) -> Any:
"""Return the replayed response, or ``_REPLAY_MISS`` when the real API should be called."""
__tracebackhide__ = _own_error
from agentverify.cassette.recorder import CassetteMode, OnMissingRequest
from agentverify.errors import CassetteMissingRequestError

Expand Down Expand Up @@ -637,6 +639,7 @@ def call_sync(
Streaming requests are recorded and replayed when the wire format is a :class:`StreamingWire`, and raise otherwise (or pass straight through in AUTO passthrough). Replay mode returns the recorded response, built by *replayed* (default: ``adapter.denormalize_response``); a miss calls the real API with ``on_missing=FALLBACK`` and raises otherwise. Record mode and AUTO passthrough call the real API and record the normalized response.
A call made while another intercepted call is reaching the real API in the same task or thread (litellm fallbacks, a tool that calls the model during Gemini automatic function calling) is part of that outer call: it runs unrecorded, because replaying the outer call never makes it.
"""
__tracebackhide__ = _own_error
if _live_call_allowed.get():
return call_real()
streaming = _streaming(adapter, kwargs)
Expand All @@ -661,6 +664,7 @@ async def call_async(
replayed: Callable[[NormalizedResponse], Any] | None = None,
) -> Any:
"""Async counterpart of :func:`call_sync`; *call_real* returns an awaitable."""
__tracebackhide__ = _own_error
if _live_call_allowed.get():
return await call_real()
streaming = _streaming(adapter, kwargs)
Expand Down
62 changes: 62 additions & 0 deletions agentverify/cassette/drift.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"""Drift: how a replayed request differs from its recording, beyond what request matching already compares.

Request matching fails on a changed model, tool names and schemas, system prompt, or user text. Drift covers the rest: tool results, the number and roles of the messages, and the provider's other parameters. It is off by default, since a tool that runs for real may return something new on every run.
"""

from __future__ import annotations

import re
from typing import Callable, Iterable

from agentverify.cassette.adapters.base import NormalizedRequest
from agentverify.cassette.texts import _NULLS, iter_request_texts

DRIFT = ("off", "warn", "fail")
_ANNOTATION = re.compile(r"\([^()]*\)")


def check_drift(value: str) -> str:
if value not in DRIFT:
raise ValueError(f"drift must be one of {', '.join(map(repr, DRIFT))}; got {value!r}")
return value


def compile_ignore(patterns: Iterable[str] | None) -> list[re.Pattern[str]]:
"""``drift_ignore`` globs over ``where``: ``*`` stands for anything, everything else is literal (brackets included). A glob may leave out the ``(role)`` and ``(tool)`` parts: ``request[*].message[*].tool_result[*].now``."""
return [re.compile("^" + re.escape(pattern).replace(r"\*", ".*") + "$") for pattern in patterns or []]


def _compared(request: NormalizedRequest, index: int, normalize: Callable[[str], str]) -> dict[str, str]:
texts: dict[str, str] = {}
token = _NULLS.set(True)
try:
for where, text in iter_request_texts(request):
where = f"request[{index}]" + where[len("request[0]") :]
if ".tool_result[" in where or where.startswith(f"request[{index}].parameters."):
texts[where] = normalize(text)
finally:
_NULLS.reset(token)
return texts


def _roles(request: NormalizedRequest) -> list[str]:
return [str(m.get("role") or m.get("type") or "message") if isinstance(m, dict) else "message" for m in request.messages or []]


def drift(recorded: NormalizedRequest, actual: NormalizedRequest, index: int, ignore: list[re.Pattern[str]], normalize: Callable[[str], str] = lambda s: s) -> list[str]:
"""The places where *actual* differs from *recorded*, as ``where`` strings (no values)."""
places: list[str] = []
recorded_roles, actual_roles = _roles(recorded), _roles(actual)
if recorded_roles != actual_roles:
places.append(f"request[{index}].messages (roles {','.join(recorded_roles)} → {','.join(actual_roles)})")
before, after = _compared(recorded, index, normalize), _compared(actual, index, normalize)
for where in sorted(set(before) | set(after)):
plain = _ANNOTATION.sub("", where) # globs may leave out the (role) and (tool) parts
if before.get(where) != after.get(where) and not any(p.match(where) or p.match(plain) for p in ignore):
places.append(where)
return places


def describe(places: list[str], limit: int = 5) -> str:
shown = ", ".join(places[:limit])
return shown + (f", and {len(places) - limit} more" if len(places) > limit else "")
Loading
Loading