agentverify 0.2.0__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. agentverify-0.4.0/PKG-INFO +832 -0
  2. agentverify-0.4.0/README.md +784 -0
  3. agentverify-0.4.0/agentverify/__init__.py +104 -0
  4. agentverify-0.4.0/agentverify/_step_builder.py +136 -0
  5. agentverify-0.4.0/agentverify/assertions.py +966 -0
  6. {agentverify-0.2.0 → agentverify-0.4.0}/agentverify/cassette/adapters/anthropic.py +64 -9
  7. {agentverify-0.2.0 → agentverify-0.4.0}/agentverify/cassette/adapters/base.py +2 -4
  8. {agentverify-0.2.0 → agentverify-0.4.0}/agentverify/cassette/adapters/bedrock.py +7 -15
  9. {agentverify-0.2.0 → agentverify-0.4.0}/agentverify/cassette/adapters/gemini.py +7 -14
  10. {agentverify-0.2.0 → agentverify-0.4.0}/agentverify/cassette/adapters/litellm.py +6 -13
  11. agentverify-0.4.0/agentverify/cassette/adapters/openai.py +360 -0
  12. {agentverify-0.2.0 → agentverify-0.4.0}/agentverify/cassette/io.py +1 -3
  13. agentverify-0.4.0/agentverify/cassette/recorder.py +562 -0
  14. {agentverify-0.2.0 → agentverify-0.4.0}/agentverify/cassette/sanitize.py +1 -2
  15. agentverify-0.4.0/agentverify/errors.py +378 -0
  16. {agentverify-0.2.0 → agentverify-0.4.0}/agentverify/fixtures.py +1 -2
  17. {agentverify-0.2.0 → agentverify-0.4.0}/agentverify/frameworks/__init__.py +1 -2
  18. agentverify-0.4.0/agentverify/frameworks/langchain.py +67 -0
  19. agentverify-0.4.0/agentverify/frameworks/langgraph.py +119 -0
  20. agentverify-0.4.0/agentverify/frameworks/openai_agents.py +193 -0
  21. agentverify-0.4.0/agentverify/frameworks/strands.py +157 -0
  22. {agentverify-0.2.0 → agentverify-0.4.0}/agentverify/markers.py +1 -2
  23. agentverify-0.4.0/agentverify/matchers.py +86 -0
  24. agentverify-0.4.0/agentverify/mocking.py +214 -0
  25. agentverify-0.4.0/agentverify/models.py +316 -0
  26. {agentverify-0.2.0 → agentverify-0.4.0}/agentverify/plugin.py +1 -3
  27. agentverify-0.4.0/agentverify/probe.py +126 -0
  28. agentverify-0.4.0/agentverify.egg-info/PKG-INFO +832 -0
  29. {agentverify-0.2.0 → agentverify-0.4.0}/agentverify.egg-info/SOURCES.txt +7 -1
  30. {agentverify-0.2.0 → agentverify-0.4.0}/agentverify.egg-info/requires.txt +2 -2
  31. {agentverify-0.2.0 → agentverify-0.4.0}/pyproject.toml +4 -4
  32. agentverify-0.4.0/tests/test_assertions.py +1520 -0
  33. {agentverify-0.2.0 → agentverify-0.4.0}/tests/test_errors.py +151 -0
  34. {agentverify-0.2.0 → agentverify-0.4.0}/tests/test_init.py +21 -0
  35. agentverify-0.4.0/tests/test_matchers.py +91 -0
  36. agentverify-0.4.0/tests/test_mocking.py +275 -0
  37. agentverify-0.4.0/tests/test_models.py +348 -0
  38. agentverify-0.4.0/tests/test_probe.py +223 -0
  39. {agentverify-0.2.0 → agentverify-0.4.0}/tests/test_properties.py +210 -2
  40. {agentverify-0.2.0 → agentverify-0.4.0}/tests/test_recorder.py +481 -0
  41. agentverify-0.4.0/tests/test_step_builder.py +162 -0
  42. agentverify-0.2.0/PKG-INFO +0 -681
  43. agentverify-0.2.0/README.md +0 -633
  44. agentverify-0.2.0/agentverify/__init__.py +0 -54
  45. agentverify-0.2.0/agentverify/assertions.py +0 -324
  46. agentverify-0.2.0/agentverify/cassette/adapters/openai.py +0 -291
  47. agentverify-0.2.0/agentverify/cassette/recorder.py +0 -314
  48. agentverify-0.2.0/agentverify/errors.py +0 -180
  49. agentverify-0.2.0/agentverify/frameworks/langchain.py +0 -92
  50. agentverify-0.2.0/agentverify/frameworks/langgraph.py +0 -100
  51. agentverify-0.2.0/agentverify/frameworks/openai_agents.py +0 -113
  52. agentverify-0.2.0/agentverify/frameworks/strands.py +0 -93
  53. agentverify-0.2.0/agentverify/matchers.py +0 -48
  54. agentverify-0.2.0/agentverify/models.py +0 -109
  55. agentverify-0.2.0/agentverify.egg-info/PKG-INFO +0 -681
  56. agentverify-0.2.0/tests/test_assertions.py +0 -356
  57. agentverify-0.2.0/tests/test_matchers.py +0 -44
  58. agentverify-0.2.0/tests/test_models.py +0 -136
  59. {agentverify-0.2.0 → agentverify-0.4.0}/LICENSE +0 -0
  60. {agentverify-0.2.0 → agentverify-0.4.0}/agentverify/cassette/__init__.py +0 -0
  61. {agentverify-0.2.0 → agentverify-0.4.0}/agentverify/cassette/adapters/__init__.py +0 -0
  62. {agentverify-0.2.0 → agentverify-0.4.0}/agentverify/py.typed +0 -0
  63. {agentverify-0.2.0 → agentverify-0.4.0}/agentverify.egg-info/dependency_links.txt +0 -0
  64. {agentverify-0.2.0 → agentverify-0.4.0}/agentverify.egg-info/entry_points.txt +0 -0
  65. {agentverify-0.2.0 → agentverify-0.4.0}/agentverify.egg-info/top_level.txt +0 -0
  66. {agentverify-0.2.0 → agentverify-0.4.0}/setup.cfg +0 -0
  67. {agentverify-0.2.0 → agentverify-0.4.0}/tests/test_base_adapter.py +0 -0
  68. {agentverify-0.2.0 → agentverify-0.4.0}/tests/test_cassette_io.py +0 -0
  69. {agentverify-0.2.0 → agentverify-0.4.0}/tests/test_fixtures.py +0 -0
  70. {agentverify-0.2.0 → agentverify-0.4.0}/tests/test_markers.py +0 -0
  71. {agentverify-0.2.0 → agentverify-0.4.0}/tests/test_plugin.py +0 -0
  72. {agentverify-0.2.0 → agentverify-0.4.0}/tests/test_sanitize.py +0 -0
@@ -0,0 +1,832 @@
1
+ Metadata-Version: 2.4
2
+ Name: agentverify
3
+ Version: 0.4.0
4
+ Summary: Deterministic testing for AI agents. Assert agent actions, not vibes.
5
+ Author: simukappu
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/simukappu/agentverify
8
+ Project-URL: Repository, https://github.com/simukappu/agentverify
9
+ Project-URL: Issues, https://github.com/simukappu/agentverify/issues
10
+ Project-URL: Changelog, https://github.com/simukappu/agentverify/blob/main/CHANGELOG.md
11
+ Keywords: pytest,testing,ai,agent,llm,tool-calls,cassette,deterministic,ci
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Framework :: Pytest
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Topic :: Software Development :: Testing
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: PyYAML
27
+ Requires-Dist: pytest>=7
28
+ Provides-Extra: openai
29
+ Requires-Dist: openai; extra == "openai"
30
+ Provides-Extra: anthropic
31
+ Requires-Dist: anthropic; extra == "anthropic"
32
+ Provides-Extra: gemini
33
+ Requires-Dist: google-genai; extra == "gemini"
34
+ Provides-Extra: bedrock
35
+ Requires-Dist: boto3; extra == "bedrock"
36
+ Provides-Extra: litellm
37
+ Requires-Dist: litellm; extra == "litellm"
38
+ Provides-Extra: all
39
+ Requires-Dist: openai; extra == "all"
40
+ Requires-Dist: anthropic; extra == "all"
41
+ Requires-Dist: google-genai; extra == "all"
42
+ Requires-Dist: boto3; extra == "all"
43
+ Requires-Dist: litellm; extra == "all"
44
+ Provides-Extra: dev
45
+ Requires-Dist: hypothesis; extra == "dev"
46
+ Requires-Dist: pytest-cov; extra == "dev"
47
+ Dynamic: license-file
48
+
49
+ # agentverify
50
+
51
+ [![PyPI](https://img.shields.io/pypi/v/agentverify)](https://pypi.org/project/agentverify/)
52
+ [![Downloads](https://img.shields.io/pepy/dt/agentverify)](https://pepy.tech/projects/agentverify)
53
+ [![CI](https://github.com/simukappu/agentverify/actions/workflows/ci.yml/badge.svg)](https://github.com/simukappu/agentverify/actions/workflows/ci.yml)
54
+ [![Coverage](https://coveralls.io/repos/github/simukappu/agentverify/badge.svg?branch=main)](https://coveralls.io/github/simukappu/agentverify?branch=main)
55
+ [![License](http://img.shields.io/badge/license-MIT-blue.svg?style=flat)](LICENSE)
56
+
57
+ **pytest for AI agents.** Assert agent actions, not vibes.
58
+
59
+ agentverify is a pytest plugin for deterministic testing of AI agent actions. Record real LLM calls once and replay them in CI with zero cost, or run against a live LLM with flexible matchers that tolerate prompt variation. Either way, assert exactly what your agent did: which tools it called, what data flowed between steps, how much it cost, and whether it stayed within your safety rules.
60
+
61
+ ![agentverify failure output showing the exact mismatch between expected and actual tool calls](docs/screenshot-error-output.png)
62
+
63
+ Specifically:
64
+
65
+ - **Tool call sequences**: exact order, subsequence, or set membership, with regex / wildcard argument matching
66
+ - **Step-level execution**: each LLM call is a step; assert what tool was called at step N, what the step's output was, and that step N's input references data produced by step M
67
+ - **Tool outcomes**: whether each tool call actually returned a usable result (vs. errored, timed out, or came back empty), what the result contained, and how many times a flaky tool was retried
68
+ - **Budgets**: token counts, cost in USD, end-to-end latency
69
+ - **Safety**: a list of tools that must never be called, no matter what the LLM decides
70
+
71
+ Built-in adapters cover LangChain, LangGraph, Strands Agents, and OpenAI Agents SDK. A small [custom converter](#custom-converters) plugs in anything else, including pure-Python ReAct loops, the Anthropic / OpenAI SDK directly, and frameworks not listed above. LLM providers supported: OpenAI, Amazon Bedrock, Google Gemini, Anthropic, and LiteLLM. Cassettes are human-readable YAML. Commit them to git, review in PRs, run in CI without an API key.
72
+
73
+ ## Why I built this
74
+
75
+ When I started building agents that call tools in a loop, I ran into a failure mode that is easy to introduce and easy to miss: the agent calls the wrong tool, ignores a tool result, or quietly retries a failing call until the budget runs over. I wanted those caught in CI the way any other regression is. But the usual options did not fit. Mocking everything proves nothing, and running against a real LLM is unreliable, costs money, and needs an API key in CI.
76
+
77
+ What I wanted was boring. Run the agent once, record what it did, and assert on it in CI like any other function: the tool sequence, the arguments, the cost, the steps where one tool's output feeds the next. Review the recording in the PR next to the prompt change that produced it. No judge model, no scoring, no cloud account. agentverify is deliberately narrow, and the cassette-replay path is what keeps those tests in CI without a key or a bill.
78
+
79
+ This is probably for you if:
80
+
81
+ - You've shipped an agent that calls tools in a loop and need CI-safe regression tests for it
82
+ - You've hit bugs like "it ignored the tool result" or "it called the wrong tool"
83
+ - You want prompt and tool changes reviewed in PRs via a concrete diff, not an informal "looks fine locally" signoff
84
+ - You're building on MCP servers and need to pin down which tools get called with which arguments
85
+ - You want token, cost, and latency budgets enforced in CI, not caught only on the billing dashboard
86
+
87
+ This is the **regression-test layer** for agents: deterministic assertions on what the agent did. It's distinct from quality evaluation (LLM-as-judge scoring on open-ended output) and production trace observability, both of which are often used alongside agentverify rather than instead of it. See [How agentverify compares](#how-agentverify-compares) for when to reach for each.
88
+
89
+ ## Install
90
+
91
+ ```bash
92
+ pip install agentverify
93
+ ```
94
+
95
+ ## Quick Start
96
+
97
+ After [installing](#install), copy this into `test_agent.py` and run `pytest`. No LLM calls, no API keys, no cassettes needed. Just pure assertions on an `ExecutionResult`.
98
+
99
+ ```python
100
+ from agentverify import (
101
+ ExecutionResult, ToolCall, ANY,
102
+ assert_tool_calls, assert_cost, assert_no_tool_call, assert_final_output,
103
+ )
104
+
105
+ # Build an ExecutionResult from your agent's output (or a dict)
106
+ result = ExecutionResult.from_dict({
107
+ "tool_calls": [
108
+ {"name": "get_location", "arguments": {"city": "Tokyo"}},
109
+ {"name": "get_weather", "arguments": {"lat": 35.6, "lon": 139.7}},
110
+ ],
111
+ "token_usage": {"input_tokens": 50, "output_tokens": 30},
112
+ "total_cost_usd": 0.002,
113
+ "final_output": "The weather in Tokyo is sunny, 22°C.",
114
+ })
115
+
116
+ def test_tool_sequence():
117
+ assert_tool_calls(result, expected=[
118
+ ToolCall("get_location", {"city": "Tokyo"}),
119
+ ToolCall("get_weather", {"lat": ANY, "lon": ANY}),
120
+ ])
121
+
122
+ def test_budget():
123
+ assert_cost(result, max_tokens=500, max_cost_usd=0.01)
124
+
125
+ def test_safety():
126
+ assert_no_tool_call(result, forbidden_tools=["delete_user", "drop_table"])
127
+
128
+ def test_output():
129
+ assert_final_output(result, contains="Tokyo")
130
+ ```
131
+
132
+ ```
133
+ $ pytest test_agent.py -v
134
+ test_agent.py::test_tool_sequence PASSED
135
+ test_agent.py::test_budget PASSED
136
+ test_agent.py::test_safety PASSED
137
+ test_agent.py::test_output PASSED
138
+ ```
139
+
140
+ > **Using a real agent framework?** Walk through the [Real-World Examples](#real-world-examples) below for in-depth walkthroughs with cassettes, or jump to the [Examples](#examples) table for a quick index of all runnable samples.
141
+
142
+ ## Real-World Examples
143
+
144
+ End-to-end examples that showcase different agent patterns and testing angles. All run with pre-recorded cassettes, no API keys needed.
145
+
146
+ ### Strands Weather Forecaster — Two-Step ReAct
147
+
148
+ Test the [Strands Weather Forecaster](https://strandsagents.com/docs/examples/python/weather_forecaster/), an official Strands Agents sample. The agent uses the `http_request` tool to call the National Weather Service API, which returns the forecast URL for the requested location; the agent then calls that URL to get the actual forecast. Two steps, one piece of data flowing between them: the simplest shape of a ReAct loop.
149
+
150
+ ```python
151
+ import pytest
152
+ from agentverify import (
153
+ assert_tool_calls, assert_cost, assert_latency,
154
+ assert_no_tool_call, assert_final_output, assert_all,
155
+ ToolCall, MATCHES,
156
+ )
157
+
158
+ # Import the weather agent from the Strands sample
159
+ # (see https://strandsagents.com/docs/examples/python/weather_forecaster/)
160
+ from weather_agent import weather_agent
161
+
162
+
163
+ @pytest.mark.agentverify
164
+ def test_weather_agent(cassette):
165
+ """Verify tool sequence, budget, latency, safety, and final output in one go."""
166
+ with cassette("weather_seattle.yaml", provider="bedrock") as rec:
167
+ weather_agent("What's the weather in Seattle?")
168
+
169
+ result = rec.to_execution_result()
170
+ assert_all(
171
+ result,
172
+ # Two http_request calls with distinct URL shapes: location lookup then forecast
173
+ lambda r: assert_tool_calls(r, expected=[
174
+ ToolCall("http_request", {"method": "GET", "url": MATCHES(r"/points/")}),
175
+ ToolCall("http_request", {"method": "GET", "url": MATCHES(r"/forecast")}),
176
+ ]),
177
+ lambda r: assert_cost(r, max_tokens=15000),
178
+ lambda r: assert_latency(r, max_ms=10_000),
179
+ lambda r: assert_no_tool_call(r, forbidden_tools=["write_file", "execute_command"]),
180
+ lambda r: assert_final_output(r, contains="Seattle"),
181
+ )
182
+ ```
183
+
184
+ Want to go deeper? Step-level assertions verify the ReAct structure and the data flow between the two steps:
185
+
186
+ ```python
187
+ from agentverify import assert_step, assert_step_uses_result_from
188
+
189
+ @pytest.mark.agentverify
190
+ def test_weather_agent_steps(cassette):
191
+ with cassette("weather_seattle.yaml", provider="bedrock") as rec:
192
+ weather_agent("What's the weather in Seattle?")
193
+ result = rec.to_execution_result()
194
+
195
+ # First step must call /points/ to discover the forecast office
196
+ assert_step(result, step=0, expected_tool=ToolCall(
197
+ "http_request", {"method": "GET", "url": MATCHES(r"/points/")},
198
+ ), partial_args=True)
199
+
200
+ # Second step must call /forecast/ AND use data from the first step's result
201
+ assert_step(result, step=1, expected_tool=ToolCall(
202
+ "http_request", {"method": "GET", "url": MATCHES(r"/forecast")},
203
+ ), partial_args=True)
204
+ assert_step_uses_result_from(result, step=1, depends_on=0)
205
+ ```
206
+
207
+ `MATCHES(pattern)` is a regex matcher. See [Assertion Modes](#assertion-modes) for details on `ANY`, `MATCHES`, `OrderMode`, and `partial_args`. Step assertions are covered in [Step-Level Assertions](#step-level-assertions).
208
+
209
+ ### OpenAI Agents SDK LLM as a Judge — Freezing a Probabilistic Refinement Loop
210
+
211
+ Test the [OpenAI Agents SDK `agent_patterns/llm_as_a_judge.py`](https://github.com/openai/openai-agents-python/blob/main/examples/agent_patterns/llm_as_a_judge.py) sample: a generator writes a story outline, an evaluator grades it with a structured `{feedback, score}` verdict, and the loop re-runs the generator with that feedback until the evaluator accepts the draft. Everything about this agent is probabilistic: how many rounds it takes, what the feedback says, whether the rewrite incorporates it. Recording one run freezes all of it into a deterministic test.
212
+
213
+ The headline assertion is the feedback chain: round 2's generator must actually consume round 1's evaluator feedback, not silently regenerate the same outline.
214
+
215
+ ```python
216
+ import pytest
217
+ from agentverify import assert_step_uses_result_from, assert_step_output
218
+
219
+ # Import the judge loop from the example
220
+ # (see examples/openai-agents-llm-as-a-judge/)
221
+ from agent import run_judge_loop_sync
222
+
223
+
224
+ @pytest.mark.agentverify
225
+ def test_generator_consumes_evaluator_feedback(cassette):
226
+ """Round 2's regeneration must reference the evaluator's round 1 feedback."""
227
+ with cassette("detective_in_space.yaml", provider="openai") as rec:
228
+ run_judge_loop_sync("A detective story in space.", max_rounds=3)
229
+ result = rec.to_execution_result()
230
+
231
+ # Step 1 is the evaluator's first verdict; it must reject on the first try.
232
+ assert_step_output(
233
+ result, step=1, matches=r'"score"\s*:\s*"(needs_improvement|fail)"'
234
+ )
235
+ # Step 2 (generator, round 2) must actually consume step 1's feedback.
236
+ # This catches "agent regenerated but ignored the judge" bugs.
237
+ assert_step_uses_result_from(result, step=2, depends_on=1)
238
+ ```
239
+
240
+ `assert_step_uses_result_from` matches across JSON-serialization boundaries. The multi-line evaluator feedback is found inside the next step's user message even when newlines are escaped during serialization.
241
+
242
+ Because each `Runner.run` call is recorded individually and the workflow spans several runs, the test builds the `ExecutionResult` straight off the cassette recorder rather than the single-run `from_openai_agents` adapter. The cassette layer is the natural single source of truth when a test covers multiple agent runs.
243
+
244
+ See [`examples/openai-agents-llm-as-a-judge/`](examples/openai-agents-llm-as-a-judge/) for the full loop, the cassette, and the remaining flat + step-level assertions (budget, safety, pass-verdict reached).
245
+
246
+ ### LangGraph + LangChain — Multi-Agent Handoff and MCP Tool Loops
247
+
248
+ Full-depth examples for the LangChain ecosystem live under [`examples/`](examples/):
249
+
250
+ - **[LangGraph multi-agent supervisor](examples/langgraph-multi-agent-supervisor/)**: a supervisor routes to a research expert and a math expert; each `add` in the math chain must consume the previous `add`'s result. `assert_step_uses_result_from` matches the numeric running total (`"231317.0"` produced as a string, consumed as `231317` int/float) across type boundaries, with digit-boundary checks that keep `"231"` from falsely appearing inside `1231`.
251
+ - **[LangChain GitHub issue triage](examples/langchain-issue-triage/)**: a `create_react_agent` drives the GitHub MCP server to list issues, read one, propose labels. The step-level tests verify that the `issue_number` passed to `get_issue` actually came from the preceding `list_issues` response, that the GitHub reads returned usable results (`assert_no_tool_errors`, `assert_tool_result_matches`), and that destructive tools like `close_issue` are never called.
252
+
253
+ Each example ships with its own pre-recorded cassette, a detailed `README.md`, and a full test file. Pick whichever framework fits your stack.
254
+
255
+ ## Build an ExecutionResult
256
+
257
+ Every agentverify assertion takes an `ExecutionResult`. You can build one three ways:
258
+
259
+ 1. **From a dict**: convenient for quick tests and fixtures, as in the [Quick Start](#quick-start).
260
+ 2. **From a built-in adapter**: one-liner for LangChain, LangGraph, Strands Agents, OpenAI Agents SDK. See [Framework Integration](#framework-integration).
261
+ 3. **From a custom converter**: for frameworks or pure-Python agents not covered by a built-in adapter, map your output to the schema below. See [`examples/custom-converter-python-agent/`](examples/custom-converter-python-agent/) for a complete walkthrough with an Anthropic SDK agent, including a pre-recorded cassette and step-level tests.
262
+
263
+ `ExecutionResult.from_dict()` accepts these keys:
264
+
265
+ | Key | Type | Description |
266
+ |---|---|---|
267
+ | `steps` | `list[dict]` | Each step dict has `index` (int), `source` (`"llm"` / `"probe"` / `"tool"`), `tool_calls` (list), `tool_results` (list), `output` (str or None), `input_context` (dict or None), `name` (str or None). See [Step-Level Assertions](#step-level-assertions) |
268
+ | `tool_calls` | `list[dict]` | **Shortcut for single-step cases**: when `steps` is absent, a flat `tool_calls` list is wrapped into a single synthetic step. Used throughout the [Quick Start](#quick-start). Each dict has `name` (str, required), `arguments` (dict, optional), `result` (any, optional) |
269
+ | `token_usage` | `dict` or `None` | `{"input_tokens": int, "output_tokens": int}` |
270
+ | `total_cost_usd` | `float` or `None` | Total cost in USD (must be set manually, not auto-calculated from tokens or populated from cassettes) |
271
+ | `duration_ms` | `float` or `None` | Wall-clock duration in milliseconds (auto-populated by the `cassette` fixture and `MockLLM`) |
272
+ | `final_output` | `str` or `None` | The agent's final text response |
273
+
274
+ `ExecutionResult.from_json(json_string)` and `to_dict()` / `to_json()` are also available for serialization.
275
+
276
+ ## Record & Replay with Cassettes
277
+
278
+ Record real LLM API calls once, then replay them in CI forever. Zero cost, fully deterministic.
279
+
280
+ ```python
281
+ import pytest
282
+ from agentverify import assert_tool_calls, ToolCall, ANY
283
+
284
+ @pytest.mark.agentverify
285
+ def test_weather_agent(cassette):
286
+ with cassette("weather_agent.yaml", provider="openai") as rec:
287
+ # Replace this with your actual agent invocation, e.g.:
288
+ # agent.run("What's the weather in Tokyo?")
289
+ run_my_agent("What's the weather in Tokyo?")
290
+
291
+ # rec.to_execution_result() is called AFTER the with block exits
292
+ result = rec.to_execution_result()
293
+ assert_tool_calls(result, expected=[
294
+ ToolCall("get_location", {"city": "Tokyo"}),
295
+ ToolCall("get_weather", {"lat": ANY, "lon": ANY}),
296
+ ])
297
+ ```
298
+
299
+ The `cassette` fixture is provided by the agentverify pytest plugin. It creates an `LLMCassetteRecorder` that intercepts LLM SDK calls (not HTTP; it patches the SDK's chat completion method directly). Use `@pytest.mark.agentverify` to mark your test, and call your agent code inside the `with cassette(...)` block. After the block exits, call `rec.to_execution_result()` to build the result for assertions.
300
+
301
+ Record the cassette once, then replay it forever:
302
+
303
+ ```bash
304
+ # First run: record real LLM calls to cassette file
305
+ pytest --cassette-mode=record
306
+
307
+ # All subsequent runs: replay from cassette (zero cost, deterministic)
308
+ pytest
309
+ ```
310
+
311
+ Cassettes are human-readable YAML (or JSON). Commit them to git, review in PRs.
312
+
313
+ agentverify supports three cassette modes:
314
+
315
+ | Mode | Behavior |
316
+ |---|---|
317
+ | `AUTO` (default) | If cassette file exists → REPLAY. Otherwise → call real LLM API but don't save (no cassette file is created). |
318
+ | `RECORD` | Always call real LLM API and save to cassette file. |
319
+ | `REPLAY` | Always replay from cassette file. Raises error if file is missing. |
320
+
321
+ ### Stale Cassette Detection
322
+
323
+ Cassette replay verifies request content by default so a stale cassette fails loudly instead of returning the old response. Each replay request is compared against the recorded request:
324
+ - **Model name**: must match exactly (empty model in either side skips the check)
325
+ - **Tool names**: the sorted list of tool names must match (empty tools in either side skips the check)
326
+
327
+ A `CassetteRequestMismatchError` is raised on mismatch with a clear message indicating which field differs and suggesting re-recording.
328
+
329
+ To disable matching (e.g., during migration):
330
+
331
+ ```bash
332
+ # CLI: disable for all tests
333
+ pytest --no-cassette-match-requests
334
+ ```
335
+
336
+ ```python
337
+ # Per-test: disable in the cassette factory call
338
+ with cassette("my_test.yaml", provider="openai", match_requests=False) as rec:
339
+ run_my_agent("What's the weather?")
340
+ ```
341
+
342
+ ### Keeping Cassettes Current
343
+
344
+ Cassettes drift when your prompts, tool schemas, or model versions change. agentverify's stale detection catches model-name and tool-name mismatches automatically (see [Stale Cassette Detection](#stale-cassette-detection)); a prompt-only change won't invalidate the cassette unless the model's tool-call output differs. In practice:
345
+
346
+ - Re-record on major prompt rewrites or tool schema changes
347
+ - Pin model versions (`gpt-4o-2024-08-06`, not `gpt-4o`) in your agent code so cassettes don't silently shift underneath you
348
+ - Treat cassette diffs as part of the PR review. A YAML diff next to the prompt diff is a feature, not noise
349
+ - Use `MATCHES` and `partial_args=True` to assert on the stable parts of tool arguments, so small wording changes in LLM outputs don't cascade into test failures
350
+
351
+ ### Cassette Sanitization
352
+
353
+ Cassette files are sanitized by default when recording. API keys, tokens, and other sensitive data are automatically redacted before saving to disk.
354
+
355
+ Built-in patterns cover:
356
+ - OpenAI API keys (`sk-...`)
357
+ - Anthropic API keys (`sk-ant-...`)
358
+ - AWS access keys (`AKIA...`)
359
+ - Bearer tokens (`Bearer ...`)
360
+
361
+ Add custom patterns:
362
+
363
+ ```python
364
+ from agentverify import SanitizePattern
365
+
366
+ custom_patterns = [
367
+ SanitizePattern(name="internal_token", pattern=r"tok-[a-f0-9]{32}", replacement="tok-***REDACTED***"),
368
+ ]
369
+
370
+ with cassette("test.yaml", provider="openai", sanitize=custom_patterns) as rec:
371
+ run_my_agent("Do something")
372
+ ```
373
+
374
+ Pass `sanitize=False` to disable sanitization entirely (not recommended).
375
+
376
+ ## Assertion Modes
377
+
378
+ ```python
379
+ from agentverify import assert_tool_calls, OrderMode, ToolCall, ANY, MATCHES
380
+
381
+ # Exact match: same tools, same order, same count (default)
382
+ assert_tool_calls(result, expected=[...])
383
+
384
+ # Subsequence: these tools appeared in this order (other calls in between are OK)
385
+ assert_tool_calls(result, expected=[...], order=OrderMode.IN_ORDER)
386
+
387
+ # Set membership: these tools were called (order doesn't matter)
388
+ assert_tool_calls(result, expected=[...], order=OrderMode.ANY_ORDER)
389
+
390
+ # Partial args: only check the keys you care about
391
+ assert_tool_calls(result, expected=[
392
+ ToolCall("search", {"query": "Tokyo"}),
393
+ ], partial_args=True)
394
+
395
+ # ANY wildcard: ignore a specific argument value
396
+ assert_tool_calls(result, expected=[
397
+ ToolCall("get_weather", {"lat": ANY, "lon": ANY}),
398
+ ])
399
+
400
+ # MATCHES regex: verify a string argument follows a pattern
401
+ # (re.search semantics; use ^/$ anchors for full match)
402
+ assert_tool_calls(result, expected=[
403
+ ToolCall("send_email", {"to": MATCHES(r"^[\w.+-]+@example\.com$")}),
404
+ ToolCall("log_event", {"event_id": MATCHES(r"^evt_[a-f0-9]{16}$")}),
405
+ ])
406
+ ```
407
+
408
+ Collect all failures at once instead of stopping at the first:
409
+
410
+ ```python
411
+ from agentverify import assert_all
412
+ assert_all(
413
+ result,
414
+ lambda r: assert_tool_calls(r, expected=[...]),
415
+ lambda r: assert_cost(r, max_tokens=1000),
416
+ lambda r: assert_latency(r, max_ms=3000),
417
+ lambda r: assert_no_tool_call(r, forbidden_tools=["delete_user"]),
418
+ lambda r: assert_final_output(r, contains="Tokyo"),
419
+ )
420
+ ```
421
+
422
+ ### Cost Assertions
423
+
424
+ `assert_cost()` enforces token and dollar budgets on an agent run. Either bound is optional. Pass `max_tokens` only, `max_cost_usd` only, or both together:
425
+
426
+ ```python
427
+ from agentverify import assert_cost
428
+
429
+ # Token budget only
430
+ assert_cost(result, max_tokens=500)
431
+
432
+ # Dollar budget only
433
+ assert_cost(result, max_cost_usd=0.01)
434
+
435
+ # Both: fail if either is exceeded
436
+ assert_cost(result, max_tokens=500, max_cost_usd=0.01)
437
+ ```
438
+
439
+ `result.token_usage` is populated automatically by the `cassette` fixture, `MockLLM`, and every built-in framework adapter. `result.total_cost_usd` must be set manually (see [Build an ExecutionResult](#build-an-executionresult)). agentverify does not compute dollar costs from tokens, since the pricing table would need per-model maintenance and get stale quickly.
440
+
441
+ ### Latency Assertions
442
+
443
+ `assert_latency()` enforces a response time SLA on your agent. When you use the `cassette` fixture, wall-clock duration is captured automatically on context exit and exposed as `ExecutionResult.duration_ms`:
444
+
445
+ ```python
446
+ from agentverify import assert_latency
447
+
448
+ @pytest.mark.agentverify
449
+ def test_weather_agent_latency(cassette):
450
+ with cassette("weather_seattle.yaml", provider="bedrock") as rec:
451
+ weather_agent("What's the weather in Seattle?")
452
+
453
+ result = rec.to_execution_result()
454
+ # Fail if the whole agent run took more than 3 seconds
455
+ assert_latency(result, max_ms=3000)
456
+ ```
457
+
458
+ During cassette **replay**, the measured duration reflects replay time (typically milliseconds), not the original call time. Capture latency data during **record** mode, or set `duration_ms` manually via [`ExecutionResult.from_dict()`](#build-an-executionresult).
459
+
460
+ ### Final Output Assertions
461
+
462
+ `assert_final_output()` verifies the agent's final text response. Use `contains` for substring checks, `equals` for exact match, or `matches` for regex:
463
+
464
+ ```python
465
+ from agentverify import assert_final_output
466
+
467
+ # Substring check
468
+ assert_final_output(result, contains="Tokyo")
469
+
470
+ # Exact match
471
+ assert_final_output(result, equals="The weather in Tokyo is sunny, 22°C.")
472
+
473
+ # Regex match
474
+ assert_final_output(result, matches=r"\d+°C")
475
+ ```
476
+
477
+ ### Strict Mode
478
+
479
+ `assert_cost()` and `assert_latency()` silently pass when the underlying data (`token_usage`, `total_cost_usd`, `duration_ms`) is `None`. Useful during cassette replay where some data may be unavailable. Pass `strict=True` to require the data to be present:
480
+
481
+ ```python
482
+ # Fails if token_usage or total_cost_usd is None
483
+ assert_cost(result, max_tokens=500, max_cost_usd=0.01, strict=True)
484
+
485
+ # Fails if duration_ms is None
486
+ assert_latency(result, max_ms=3000, strict=True)
487
+ ```
488
+
489
+ ## Step-Level Assertions
490
+
491
+ For agents that make multiple LLM calls per execution (ReAct, Plan-and-Execute, multi-hop retrieval, workflow-style), agentverify exposes the full step structure, not just a flat list of tool calls.
492
+
493
+ `ExecutionResult.steps` is the single source of truth; `result.tool_calls` remains as a derived flat view for simpler cases.
494
+
495
+ > The [Real-World Examples](#real-world-examples) above show `assert_step` and `assert_step_uses_result_from` in action on Strands and the OpenAI Agents SDK; the LangGraph, LangChain, and pure-Python custom-converter examples linked from there exercise the same API on different agent shapes. This section covers the full API.
496
+
497
+ ```python
498
+ from agentverify import assert_step, assert_step_output, ToolCall, MATCHES
499
+
500
+ @pytest.mark.agentverify
501
+ def test_plan_and_execute(cassette):
502
+ with cassette("trip_planner.yaml", provider="openai") as rec:
503
+ plan_trip("2 nights in Shibuya, Tokyo")
504
+ result = rec.to_execution_result()
505
+
506
+ # Step 0: agent plans what to search for
507
+ assert_step_output(result, step=0, contains="flights")
508
+
509
+ # Step 1: agent calls the flight search tool
510
+ assert_step(result, step=1, expected_tool=ToolCall("search_flights", {"city": "Tokyo"}))
511
+
512
+ # Step 2: agent calls the hotel search with the neighborhood the user asked for
513
+ assert_step(result, step=2, expected_tool=ToolCall("search_hotels", {"area": MATCHES(r"Shibuya")}))
514
+ ```
515
+
516
+ ### Assert Step-to-Step Data Flow
517
+
518
+ `assert_step_uses_result_from()` verifies that one step's input references data produced by another. Catches "agent ignored the tool result" bugs.
519
+
520
+ ```python
521
+ from agentverify import assert_step_uses_result_from
522
+
523
+ # Verify step 2 (hotel search) actually uses the result of step 1 (flight search)
524
+ assert_step_uses_result_from(result, step=2, depends_on=1)
525
+
526
+ # Restrict to a specific channel
527
+ assert_step_uses_result_from(result, step=2, depends_on=1, via="tool_result")
528
+ ```
529
+
530
+ The check searches for any produced value (step M's `tool_results`, `tool_calls[*].result`, or `output`) inside step N's `input_context` or `tool_calls[*].arguments`. Strings are substring-matched; primitives (numbers, booleans) are matched structurally inside containers; JSON-encoded tool results are descended automatically.
531
+
532
+ To see this concretely with a different example: if step 0's `list_issues` tool returned `[{"number": 1}, {"number": 2}]` and step 1 called `get_issue(issue_number=2)`, the check finds that the number `2` produced by step 0 shows up in step 1's arguments. Data flows correctly. This is exactly the pattern the [LangChain GitHub issue triage example](examples/langchain-issue-triage/) verifies.
533
+
534
+ This works on cassette replay. Cassette recorders don't record tool execution results directly, but agentverify backfills them from the next step's `input_context` so you can assert data flow without any special adapter setup.
535
+
536
+ ### Workflow-Style Agents with `step_probe`
537
+
538
+ Many production agents aren't pure ReAct loops. They mix LLM calls with caching, state management, validation, and conditional branches. `step_probe()` lets you mark logical step boundaries in your agent code so tests can assert on those non-LLM steps.
539
+
540
+ ```python
541
+ # agent.py
542
+ from agentverify import step_probe
543
+
544
+ def run_agent(query: str) -> str:
545
+ with step_probe("fetch_cache") as p:
546
+ cached = cache.get(query)
547
+ p.set_tool_result({"hit": cached is not None})
548
+ if cached:
549
+ return cached
550
+ with step_probe("call_llm"):
551
+ response = llm.invoke(query)
552
+ with step_probe("postprocess", output="formatted"):
553
+ return format_output(response)
554
+ ```
555
+
556
+ ```python
557
+ # test_agent.py
558
+ def test_cache_miss_path():
559
+ with MockLLM([mock_response(content="42")], provider="openai") as rec:
560
+ run_agent("what's the answer?")
561
+ result = rec.to_execution_result()
562
+ assert_step(result, name="fetch_cache", expected_tools=[]) # probe with no tool calls
563
+ assert_step_output(result, name="call_llm", contains="42") # the LLM step returned the answer
564
+ assert_step_output(result, name="postprocess", equals="formatted")
565
+ ```
566
+
567
+ **`step_probe` is a zero-cost no-op outside of test recording contexts.** When no `LLMCassetteRecorder` or `MockLLM` is active, it's a pass-through context manager. Safe to leave in production code.
568
+
569
+ ## Tool Result Assertions
570
+
571
+ Knowing the agent *called* the right tool is not the same as knowing the call *worked*. A tool can return a 5xx, time out, or hand back an empty body, and the LLM will often smooth that over in its final reply. These assertions check the result a tool handed back, not just which tool was called and with what arguments.
572
+
573
+ ```python
574
+ from agentverify import (
575
+ assert_tool_invocation_succeeded,
576
+ assert_no_tool_errors,
577
+ assert_tool_result_matches,
578
+ assert_retry_count,
579
+ )
580
+
581
+ # Affirmative: the tool call(s) at this step returned a usable result
582
+ assert_tool_invocation_succeeded(result, step=1)
583
+
584
+ # Blanket safety net: no tool anywhere in the run errored
585
+ assert_no_tool_errors(result)
586
+
587
+ # The tool returned a well-shaped / non-empty result
588
+ assert_tool_result_matches(result, step=1, contains="temperature")
589
+ assert_tool_result_matches(result, step=1, matches=r'"temp":\s*\d+')
590
+
591
+ # Budget on retries of a flaky tool (counted from consecutive repeat calls)
592
+ assert_retry_count(result, tool_name="http_request", max=2)
593
+ ```
594
+
595
+ agentverify reads a per-result error signal that the built-in adapters populate from each framework's native tool-error convention (LangGraph `ToolMessage.status == "error"`, Strands `toolResult` status, OpenAI Agents `is_error`, LangChain error-shaped observations), and that cassette replay reconstructs from the recorded tool messages.
596
+
597
+ The signal is three-valued: a result is a **known error**, a **known success**, or **unknown** (for example, a plain-string tool output on cassette replay where no structured status survived). `assert_tool_invocation_succeeded` and `assert_no_tool_errors` fail only on a *known* error; unknown and absent results pass, so the same test gives the same verdict whether it runs against a live agent or a replayed cassette. To require that a result is actually present and well-formed, use `assert_tool_result_matches`, which fails when the step has no tool result at all.
598
+
599
+ `assert_no_tool_errors` is a blanket gate, so reach for it only when every tool in the run is expected to succeed. If your agent's correct behaviour includes recovering from a failure (a 429 then a retry, a primary tool then a fallback), that trajectory contains an expected error, and the blanket gate would flag it. In that case assert success on the specific steps that must succeed with `assert_tool_invocation_succeeded(step=N)` instead.
600
+
601
+ If you build an `ExecutionResult` by hand or with a custom converter, set the signal yourself via the `tool_results_meta` field on each `Step`: a list positionally aligned with `tool_results`, where entry `i` is `{"is_error": True}`, `{"is_error": False}`, or `{}` (unknown). With `step_probe`, pass it through `handle.set_tool_result(result, is_error=True)`.
602
+
603
+ ## Framework Integration
604
+
605
+ ### Built-in Adapters
606
+
607
+ agentverify ships with built-in adapters for popular agent frameworks. No converter function needed. Just import and call:
608
+
609
+ | Framework | Adapter | Input |
610
+ |---|---|---|
611
+ | [LangChain](https://github.com/langchain-ai/langchain) | `from agentverify.frameworks.langchain import from_langchain` | `AgentExecutor.invoke()` dict |
612
+ | [LangGraph](https://github.com/langchain-ai/langgraph) | `from agentverify.frameworks.langgraph import from_langgraph` | `create_react_agent` result dict |
613
+ | [Strands Agents](https://github.com/strands-agents/sdk-python) | `from agentverify.frameworks.strands import from_strands` | `AgentResult` |
614
+ | [OpenAI Agents SDK](https://github.com/openai/openai-agents-python) | `from agentverify.frameworks.openai_agents import from_openai_agents` | `RunResult` |
615
+
616
+ For LangChain, pass the conversation history `messages` list as a second argument to capture token usage:
617
+
618
+ ```python
619
+ from agentverify.frameworks.langchain import from_langchain
620
+
621
+ execution_result = from_langchain(result, messages=memory.chat_memory.messages)
622
+ ```
623
+
624
+ LangGraph, Strands, and OpenAI Agents adapters take the raw agent output directly:
625
+
626
+ ```python
627
+ from agentverify.frameworks.langgraph import from_langgraph
628
+ from agentverify.frameworks.strands import from_strands
629
+ from agentverify.frameworks.openai_agents import from_openai_agents
630
+
631
+ # LangGraph: create_react_agent / create_supervisor result
632
+ execution_result = from_langgraph(app.invoke({"messages": [...]}))
633
+
634
+ # Strands: agent call result
635
+ execution_result = from_strands(weather_agent("What's the weather in Seattle?"))
636
+
637
+ # OpenAI Agents SDK: Runner.run_sync() / await Runner.run() result
638
+ execution_result = from_openai_agents(Runner.run_sync(agent, "your prompt"))
639
+ ```
640
+
641
+ ### Custom Converters
642
+
643
+ For other frameworks, build an `ExecutionResult` from your agent's output using a small converter function. See [`examples/custom-converter-python-agent/`](examples/custom-converter-python-agent/) for a complete reference: an Anthropic SDK ReAct agent paired with a ~80-line `converter.py`, a recorded cassette, and step-level tests.
644
+
645
+ ## Supported LLM Providers
646
+
647
+ | Provider | Extra |
648
+ |---|---|
649
+ | OpenAI | `pip install "agentverify[openai]"` |
650
+ | Amazon Bedrock | `pip install "agentverify[bedrock]"` |
651
+ | Google Gemini | `pip install "agentverify[gemini]"` |
652
+ | Anthropic | `pip install "agentverify[anthropic]"` |
653
+ | LiteLLM | `pip install "agentverify[litellm]"` |
654
+ | All providers | `pip install "agentverify[all]"` |
655
+
656
+ ## LLM Mocking with MockLLM
657
+
658
+ `MockLLM` replays a list of predefined LLM responses that you define in code. Test your agent's routing logic without a cassette or a real LLM call. Useful when you haven't recorded yet, or when you want to drive the agent through hypothetical responses (errors, edge cases) that would be awkward to elicit from a real model.
659
+
660
+ ```python
661
+ import pytest
662
+ from agentverify import (
663
+ MockLLM, mock_response, ToolCall,
664
+ assert_tool_calls, assert_no_tool_call,
665
+ )
666
+
667
+ def test_agent_routes_to_weather_tool():
668
+ with MockLLM([
669
+ mock_response(tool_calls=[("get_weather", {"city": "Tokyo"})]),
670
+ mock_response(content="Tokyo is sunny, 22°C."),
671
+ ], provider="openai") as rec:
672
+ my_agent("What's the weather in Tokyo?")
673
+
674
+ result = rec.to_execution_result()
675
+ assert_tool_calls(result, expected=[ToolCall("get_weather", {"city": "Tokyo"})])
676
+ assert_no_tool_call(result, forbidden_tools=["delete_user"])
677
+ ```
678
+
679
+ `mock_response()` accepts:
680
+
681
+ - `content`: the final text message the LLM should return.
682
+ - `tool_calls`: a list of `(name, arguments)` tuples or `{"name": ..., "arguments": ...}` dicts.
683
+ - `input_tokens` / `output_tokens`: optional token usage to report.
684
+
685
+ Provide one `mock_response(...)` per LLM call your agent is expected to make. If your agent makes more calls than you've queued, `MockLLM` raises [`CassetteMissingRequestError`](#error-messages) so under-specified tests fail loudly.
686
+
687
+ ### When to Use MockLLM vs Cassettes
688
+
689
+ | Use MockLLM when | Use cassettes when |
690
+ |---|---|
691
+ | You haven't recorded a cassette yet | You want fidelity with real LLM output |
692
+ | You want to test hypothetical scenarios (errors, edge cases) | You want to catch prompt-regression bugs |
693
+ | You're doing behavior-driven tests of routing | You're regression-testing full agent runs |
694
+ | You want zero dependency on any API key | You've already got recordings to replay |
695
+
696
+ ## CI Integration
697
+
698
+ agentverify is designed for CI pipelines. Commit your cassette files to git and replay them in CI with zero LLM cost.
699
+
700
+ ### GitHub Actions
701
+
702
+ ```yaml
703
+ name: Agent Tests
704
+ on: [push, pull_request]
705
+
706
+ jobs:
707
+ test:
708
+ runs-on: ubuntu-latest
709
+ steps:
710
+ - uses: actions/checkout@v5
711
+ - uses: actions/setup-python@v6
712
+ with:
713
+ python-version: "3.14"
714
+ # Shown separately here for clarity. In practice, list agentverify
715
+ # alongside the rest of your project's deps in requirements.txt.
716
+ - run: pip install "agentverify[all]"
717
+ - run: pip install -r requirements.txt # your project's deps
718
+ - run: pytest --tb=short -v
719
+ ```
720
+
721
+ Cassette files in `tests/cassettes/` are replayed automatically. No API keys or secrets needed in CI.
722
+
723
+ ## Error Messages
724
+
725
+ Clear, structured output when assertions fail:
726
+
727
+ ```
728
+ ToolCallSequenceError: Tool call sequence mismatch at index 1 (step 0)
729
+
730
+ Expected:
731
+ [0] get_location(city="Tokyo")
732
+ [1] get_news(topic="weather") ← first mismatch
733
+
734
+ Actual:
735
+ [0] get_location(city="Tokyo")
736
+ [1] search_web(query="Tokyo weather") ← actual
737
+ ```
738
+
739
+ ```
740
+ CostBudgetError: Token budget exceeded
741
+
742
+ Actual: 1,100 tokens
743
+ Limit: 1,000 tokens
744
+ Exceeded by: 100 tokens (10.0%)
745
+ ```
746
+
747
+ ```
748
+ LatencyBudgetError: Latency budget exceeded
749
+
750
+ Actual: 3,450.0 ms
751
+ Limit: 3,000.0 ms
752
+ Exceeded by: 450.0 ms (15.0%)
753
+ ```
754
+
755
+ Other error types follow the same pattern: `SafetyRuleViolationError`, `FinalOutputError`, `CassetteRequestMismatchError` (stale cassette detected), `CassetteMissingRequestError` (cassette or MockLLM ran out of queued responses), and the step-level `StepIndexError`, `StepNameNotFoundError`, `StepNameAmbiguousError`, `StepOutputError`, `StepDependencyError`. All inherit from `AgentVerifyError`, which itself extends `AssertionError` so pytest treats them as normal test failures.
756
+
757
+ ## Requirements
758
+
759
+ - Python 3.10+
760
+ - pytest 7+
761
+
762
+ ## Examples
763
+
764
+ The [`examples/`](examples/) directory contains end-to-end examples with real agent frameworks and MCP servers. Each example ships with pre-recorded cassettes, so tests run without any API keys.
765
+
766
+ | Example | Framework | Description |
767
+ |---|---|---|
768
+ | [`langchain-issue-triage`](examples/langchain-issue-triage/) | LangChain + OpenAI | Triages GitHub issues via GitHub MCP, step-level data flow for the discovered issue number, tool-result outcome checks |
769
+ | [`langgraph-multi-agent-supervisor`](examples/langgraph-multi-agent-supervisor/) | LangGraph + OpenAI | Research + math multi-agent handoff with running-total data flow |
770
+ | [`strands-weather-forecaster`](examples/strands-weather-forecaster/) | Strands Agents + Bedrock | Two-step ReAct that discovers a forecast URL, then calls it |
771
+ | [`openai-agents-llm-as-a-judge`](examples/openai-agents-llm-as-a-judge/) | OpenAI Agents SDK | Probabilistic generator ↔ evaluator refinement loop, frozen into a deterministic test with feedback-chain data flow |
772
+ | [`custom-converter-python-agent`](examples/custom-converter-python-agent/) | Anthropic SDK (no framework) | Reference for writing a custom converter: a hand-rolled ReAct loop calling the Anthropic Messages API directly |
773
+ | [`mcp-server`](examples/mcp-server/) | (shared utility) | Mock GitHub MCP server for token-free testing |
774
+
775
+ See each example's README for setup and recording mode details.
776
+
777
+ ## Benchmark
778
+
779
+ The [`benchmarks/execution-model-trajectory/`](benchmarks/execution-model-trajectory/) directory contains a comparison study that writes the same execution-trajectory assertion in three different assertion-execution-model styles (inline pytest via agentverify, separate-runner via [DeepEval](https://www.deepeval.com/docs/evaluation-llm-tracing) [`ToolCorrectnessMetric`](https://www.deepeval.com/docs/metrics-tool-correctness) + `@observe`, managed remote via [Amazon Bedrock AgentCore Evaluations Custom code-based evaluator](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/code-based-evaluators.html) on Lambda) over two agents (Strands single-agent ReAct and LangGraph multi-agent supervisor). Per-cell numbers (LOC, wall time, API calls, dollar cost, CI secrets, cold-start) are recorded under [`results/`](benchmarks/execution-model-trajectory/results/). See the bench's [`README.md`](benchmarks/execution-model-trajectory/README.md) for the operating manual and [`DESIGN.md`](benchmarks/execution-model-trajectory/DESIGN.md) for the methodology and explicit non-goals. The benchmark is a one-time exercise that refreshes when tooling versions change materially, not a continuous CI gate.
780
+
781
+ ## How agentverify compares
782
+
783
+ Agent evaluation covers a few different jobs, and agentverify does one of them. This table is meant to help you pick the right tool for a given job, not to rank them. In practice they are often used together.
784
+
785
+ | Tool | Best at | Execution model |
786
+ |---|---|---|
787
+ | **agentverify** | Deterministic regression tests on what the agent did: tool calls, arguments, step-to-step data flow, cost, latency, safety | Inline pytest, in-process, no LLM call on replay, no cloud account |
788
+ | [DeepEval](https://github.com/confident-ai/deepeval) (Confident AI) | A large catalog of quality metrics (relevancy, faithfulness, and 40+ others), run locally or on a cloud platform | Separate test runner / cloud |
789
+ | [LangSmith](https://www.langchain.com/langsmith) (LangChain) | Agent tracing and dataset-based evaluation for the LangChain / LangGraph stack: trajectory matching and LLM-as-judge, with a pytest / vitest integration | Hosted platform (plus open-source evaluator packages) |
790
+ | Managed cloud eval services: [Amazon Bedrock AgentCore Evaluations](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/evaluations), [Google Vertex AI Gen AI evaluation](https://cloud.google.com/vertex-ai/generative-ai/docs/models/evaluation-overview), [Azure AI Foundry evaluators](https://learn.microsoft.com/azure/ai-foundry/concepts/evaluation-evaluators/agent-evaluators) | Hosted quality scoring (LLM-as-judge) plus some deterministic trajectory and metric checks, with datasets, dashboards, and reuse across CI and production | Managed, tied to a cloud account |
791
+ | [Scenario](https://github.com/langwatch/scenario) (LangWatch) | Multi-turn simulation of a user conversing with the agent | Simulation against a live LLM |
792
+
793
+ Most of these tools focus on output quality, often via LLM-as-judge, and several now add deterministic trajectory checks too. The line agentverify draws is narrower and lower in the stack: it asserts the **trajectory** (what tools ran, with what arguments, in what order, feeding what into what) inline in pytest, with no LLM in the loop on replay and no cloud account. Quality judgements ("was this a good answer?") need a judge model and fit better on a separate stage of the pipeline, usually against a live agent in staging rather than on every PR. The two are complementary: one gates the agent's actions cheaply on every commit, the other scores answer quality less often, where the judge cost is justified.
794
+
795
+ A rough guide:
796
+
797
+ - Want a broad catalog of quality metrics you can run locally? DeepEval has the widest catalog.
798
+ - Building entirely on the LangChain / LangGraph stack and want tracing plus evaluation in one place? LangSmith fits naturally.
799
+ - Already invested in a cloud agent platform (AWS, Google, or Azure) and want hosted quality scoring with datasets and dashboards? The managed eval services fit, and several now include deterministic trajectory checks too.
800
+ - Need to stress-test multi-turn conversations with a simulated user? Scenario is built for that.
801
+ - Want trajectory assertions inline in pytest, on every PR, with no API key, no secrets, and no cloud account to stand up? That is what agentverify is for.
802
+
803
+ ## Roadmap
804
+
805
+ We want agentverify to become the way people regression-test agents in CI: tests that live next to the agent code, in git, reviewed in PRs alongside the prompt and tool changes that affect them.
806
+
807
+ - Async support: first-class `asyncio` testing for async agents and tools
808
+ - Responses API cassette adapter: record/replay for OpenAI Agents SDK (Responses API) with end-to-end example
809
+ - Framework adapters for Google ADK and CrewAI: pending async support and stable tool-call APIs from these frameworks
810
+ - Cost estimation from tokens: auto-calculate `total_cost_usd` from token usage and model pricing
811
+
812
+ ## Changelog
813
+
814
+ See [CHANGELOG.md](CHANGELOG.md) for release history.
815
+
816
+ ## License
817
+
818
+ [MIT](LICENSE)
819
+
820
+ ## Contributing
821
+
822
+ Contributions welcome. Please open an issue first to discuss what you'd like to change. See [CONTRIBUTING.md](CONTRIBUTING.md) for commit, CHANGELOG, and coverage conventions.
823
+
824
+ Development setup:
825
+
826
+ ```bash
827
+ git clone https://github.com/simukappu/agentverify.git
828
+ cd agentverify
829
+ python -m venv .venv && source .venv/bin/activate
830
+ pip install -e ".[dev]"
831
+ pytest
832
+ ```