diff --git a/CHANGELOG.md b/CHANGELOG.md index 979e794..b652107 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 @@ -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 @@ -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. diff --git a/README.md b/README.md index 763b615..66d109c 100644 --- a/README.md +++ b/README.md @@ -8,20 +8,22 @@ **pytest for AI agents.** Assert agent actions, not vibes. -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. +agentverify is a pytest plugin for deterministic testing of AI agent actions. Record real LLM calls and the agent's tool 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. -![agentverify failure output showing the exact mismatch between expected and actual tool calls](docs/screenshot-error-output.png) +![agentverify failure output: a supervisor that skipped the research agent, and a math step that ignored the previous step's result](docs/screenshots/multi-agent.png) Specifically: -- **Tool call sequences**: exact order, subsequence, or set membership, with regex / wildcard argument matching +- **Tool call sequences**: exact order, subsequence, or set membership, with regex / wildcard argument matching, and an allow list with argument conditions - **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 - **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 - **Multi-agent routing**: which agent handed off to which, and which agent acted at each step - **Budgets**: token counts, cost in USD, end-to-end latency -- **Safety**: a list of tools that must never be called, no matter what the LLM decides +- **What the model was sent**: no credential URLs, and your own checks on every text in the requests +- **Cassettes that stay honest**: replay fails when the prompt or a tool schema changed, or when a cassette is past its age limit +- **Production traces**: the same assertions on OpenTelemetry traces -Built-in adapters cover LangChain, LangGraph, Strands Agents, OpenAI Agents SDK, Pydantic AI, Google ADK, and CrewAI, and agents may be sync or async, streamed or not. 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 (Chat Completions and Responses), 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. +Adapters cover LangChain, LangGraph, Strands Agents, OpenAI Agents SDK, Pydantic AI, Google ADK, and CrewAI; a small [custom converter](#custom-converters) plugs in anything else. LLM providers: OpenAI (Chat Completions and Responses), Amazon Bedrock, Google Gemini, Anthropic, and LiteLLM, sync or async, streamed or not. Cassettes are human-readable YAML: commit them to git, review them in PRs, run them in CI without an API key. ## Why I built this @@ -95,11 +97,9 @@ test_agent.py::test_safety PASSED test_agent.py::test_output PASSED ``` -> **Using a real agent framework?** See the [Real-World Examples](#real-world-examples) below, or the [Examples](#examples) table for every runnable sample. +> **Using a real agent framework?** See the [Real-World Example](#real-world-example) below, or the [Examples](#examples) table for every runnable sample. -## Real-World Examples - -End-to-end examples that showcase different agent patterns and testing angles. All run with pre-recorded cassettes, no API keys needed. +## Real-World Example ### Strands Weather Forecaster — Two-Step ReAct @@ -168,80 +168,7 @@ def test_weather_agent_steps(cassette): assert_step_uses_result_from(result, step=1, depends_on=0) ``` -`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). - -### OpenAI Agents SDK LLM as a Judge — Freezing a Probabilistic Refinement Loop - -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. - -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. - -```python -import pytest -from agentverify import assert_step_uses_result_from, assert_step_output - -# Import the judge loop from the example -# (see examples/openai-agents-llm-as-a-judge/) -from agent import run_judge_loop_sync - - -@pytest.mark.agentverify -def test_generator_consumes_evaluator_feedback(cassette): - """Round 2's regeneration must reference the evaluator's round 1 feedback.""" - with cassette("detective_in_space.yaml", provider="openai") as rec: - run_judge_loop_sync("A detective story in space.", max_rounds=3) - result = rec.to_execution_result() - - # Step 1 is the evaluator's first verdict; it must reject on the first try. - assert_step_output( - result, step=1, matches=r'"score"\s*:\s*"(needs_improvement|fail)"' - ) - # Step 2 (generator, round 2) must actually consume step 1's feedback. - # This catches "agent regenerated but ignored the judge" bugs. - assert_step_uses_result_from(result, step=2, depends_on=1) -``` - -`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. - -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. - -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). - -### OpenAI Agents SDK on LiteLLM — An Async Agent - -Test the [OpenAI Agents SDK `model_providers/litellm_provider.py`](https://github.com/openai/openai-agents-python/blob/main/examples/model_providers/litellm_provider.py) sample. `Runner.run` is async and `LitellmModel` calls `litellm.acompletion`, so the cassette is opened inside a coroutine: - -```python -import asyncio -import pytest -from agentverify import ToolCall, assert_step_uses_result_from, assert_tool_calls - -from agent import run_agent # examples/openai-agents-litellm-provider/ - - -@pytest.mark.agentverify -def test_answer_uses_the_weather_tool(cassette): - async def main(): - with cassette("weather_tokyo.yaml", provider="litellm") as rec: - await run_agent("What's the weather in Tokyo?") - return rec.to_execution_result() - - result = asyncio.run(main()) - assert_tool_calls(result, expected=[ToolCall("get_weather", {"city": "Tokyo"})]) - # The answer step must read the tool's result, not guess the weather. - assert_step_uses_result_from(result, step=1, depends_on=0, via="tool_result") -``` - -See [`examples/openai-agents-litellm-provider/`](examples/openai-agents-litellm-provider/) for the agent, the cassette, and the remaining assertions. - -### LangGraph + LangChain — Multi-Agent Handoff and MCP Tool Loops - -Full-depth examples for the LangChain ecosystem live under [`examples/`](examples/): - -- **[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`. -- **[LangChain GitHub issue triage](examples/langchain-issue-triage/)**: a LangChain agent drives a GitHub MCP server to list issues, read them, and 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. - -Each example ships with its own pre-recorded cassette, a detailed `README.md`, and a full test file. +`MATCHES(pattern)` is a regex matcher. See [Assertion Modes](#assertion-modes) for `ANY`, `MATCHES`, `OrderMode`, and `partial_args`, and [Step-Level Assertions](#step-level-assertions) for the step API. More agents, from an LLM-as-a-judge loop to an ADK agent team, are in the [Examples](#examples). ## Build an ExecutionResult @@ -298,19 +225,18 @@ pytest --cassette-mode=record pytest ``` -Cassettes are human-readable YAML (or JSON). Commit them to git, review in PRs. - -agentverify supports three cassette modes: +Cassettes are YAML (or JSON). There are four modes: | Mode | Behavior | |---|---| | `AUTO` (default) | If cassette file exists → REPLAY. Otherwise → call real LLM API but don't save (no cassette file is created). | | `RECORD` | Always call real LLM API and save to cassette file. | | `REPLAY` | Always replay from cassette file. Raises error if file is missing. | +| `RECORD_MISSING` (`--cassette-mode=record-missing`) | If cassette file exists → REPLAY. Otherwise → RECORD. Adds new cassettes without re-recording (and paying for) the others; pytest lists the new ones at the end of the run. | ### Tool Calls -The cassette records the agent's tool calls too. Replay returns each tool's recorded result instead of running the tool, so a replayed test makes no tool requests, needs no tool credentials, and leaves no side effects (MCP servers still start, since the agent lists their tools): +The cassette records the agent's tool calls too. Replay returns each tool's recorded result instead of running the tool, so a replayed test makes no tool requests, needs no tool credentials, and leaves no side effects: ```yaml tool_executions: @@ -320,101 +246,49 @@ tool_executions: result: {status: success, content: [{text: ...}]} ``` -- Tools are recorded through LangChain / LangGraph, Strands Agents, OpenAI Agents SDK, Pydantic AI, Google ADK, CrewAI, and MCP's `ClientSession.call_tool`, including agents created before the cassette. -- For a hand-written agent, decorate the tool function with `@cassette_tool`. -- Calls match on the tool name and arguments, in any order. A call with no recorded match raises `CassetteToolMismatchError`, and fails the test when the cassette closes, even if the framework passed the error to the model. Re-record the cassette when the agent's tool calls change. -- A tool error replays as it was recorded: the error result the framework made of it, or the same exception type and message (`agentverify.cassette.tools.ReplayedToolError` when the type cannot be rebuilt from its message). -- A few calls run for real on replay too, marked `run_on_replay` in the cassette: results that do not survive YAML (a LangGraph `Command`, binary content), and CrewAI tools with `result_as_answer`. -- A replayed tool that called the LLM while recording (an agent used as a tool) skips those LLM calls on replay, so the outer agent's calls stay in step. -- Replay returns the recorded result only. What a tool does to the agent's own state is not replayed: Google ADK `tool_context.state`, Pydantic AI `deps`, an OpenAI Agents SDK context object, or anything else the tool changes in the process. LangChain tool callbacks (`on_tool_start` / `on_tool_end`) do not fire for a replayed call either. Pass `replay_tools=False` when a test depends on these. -- Tool arguments and results go through [sanitization](#cassette-sanitization) like the rest of the cassette. -- Cassettes recorded before 0.7.0 have no `tool_executions`, and their tools run for real. Pass `replay_tools=False` to run the real tools always, for example to test a tool's side effects. +Tools are recorded through every built-in framework and MCP's `ClientSession.call_tool`; for a hand-written agent, decorate the tool function with `@cassette_tool`. Calls match on the tool name and arguments; a call with no recording raises `CassetteToolMismatchError`. Replay does not restore what a tool changed in the process (Google ADK `tool_context.state`, Pydantic AI `deps`), so pass `replay_tools=False` when a test depends on that or on a tool's side effects. Which calls still run for real, and the other details, are in [docs/cassettes.md](docs/cassettes.md#tool-replay). ### Stale Cassette Detection -Replay checks that the agent still sends what was recorded, so a prompt or tool change fails the test instead of replaying old responses. Each request is compared with the recorded one: -- **Model name** (an empty model on either side skips the check) -- **Tool names**, and each tool's **parameter schema** (a request with no tools on either side skips the check) -- **System prompt**: system and developer messages, and the providers' `system` / `instructions` parameters -- **User message text**. Tool results in their own messages or blocks are not compared, since a tool running for real may return something new. +Replay checks that the agent still sends what was recorded: the model, the tool names and schemas, the system prompt, and the user's text ([details](docs/cassettes.md#request-matching)). A change raises `CassetteRequestMismatchError` with a diff, even if the agent's framework caught it, and pytest lists the stale cassettes and the command that re-records them: -A field the cassette did not record (no system prompt, or a cassette from an older version) is not compared. The request is sanitized like the cassette before comparing. +![A one-line system prompt change failing replay with a diff, and the stale cassettes summary with the command that re-records them](docs/screenshots/stale-cassette.png) -A difference raises `CassetteRequestMismatchError` with a diff, and fails the test when the cassette closes even if the agent's framework caught it. At the end of the run, pytest lists the stale cassettes and the command that re-records them: - -``` -=================== agentverify: stale cassettes =================== -tests/cassettes/weather_agent.yaml (system prompt changed) - -Re-record them with (from /path/to/project): - pytest --cassette-mode=record tests/test_agent.py::test_weather_agent -``` - -Text that changes on every run, such as today's date in a prompt, can be left out of the comparison with `match_ignore`, a list of regular expressions: +Text that changes on every run, such as today's date in a prompt, can be left out with `match_ignore`, a list of regular expressions. `match_requests=False` (or `--no-cassette-match-requests`) turns matching off. ```python with cassette("my_test.yaml", provider="openai", match_ignore=[r"\d{4}-\d{2}-\d{2}"]) as rec: run_my_agent("What's the weather?") ``` -To turn matching off (e.g., during migration), pass `match_requests=False`, or `--no-cassette-match-requests` for all tests. +Matching leaves tool results alone, since a tool that runs for real may return something new. To also notice changed tool results, message roles, or parameters, turn on [drift](docs/cassettes.md#drift): `agentverify_cassette_drift = "warn"` in the pytest settings, or `cassette(drift="fail")` for the cassettes that matter most. It raises `CassetteDriftError` or lists the places that differ, never the values. ### Keeping Cassettes Current -Cassettes drift when your prompts, tool schemas, or model versions change, and [stale detection](#stale-cassette-detection) tells you which ones. In practice: - - Re-record a cassette in the same PR as the prompt or tool change that made it stale -- Pin model versions (a dated snapshot, not a moving alias) in your agent code so cassettes don't silently shift underneath you +- Pin model versions (a dated snapshot, not a moving alias) so cassettes don't silently shift underneath you - Treat cassette diffs as part of the PR review. A YAML diff next to the prompt diff is a feature, not noise -- 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 -- Set an expiry, so that cassettes nobody re-records fail instead of drifting away from the live model unnoticed - -Replaying a cassette recorded longer ago than `max_age` raises `CassetteExpiredError` before the agent runs, and the cassette joins the stale list at the end of the run. The age comes from the cassette's `metadata.recorded_at` (a value without a time zone is UTC); a cassette without one counts as expired. Set the limit for the whole suite, per run, or per cassette (the later ones win): +- Use `MATCHES` and `partial_args=True` to assert on the stable parts of tool arguments +- Set an expiry, so that cassettes nobody re-records fail instead of drifting away from the live model unnoticed: ```toml # pyproject.toml [tool.pytest.ini_options] -agentverify_cassette_max_age = "30d" # or "12h" +agentverify_cassette_max_age = "30d" # replaying an older cassette raises CassetteExpiredError ``` ```bash -pytest --cassette-max-age=30d # overrides the setting for this run -pytest --cassette-expired=warn # warn instead of failing, when there is no time to re-record -pytest --cassette-report # list the cassettes: recorded when, with which model, expired or not; runs no tests +pytest --cassette-max-age=7d # this run only; cassette(max_age=...) sets one cassette +pytest --cassette-expired=warn # warn instead of failing, when there is no time to re-record +pytest --cassette-report # list the cassettes: recorded when, with which model, expired or not +pytest --cassette-mode=record-missing # record only the cassettes that do not exist yet ``` -```python -with cassette("weather.yaml", provider="openai", max_age="7d", on_expired="warn") as rec: - ... -``` - -The limit applies when a cassette is replayed. `--cassette-report` also lists the cassettes no test replays, from the `cassettes/` directory next to each collected test file (not a custom `cassette_dir`). Its status column uses the suite or run limit, not a `max_age=` passed to one cassette, and it needs a run without pytest-xdist workers (`-p no:xdist`). - -### Recorded and Unsupported Calls - -Cassettes record chat calls, streamed or not, sync or async: OpenAI `chat.completions.create` and `responses.create` (and their `stream()` helpers), Anthropic `messages.create` and `messages.stream()`, Gemini `models.generate_content` and `generate_content_stream`, Bedrock `Converse` and `ConverseStream`, and LiteLLM `completion` / `acompletion`. Inside a cassette or `MockLLM`, other LLM calls are handled as follows. - -These raise `CassetteUnsupportedCallError`: -- Other streaming calls (OpenAI `responses.connect()` WebSocket sessions, Anthropic `messages.stream(output_format=...)`, Bedrock `InvokeModelWithResponseStream`, ...), in record and replay mode. -- In replay mode, every other request through an OpenAI, Anthropic, or Gemini SDK client (`parse()`, embeddings, beta resources, ...), Bedrock operations that generate (`InvokeModel`, `InvokeAgent`, `RetrieveAndGenerate`, ...), and LiteLLM `text_completion` and `responses`. - -These reach the real API: -- In record mode, those other requests. `parse()`, the Bedrock operations, and the LiteLLM calls warn that the cassette will not contain them; embeddings, beta resources, and WebSocket APIs do not. Replay then fails at that call. -- With no cassette file (`AUTO` passthrough), every call. Nothing is saved. - -### Streaming - -A streamed call is stored as the same response as a non-streamed one, so a cassette recorded either way replays either way. Frameworks that stream by default (Strands' `BedrockModel`, `Runner.run_streamed` in the OpenAI Agents SDK, LangChain's `stream()`) need no change. Replay yields the text in one chunk and each tool call in one chunk, not in the recorded chunk sizes. A stream the agent stops reading early is recorded with what it read. - -### OpenAI Responses API - -`responses.create` is recorded in the same `provider="openai"` cassette as Chat Completions, including the `with_raw_response` path that langchain-openai uses. The OpenAI Agents SDK uses it by default. Tool results sent back as `function_call_output` items become the step's `tool_results`, so `assert_step_uses_result_from` works the same way. Only function tools are recorded: a response with a client-executed computer, shell, apply-patch, or custom tool call raises `CassetteUnsupportedCallError`. - -With `previous_response_id` or `conversation`, the API keeps earlier turns on the server and each request carries only the new input. The cassette then misses those turns, and agentverify warns. Pass `store=False` and send the full input instead. +The rules for ages, the report, and the calls cassettes cannot record are in [docs/cassettes.md](docs/cassettes.md). ### Async Agents -The cassette is a plain context manager, so it works around `await` calls too, either in a sync test that runs the agent with `asyncio.run()` or inside your own async test (agentverify does not depend on `pytest-asyncio` or `anyio`; use whichever you already have): +The cassette is a plain context manager, so it works around `await` calls too, in a sync test that runs the agent with `asyncio.run()` or inside your own async test. Async clients of every provider are recorded, and calls that overlap (`asyncio.gather`, threads) replay with their own responses: ```python def test_async_agent(cassette): @@ -427,23 +301,13 @@ def test_async_agent(cassette): assert_final_output(result, contains="detective") ``` -Async clients of OpenAI, Anthropic, Gemini, LiteLLM, and Bedrock (`aiobotocore` / `aioboto3`) are recorded and replayed. - -Calls may overlap (`asyncio.gather`, threads). Replay matches each request to its recording on the model, tool names, system prompt, user text, and history length, so calls that finish in another order than when recorded still get their own responses; requests identical in all of these replay in recorded order. Concurrent agents keep their own `step_probe` steps and tool results. - ### Cassette Sanitization Cassettes are sanitized by default when recording. Before saving, agentverify redacts: - values that match a built-in key pattern, anywhere in the cassette - call arguments and headers under a credential key, whatever their format: `api_key`, `authorization`, `x-api-key`, `cookie`, and names ending in `token`, `secret`, `password`, and similar (for example in `extra_headers`) -Built-in patterns (`DEFAULT_PATTERNS`) cover: -- OpenAI and Anthropic API keys (`sk-...`, `sk-ant-...`) -- AWS access keys (`AKIA...`, `ASIA...`) -- Amazon Bedrock API keys (`ABSK...`, `bedrock-api-key-...`) -- Google API keys (`AIza...`) -- GitHub tokens (`ghp_...`, `github_pat_...`) -- Bearer tokens (`Bearer ...`) +Built-in patterns (`DEFAULT_PATTERNS`) cover OpenAI and Anthropic API keys (`sk-...`, `sk-ant-...`), AWS access keys (`AKIA...`, `ASIA...`), Amazon Bedrock API keys (`ABSK...`, `bedrock-api-key-...`), Google API keys (`AIza...`), GitHub tokens (`ghp_...`, `github_pat_...`), and Bearer tokens. A custom list replaces the built-in patterns, so extend `DEFAULT_PATTERNS` to keep them. Credential keys in call arguments are redacted either way: @@ -525,81 +389,25 @@ assert_tool_calls_allowed(result, allowed={ }) ``` -The conditions are a small part of JSON Schema, as tool parameter schemas use it: `type`, `enum`, `const`, `minimum`, `maximum`, `minLength`, `maxLength`, `pattern`, `required`, `properties`, and `additionalProperties`. Any other keyword raises `ValueError` rather than being ignored. Values are compared strictly: booleans are never numbers, `number` takes no NaN or infinity, `enum` and `const` compare types (`True` is not `1`), and, unlike JSON Schema, `integer` takes no float such as `3.0`. A failure (`ToolPolicyError`) lists each call outside the policy with its position, `call_id`, and reasons. - -### Cost Assertions - -`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: - -```python -from agentverify import assert_cost - -# Token budget only -assert_cost(result, max_tokens=500) - -# Dollar budget only -assert_cost(result, max_cost_usd=0.01) - -# Both: fail if either is exceeded -assert_cost(result, max_tokens=500, max_cost_usd=0.01) -``` - -`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. - -### Latency Assertions - -`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`: - -```python -from agentverify import assert_latency - -@pytest.mark.agentverify -def test_weather_agent_latency(cassette): - with cassette("weather_seattle.yaml", provider="bedrock") as rec: - weather_agent("What's the weather in Seattle?") +![An MCP agent's tool calls outside the allow list: a list_issues call with state 'all', and a get_issue call on another repository](docs/screenshots/safety.png) - result = rec.to_execution_result() - # Fail if the whole agent run took more than 3 seconds - assert_latency(result, max_ms=3000) -``` - -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). +The conditions are a small part of JSON Schema, as tool parameter schemas use it: `type`, `enum`, `const`, `minimum`, `maximum`, `minLength`, `maxLength`, `pattern`, `required`, `properties`, and `additionalProperties`. Any other keyword raises `ValueError` rather than being ignored. Values are compared strictly: booleans are never numbers, `number` takes no NaN or infinity, `enum` and `const` compare types (`True` is not `1`), and, unlike JSON Schema, `integer` takes no float such as `3.0`. A failure (`ToolPolicyError`) lists each call outside the policy with its position, `call_id`, and reasons. -### Final Output Assertions +### Budgets and Final Output -`assert_final_output()` verifies the agent's final text response. Use `contains` for substring checks, `equals` for exact match, or `matches` for regex: +`token_usage` and `duration_ms` are filled in by the `cassette` fixture, `MockLLM`, and every adapter; `total_cost_usd` is yours to set, since a pricing table would go stale. Replay measures replay time, so check latency on a recording or a live run. ```python -from agentverify import assert_final_output +from agentverify import assert_cost, assert_final_output, assert_latency -# Substring check -assert_final_output(result, contains="Tokyo") +assert_cost(result, max_tokens=500, max_cost_usd=0.01) # either bound is optional +assert_latency(result, max_ms=3000) -# Exact match -assert_final_output(result, equals="The weather in Tokyo is sunny, 22°C.") - -# Regex match -assert_final_output(result, matches=r"\d+°C") +assert_final_output(result, contains="Tokyo") # or equals=..., matches=r"\d+°C" +assert_final_output(result, contains=["Tokyo", "22°C"], case_sensitive=False) ``` -`contains` also accepts a list; every substring must appear. `case_sensitive=False` ignores case in `contains` only; for a case-insensitive regex, put `(?i)` in the pattern. `assert_step_output` and `assert_tool_result_matches` accept the same options: - -```python -assert_final_output(result, contains=["Tokyo", "22°C"]) -assert_final_output(result, contains="tokyo", case_sensitive=False) -``` - -### Strict Mode - -`assert_cost()` and `assert_latency()` silently pass when the underlying data (`token_usage`, `total_cost_usd`, `duration_ms`) is `None`, which keeps them usable on cassette replay where some data may be missing. Pass `strict=True` to require the data to be present: - -```python -# Fails if token_usage or total_cost_usd is None -assert_cost(result, max_tokens=500, max_cost_usd=0.01, strict=True) - -# Fails if duration_ms is None -assert_latency(result, max_ms=3000, strict=True) -``` +`assert_cost` and `assert_latency` pass when their data is missing; `strict=True` requires it. `assert_step_output` and `assert_tool_result_matches` take the same `contains` / `equals` / `matches` options as `assert_final_output`. ## Step-Level Assertions @@ -607,8 +415,6 @@ For agents that make multiple LLM calls per execution (ReAct, Plan-and-Execute, `ExecutionResult.steps` is the single source of truth; `result.tool_calls` remains as a derived flat view for simpler cases. -> 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. - ```python from agentverify import assert_step, assert_step_output, ToolCall, MATCHES @@ -708,7 +514,7 @@ Plain-string names compare as handoff tools spell them: `"Billing Agent"` matche ## Tool Result Assertions -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. +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: ```python from agentverify import ( @@ -734,13 +540,24 @@ assert_tool_result_matches(result, step=1, contains=["temp", "unit"], case_sensi assert_retry_count(result, tool_name="http_request", max=2) ``` -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 SDK default failure and timeout messages, Pydantic AI retry prompts and tool return outcomes, CrewAI `tool_failures`, error-shaped results such as ADK's `{"status": "error"}`), and that cassette replay reconstructs from the recorded tool messages (OpenAI tool messages, Anthropic `is_error`, Bedrock `toolResult` status). +The adapters and cassette replay read each framework's own tool-error convention, and a result is a known error, a known success, or unknown; the assertions fail only on a known error, so a test gives the same verdict live and on replay ([details](docs/tool-results.md)). `assert_no_tool_errors` is a blanket gate: if the agent is meant to recover from a failure (a 429 then a retry), assert the steps that must succeed with `assert_tool_invocation_succeeded(step=N)` instead. -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. +## Checking What the Model Was Sent -`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. +`iter_request_texts` walks every text the agent sent the model, with where it sits: the system prompt, each message with its role, tool call arguments and tool results with the tool's name, the tool definitions (including `enum` values), and the provider's other parameters, in every provider's shape. Use it for checks of your own (personal data, internal ids): -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)`. +```python +from agentverify import assert_no_credential_urls, iter_request_texts + +for where, text in iter_request_texts("tests/cassettes/weather_agent.yaml"): + # where: request[1].message[3](tool).tool_result[0](get_weather).temp, ... + assert not EMPLOYEE_ID.search(text), where + +# Fails on a presigned link a tool returned, ?access_token=, X-Amz-Signature, a JWT, ... +assert_no_credential_urls("tests/cassettes/camera_history.yaml") +``` + +`assert_no_credential_urls` names where each URL was and its host, never the value. It also takes a recorder after the run; `extra_patterns` and `ignore` adjust what counts ([details](docs/cassettes.md#checking-what-the-model-was-sent)). ## Production Traces @@ -776,30 +593,23 @@ agentverify ships with built-in adapters for popular agent frameworks. No conver | [Google ADK](https://github.com/google/adk-python) | `from agentverify.frameworks.google_adk import from_google_adk` | The events of `Runner.run()` / `run_async()`, streamed or not | | [CrewAI](https://github.com/crewAIInc/crewAI) | `from agentverify.frameworks.crewai import from_crewai` | `CrewOutput` from `crew.kickoff()` (token usage is the crew total) | -LangChain 1.x `create_agent` returns a LangGraph graph, so pass its result to `from_langgraph`. For a legacy `AgentExecutor`, pass the conversation history `messages` list as a second argument to `from_langchain` to capture token usage: +LangChain 1.x `create_agent` returns a LangGraph graph, so pass its result to `from_langgraph`. ```python from agentverify.frameworks.langchain import from_langchain - -execution_result = from_langchain(result, messages=memory.chat_memory.messages) -``` - -LangGraph and OpenAI Agents adapters take the raw agent output directly, and the Strands adapter takes the agent: - -```python from agentverify.frameworks.langgraph import from_langgraph -from agentverify.frameworks.strands import from_strands from agentverify.frameworks.openai_agents import from_openai_agents +from agentverify.frameworks.strands import from_strands -# LangGraph: create_react_agent / create_supervisor / LangChain create_agent result execution_result = from_langgraph(app.invoke({"messages": [...]})) +execution_result = from_openai_agents(Runner.run_sync(agent, "your prompt")) # Strands: the agent after the call (its messages include earlier calls; clear them between tests) weather_agent("What's the weather in Seattle?") execution_result = from_strands(weather_agent) -# OpenAI Agents SDK: Runner.run_sync() / await Runner.run() result -execution_result = from_openai_agents(Runner.run_sync(agent, "your prompt")) +# Legacy AgentExecutor: pass the history to capture token usage +execution_result = from_langchain(result, messages=memory.chat_memory.messages) ``` ### Custom Converters @@ -808,6 +618,8 @@ For other frameworks, build an `ExecutionResult` from your agent's output using ## Supported LLM Providers +Install the extra for the SDK your agent uses: + | Provider | Extra | |---|---| | OpenAI | `pip install "agentverify[openai]"` | @@ -817,13 +629,7 @@ For other frameworks, build an `ExecutionResult` from your agent's output using | LiteLLM | `pip install "agentverify[litellm]"` | | All providers | `pip install "agentverify[all]"` | -OpenAI models on Amazon Bedrock can be reached three ways; record each with the provider that owns the client: - -| Route | Cassette provider | -|---|---| -| boto3 `bedrock-runtime` `converse` | `"bedrock"` | -| OpenAI SDK with `base_url="https://bedrock-runtime..amazonaws.com/openai/v1"` (`chat.completions.create`, `responses.create`) | `"openai"` | -| boto3 `invoke_model` | not recorded; raises in replay mode | +OpenAI models on Bedrock can be reached through boto3 or the OpenAI SDK; see [docs/cassettes.md](docs/cassettes.md#recorded-and-unsupported-calls) for which provider records each route. ## LLM Mocking with MockLLM @@ -851,19 +657,12 @@ def test_agent_routes_to_weather_tool(): `mock_response()` accepts: - `content`: the final text message the LLM should return. -- `tool_calls`: a list of `(name, arguments)` tuples or `{"name": ..., "arguments": ...}` dicts. +- `tool_calls`: a list of `(name, arguments)` tuples or `{"name": ..., "arguments": ...}` dicts; add `"id"` for a fixed tool call id (otherwise each call gets a unique one). - `input_tokens` / `output_tokens`: optional token usage to report. 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. -### When to Use MockLLM vs Cassettes - -| Use MockLLM when | Use cassettes when | -|---|---| -| You haven't recorded a cassette yet | You want fidelity with real LLM output | -| You want to test hypothetical scenarios (errors, edge cases) | You want to catch prompt-regression bugs | -| You're doing behavior-driven tests of routing | You're regression-testing full agent runs | -| You want each LLM response visible in the test code | You've already got recordings to replay | +Use `MockLLM` for routing logic and hypothetical responses written in the test; use cassettes for fidelity with real LLM output and to catch prompt regressions. ## Live Runs and Pass Rates @@ -922,23 +721,7 @@ Actual: [1] search_web(query="Tokyo weather") ← actual ``` -``` -CostBudgetError: Token budget exceeded - - Actual: 1,100 tokens - Limit: 1,000 tokens - Exceeded by: 100 tokens (10.0%) -``` - -``` -LatencyBudgetError: Latency budget exceeded - - Actual: 3,450.0 ms - Limit: 3,000.0 ms - Exceeded by: 450.0 ms (15.0%) -``` - -Every assertion error follows the same pattern and inherits from `AgentVerifyError`, which extends `AssertionError` so pytest treats it as a normal test failure. The cassette errors too: `CassetteRequestMismatchError` (stale cassette), `CassetteMissingRequestError` (cassette or MockLLM ran out of responses), `CassetteToolMismatchError` (a tool call with no recorded result), `CassetteExpiredError` (a cassette past its `max_age`), and `CassetteUnsupportedCallError`. +Every assertion error follows the same pattern and inherits from `AgentVerifyError`, which extends `AssertionError` so pytest treats it as a normal test failure ([all errors](docs/reference.md#errors)). The cassette errors too: `CassetteRequestMismatchError` (stale cassette), `CassetteMissingRequestError` (cassette or MockLLM ran out of responses), `CassetteToolMismatchError` (a tool call with no recorded result), `CassetteExpiredError` (a cassette past its `max_age`), `CassetteDriftError` (a replayed request that differs, with `drift="fail"`), `CredentialURLError` (from `assert_no_credential_urls`), and `CassetteUnsupportedCallError`. ## Examples @@ -946,12 +729,12 @@ The [`examples/`](examples/) directory contains end-to-end examples with real ag | Example | Framework | Description | |---|---|---| -| [`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 | -| [`langgraph-multi-agent-supervisor`](examples/langgraph-multi-agent-supervisor/) | LangGraph + OpenAI | Research + math multi-agent handoff with running-total data flow | -| [`strands-weather-forecaster`](examples/strands-weather-forecaster/) | Strands Agents + Bedrock | Two-step ReAct that discovers a forecast URL, then calls it | -| [`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 | +| [`strands-weather-forecaster`](examples/strands-weather-forecaster/) | Strands Agents + Bedrock | Two-step ReAct that discovers a forecast URL, then calls it (the [Real-World Example](#real-world-example)) | +| [`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: round 2 must consume round 1's feedback | | [`openai-agents-litellm-provider`](examples/openai-agents-litellm-provider/) | OpenAI Agents SDK + LiteLLM + Bedrock | Async agent (`Runner.run` → `litellm.acompletion`) with a weather tool, cassette opened inside a coroutine | | [`google-adk-agent-team`](examples/google-adk-agent-team/) | Google ADK + LiteLLM + Bedrock | The ADK tutorial's agent team: a weather agent delegating greetings and farewells to sub-agents, with the delegation route and each agent's tools asserted | +| [`langgraph-multi-agent-supervisor`](examples/langgraph-multi-agent-supervisor/) | LangGraph + OpenAI | Research + math multi-agent handoff; each `add` must consume the previous running total, across string and number types | +| [`langchain-issue-triage`](examples/langchain-issue-triage/) | LangChain + OpenAI + MCP | Triages GitHub issues via a GitHub MCP server: the `issue_number` read must come from the listing, the reads must succeed, and `close_issue` is never called | | [`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 | | [`mcp-server`](examples/mcp-server/) | (shared utility) | Mock GitHub MCP server for token-free testing | @@ -976,6 +759,10 @@ We want agentverify to become the way people regression-test agents in CI: tests - MCP testing helpers: pin an MCP server's tool schemas, so a server upgrade that changes them fails a test +## Reference + +[docs/reference.md](docs/reference.md) is the API reference: every public name and pytest option, with where it is described, plus what this README only mentions (`LLMCassetteRecorder` without the fixture, `on_missing`, `@cassette_tool`, `step_probe`, the result objects, every error). [docs/cassettes.md](docs/cassettes.md) and [docs/tool-results.md](docs/tool-results.md) hold the details behind the cassette and tool result sections. + ## Changelog See [CHANGELOG.md](CHANGELOG.md) for release history. diff --git a/agentverify/__init__.py b/agentverify/__init__.py index 5408ceb..c1aa2cf 100644 --- a/agentverify/__init__.py +++ b/agentverify/__init__.py @@ -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, @@ -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 diff --git a/agentverify/assertions.py b/agentverify/assertions.py index 038171e..cb41266 100644 --- a/agentverify/assertions.py +++ b/agentverify/assertions.py @@ -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 @@ -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: @@ -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. @@ -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 @@ -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) @@ -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 @@ -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( @@ -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 @@ -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] = [] @@ -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" @@ -414,6 +425,7 @@ def assert_all( Raises: MultipleAssertionError: When one or more assertions fail. """ + __tracebackhide__ = True errors: list[AgentVerifyError] = [] for assertion in assertions: @@ -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) @@ -522,6 +535,7 @@ 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): @@ -529,6 +543,7 @@ def _assert_step_agent(step_obj: Any, agent: Any) -> None: 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): @@ -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 @@ -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( @@ -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: @@ -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"): @@ -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)): @@ -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)): @@ -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" @@ -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}" @@ -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)) @@ -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 = [ diff --git a/agentverify/cassette/adapters/base.py b/agentverify/cassette/adapters/base.py index a2febeb..b6375ff 100644 --- a/agentverify/cassette/adapters/base.py +++ b/agentverify/cassette/adapters/base.py @@ -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: @@ -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 @@ -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) @@ -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) diff --git a/agentverify/cassette/drift.py b/agentverify/cassette/drift.py new file mode 100644 index 0000000..c2a2ff2 --- /dev/null +++ b/agentverify/cassette/drift.py @@ -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 "") diff --git a/agentverify/cassette/recorder.py b/agentverify/cassette/recorder.py index 690f6fc..ca31e89 100644 --- a/agentverify/cassette/recorder.py +++ b/agentverify/cassette/recorder.py @@ -24,6 +24,8 @@ NormalizedResponse, with_call_ids, ) +from agentverify.cassette.drift import check_drift, compile_ignore, describe, drift +from agentverify.cassette.texts import _SYSTEM_KEYS from agentverify.cassette.expiry import MaxAge, check_on_expired, expiry, parse_max_age from agentverify.cassette.io import _parse_interactions, load_document, save_cassette from agentverify.cassette.sanitize import ( @@ -34,7 +36,7 @@ sanitize_tool_executions, ) from agentverify.cassette.tools import ToolExecution, ToolSession -from agentverify.errors import CassetteRequestMismatchError +from agentverify.errors import CassetteRequestMismatchError, _own_error from agentverify.models import ExecutionResult, TokenUsage, ToolCall, attribute_agents, handoff_target @@ -44,6 +46,8 @@ class CassetteMode(Enum): RECORD = "record" REPLAY = "replay" AUTO = "auto" + #: Replay the cassette if its file exists, else record it (call the real API and save). + RECORD_MISSING = "record-missing" def _request_to_context(request: NormalizedRequest | None) -> dict[str, Any] | None: @@ -144,8 +148,12 @@ def __init__( match_ignore: list[str] | None = None, max_age: MaxAge = None, on_expired: str = "error", + drift: str = "off", + drift_ignore: list[str] | None = None, ) -> None: self.cassette_path = Path(cassette_path) + self.drift = check_drift(drift) + self._drift_ignore = compile_ignore(drift_ignore) self.max_age = parse_max_age(max_age) self.on_expired = check_on_expired(on_expired) self.replay_tools = replay_tools @@ -166,8 +174,11 @@ def __init__( else: self._sanitize_patterns = sanitize - # Resolve AUTO mode based on file existence. - if mode == CassetteMode.AUTO: + # Resolve AUTO and RECORD_MISSING based on file existence. + if mode == CassetteMode.RECORD_MISSING: + self._auto_passthrough = False + self.mode = CassetteMode.REPLAY if self.cassette_path.exists() else CassetteMode.RECORD + elif mode == CassetteMode.AUTO: if self.cassette_path.exists(): self.mode = CassetteMode.REPLAY else: @@ -290,7 +301,9 @@ def __exit__(self, *args: Any) -> None: fill_in() self._pending_streams = [] - if self.mode == CassetteMode.RECORD: + # record-missing would replay a recording cut short by an error on every later run, so it keeps none. + failed_new = self._requested_mode == CassetteMode.RECORD_MISSING and args[0] is not None + if self.mode == CassetteMode.RECORD and not failed_new: interactions = self._interactions tools = None if self._tool_session is None else [e.to_dict() for e in self._tool_session.recorded] if self._sanitize_patterns is not None: @@ -302,6 +315,8 @@ def __exit__(self, *args: Any) -> None: provider=self._adapter.name, tool_executions=tools, ) + if self._requested_mode == CassetteMode.RECORD_MISSING: + _new_cassettes.append((str(self.cassette_path), self.test_id)) # A mismatch raised inside the agent may have been caught by the framework # (and a tool error turned into a message for the model); fail the test here instead. if args[0] is None and self._request_errors: @@ -357,6 +372,7 @@ def lookup(self, request: NormalizedRequest) -> NormalizedResponse | None: The next :class:`NormalizedResponse`, or ``None`` if all interactions have been consumed. """ + __tracebackhide__ = _own_error key = self._key(request) with self._lock: unused = [i for i in range(len(self._interactions)) if i not in self._used] @@ -364,7 +380,7 @@ def lookup(self, request: NormalizedRequest) -> NormalizedResponse | None: return None # no more recorded interactions index = next((i for i in unused if self._recorded_key(i) == key), unused[0]) recorded_req, response = self._interactions[index] - if self.match_requests: + if self.match_requests or self.drift != "off": self._verify_request(index, recorded_req, request) # Tool calls recorded without an id get one here, so the framework and ToolCall.call_id agree. response = with_call_ids(response, self._adapter.call_id_prefix) @@ -414,18 +430,33 @@ def _verify_request( recorded: NormalizedRequest, actual: NormalizedRequest, ) -> None: - """Compare recorded and actual requests, raising on mismatch.""" + """Compare recorded and actual requests: match (when match_requests) and drift (when drift is on).""" + __tracebackhide__ = _own_error if self._sanitize_patterns is not None: # The recording was sanitized when saved; compare like with like. actual = sanitize_interactions([(actual, NormalizedResponse())], self._sanitize_patterns)[0][0] - try: - self._compare(index, recorded, actual) - except CassetteRequestMismatchError as error: - self._request_errors.append(error) - _stale_cassettes.append((str(self.cassette_path), self.test_id, error.field)) - raise + if self.match_requests: + try: + self._compare(index, recorded, actual) + except CassetteRequestMismatchError as error: + self._request_errors.append(error) + _stale_cassettes.append((str(self.cassette_path), self.test_id, error.field)) + raise + if self.drift == "off": + return + places = drift(recorded, actual, index, self._drift_ignore, self._ignore) + if not places: + return + _stale_cassettes.append((str(self.cassette_path), self.test_id, f"drift: {describe(places)}")) + if self.drift == "fail": + from agentverify.errors import CassetteDriftError + + error = CassetteDriftError(str(self.cassette_path), index, places) + self._request_errors.append(error) # type: ignore[arg-type] + raise error def _compare(self, index: int, recorded: NormalizedRequest, actual: NormalizedRequest) -> None: + __tracebackhide__ = _own_error # Check model name if recorded.model and actual.model and recorded.model != actual.model: raise CassetteRequestMismatchError( @@ -808,6 +839,8 @@ def _tool_calls_in(message: Any) -> list[tuple[str, Any]]: # (cassette path, test id, field) for each stale cassette found in this run, for the pytest summary. _stale_cassettes: list[tuple[str, str | None, str]] = [] +# (cassette path, test id) for each cassette that record-missing recorded in this run, for the pytest summary. +_new_cassettes: list[tuple[str, str | None]] = [] # How agentverify before 0.7.0 recorded google-genai Content objects: their repr. @@ -869,7 +902,7 @@ def _system_texts(request: NormalizedRequest) -> list[str]: from agentverify.cassette.sanitize import _as_plain texts = _message_texts(request, ("system", "developer")) - for key in ("system", "system_instruction", "instructions"): + for key in _SYSTEM_KEYS: value = _as_plain(request.parameters.get(key)) texts += _texts(value.get("parts")) if isinstance(value, dict) else _texts(value) return texts diff --git a/agentverify/cassette/report.py b/agentverify/cassette/report.py index 49c06ff..f0c234b 100644 --- a/agentverify/cassette/report.py +++ b/agentverify/cassette/report.py @@ -25,25 +25,31 @@ def report(session: Any) -> None: max_age = parse_max_age(config.getoption("--cassette-max-age", default=None) or _ini(config, "agentverify_cassette_max_age")) writer = config.pluginmanager.get_plugin("terminalreporter") writer.section("agentverify: cassettes") - files = cassette_files(session) - if not files: - hint = " Under pytest-xdist the report needs a run without workers (-p no:xdist or -n 0)." if config.pluginmanager.hasplugin("dsession") else "" - writer.write_line("No cassettes next to the collected tests." + hint) - return now = datetime.now(timezone.utc) rows = [] - for path in files: + for path in cassette_files(session): try: - metadata = load_document(path).get("metadata") or {} - if not isinstance(metadata, dict): - raise TypeError("metadata is not a mapping") - except Exception as error: # a file that is not a cassette + document = load_document(path) + except Exception as error: # a broken file rows.append((path, "-", "-", "-", f"unreadable: {type(error).__name__}")) continue + if not document: + rows.append((path, "-", "-", "-", "unreadable: empty")) + continue + if not isinstance(document, dict) or "interactions" not in document: + continue # another file kept next to the cassettes, not a cassette + metadata = document.get("metadata") or {} + if not isinstance(metadata, dict): + rows.append((path, "-", "-", "-", "unreadable: metadata is not a mapping")) + continue stamp = recorded_at(metadata) recorded = f"{stamp.date().isoformat()} ({(now - stamp).days}d ago)" if stamp else "-" status = "-" if max_age is None else (expiry(metadata, max_age, now) or "ok") rows.append((path, recorded, str(metadata.get("provider", "-")), str(metadata.get("model", "-")), status)) + if not rows: + hint = " Under pytest-xdist the report needs a run without workers (-p no:xdist or -n 0)." if config.pluginmanager.hasplugin("dsession") else "" + writer.write_line("No cassettes next to the collected tests." + hint) + return root = config.rootpath shown = [(_relative(p, root), *rest) for p, *rest in rows] header = ("cassette", "recorded", "provider", "model", "status" if max_age is None else f"status (max age {_format(max_age)})") diff --git a/agentverify/cassette/texts.py b/agentverify/cassette/texts.py new file mode 100644 index 0000000..3cecd89 --- /dev/null +++ b/agentverify/cassette/texts.py @@ -0,0 +1,177 @@ +"""Every piece of text a request sends the model, with where it sits: ``iter_request_texts``. + +For checks that must see all of it (personal data, secrets, credential URLs): the system prompt, each message, tool call arguments and tool results, the tool definitions (including ``enum`` values), and the provider's other parameters. The providers' message shapes (OpenAI, the Responses API as recorded, Anthropic, Bedrock Converse, Gemini, LiteLLM) are read alike. +""" + +from __future__ import annotations + +import json +from contextvars import ContextVar +from pathlib import Path +from typing import Any, Iterable, Iterator, Union + +from agentverify.cassette.adapters.base import NormalizedRequest +from agentverify.cassette.sanitize import _as_plain + +# Not text the agent sent: provider ids, reasoning signatures, encrypted reasoning, and binary payloads. +_SKIP_KEYS = frozenset({"id", "toolUseId", "tool_use_id", "tool_call_id", "call_id", "signature", "encrypted_content", "redactedContent", "data", "bytes"}) +_SYSTEM_KEYS = ("system", "system_instruction", "instructions") + +Source = Union[str, Path, NormalizedRequest, Any] +# Drift compares nulls too (a new "description": null is a change); text checks have no use for them. +_NULLS: ContextVar[bool] = ContextVar("agentverify_texts_nulls", default=False) + + +def _requests(source: Source) -> list[NormalizedRequest]: + if isinstance(source, NormalizedRequest): + return [source] + if isinstance(source, (str, Path)): + from agentverify.cassette.io import _parse_interactions, load_document + + return [request for request, _ in _parse_interactions(load_document(Path(source)))[1]] + interactions = getattr(source, "_interactions", None) # LLMCassetteRecorder / MockLLM + if isinstance(interactions, list): + return [request for request, _ in interactions] + raise TypeError(f"iter_request_texts() takes a cassette path, an LLMCassetteRecorder or MockLLM, or a NormalizedRequest; got {type(source).__name__}") + + +def _parsed(value: Any) -> Any: + """A JSON string as the value it holds (tool arguments and results often arrive encoded).""" + if isinstance(value, str) and value[:1] in ("{", "["): + try: + return json.loads(value) + except ValueError: + return value + return value + + +def _leaves(value: Any, where: str, payload: bool = False) -> Iterator[tuple[str, str]]: + """Each text, number, and boolean inside *value*, with its path. + + In the provider's envelope, ids, signatures, and binary fields are left out. Inside a *payload* (tool arguments and results, tool schemas) every key is the agent's or the tool's own, so none is. + """ + value = _parsed(_as_plain(value)) + if isinstance(value, dict): + for key, item in value.items(): + if payload or key not in _SKIP_KEYS: + yield from _leaves(item, f"{where}.{key}", payload) + elif isinstance(value, list): + for index, item in enumerate(value): + yield from _leaves(item, f"{where}[{index}]", payload) + elif isinstance(value, str): + if value and not value.startswith("data:"): # an embedded image or file, not text + yield where, value + elif isinstance(value, (bool, int, float)): + yield where, str(value) + elif value is None and _NULLS.get(): + yield where, "null" + + +def _tool_names(request: NormalizedRequest) -> dict[str, str]: + """Tool call id to tool name, from the calls in the request's history.""" + names: dict[str, str] = {} + for message in map(_as_plain, request.messages or []): + if not isinstance(message, dict): + continue + for call in map(_as_plain, message.get("tool_calls") or []): # OpenAI / LiteLLM + if isinstance(call, dict) and isinstance(call.get("function"), dict): + names[str(call.get("id"))] = str(call["function"].get("name")) + content = message.get("content") + for block in map(_as_plain, content) if isinstance(content, list) else []: + if not isinstance(block, dict): + continue + if block.get("type") == "tool_use": # Anthropic + names[str(block.get("id"))] = str(block.get("name")) + if isinstance(block.get("toolUse"), dict): # Bedrock + names[str(block["toolUse"].get("toolUseId"))] = str(block["toolUse"].get("name")) + if message.get("type") == "function_call": # Responses API items + names[str(message.get("call_id"))] = str(message.get("name")) + return names + + +def _message(message: Any, where: str, names: dict[str, str]) -> Iterator[tuple[str, str]]: + message = _as_plain(message) + if not isinstance(message, dict): + yield from _leaves(message, where) + return + role = message.get("role") or message.get("type") or "message" + where = f"{where}({role})" + calls = 0 + results = 0 + for key, value in message.items(): + if key in ("role", "type") or key in _SKIP_KEYS: + continue + if key == "tool_calls" and isinstance(value, list): # OpenAI / LiteLLM + for call in map(_as_plain, value): + function = _as_plain(call.get("function")) if isinstance(call, dict) else None + if isinstance(function, dict): + yield from _leaves(function.get("arguments"), f"{where}.tool_call[{calls}]({function.get('name')}).arguments", payload=True) + calls += 1 + elif key == "content" and role == "tool": # OpenAI tool message, text or a list of parts + yield from _leaves(value, f"{where}.tool_result[0]({names.get(str(message.get('tool_call_id')), '?')})", payload=True) + elif key in ("content", "parts") and isinstance(value, list): + for index, block in enumerate(map(_as_plain, value)): + if not isinstance(block, dict): + yield from _leaves(block, f"{where}.content[{index}]") + continue + if block.get("type") == "tool_use" or isinstance(block.get("toolUse"), dict): + use = block.get("toolUse") or block + yield from _leaves(use.get("input"), f"{where}.tool_call[{calls}]({use.get('name')}).arguments", payload=True) + calls += 1 + elif isinstance(block.get("function_call") or block.get("functionCall"), dict): # Gemini + call = block.get("function_call") or block.get("functionCall") + yield from _leaves(call.get("args"), f"{where}.tool_call[{calls}]({call.get('name')}).arguments", payload=True) + calls += 1 + elif block.get("type") == "tool_result" or isinstance(block.get("toolResult"), dict): + result = block.get("toolResult") or block + name = names.get(str(result.get("toolUseId") or result.get("tool_use_id")), "?") + yield from _leaves(result.get("content"), f"{where}.tool_result[{results}]({name})", payload=True) + results += 1 + elif isinstance(block.get("function_response") or block.get("functionResponse"), dict): # Gemini + response = block.get("function_response") or block.get("functionResponse") + yield from _leaves(response.get("response"), f"{where}.tool_result[{results}]({response.get('name')})", payload=True) + results += 1 + else: + yield from _leaves({k: v for k, v in block.items() if k != "type"}, f"{where}.content[{index}]") + elif key == "output" and role == "function_call_output": # Responses API + yield from _leaves(value, f"{where}.tool_result[0]({names.get(str(message.get('call_id')), '?')})", payload=True) + elif key == "arguments" and role == "function_call": + yield from _leaves(value, f"{where}.tool_call[0]({message.get('name')}).arguments", payload=True) + elif key == "content" and isinstance(value, str): + yield f"{where}.text", value + elif not (key == "name" and role == "function_call"): + yield from _leaves(value, f"{where}.{key}") + + +def _tool(tool: Any, where: str) -> Iterator[tuple[str, str]]: + tool = _as_plain(tool) + if not isinstance(tool, dict): + yield from _leaves(tool, where) + return + spec = tool.get("function") if isinstance(tool.get("function"), dict) else tool.get("toolSpec") if isinstance(tool.get("toolSpec"), dict) else tool + name = spec.get("name", "?") + for key, value in spec.items(): + if key == "name": + yield f"{where}[{name}].name", str(value) + elif key in ("parameters", "input_schema", "inputSchema"): + yield from _leaves(value, f"{where}[{name}].schema", payload=True) + else: + yield from _leaves(value, f"{where}[{name}].{key}") + + +def iter_request_texts(source: Source) -> Iterable[tuple[str, str]]: + """Every text a request sends the model, as ``(where, text)`` pairs. + + Args: + source: A cassette path, an ``LLMCassetteRecorder`` or ``MockLLM`` after the run (all its requests: in replay, the recorded ones), or one ``NormalizedRequest``. An ``ExecutionResult`` is not accepted: it does not keep the tool definitions or the system prompt. + + ``where`` reads like ``request[0].system``, ``request[0].message[2](assistant).tool_call[0](get_weather).arguments.city``, ``request[0].message[3](user).tool_result[0](get_weather).temp``, ``request[0].tool[get_weather].schema.properties.unit.enum[1]``, or ``request[0].parameters.temperature``. Messages carry their role, so ``(assistant)`` picks out the model's own answers; tool results carry the tool's name. JSON strings (tool arguments, tool results) are read as the values they hold. Numbers and booleans come as text. Provider ids (``toolUseId``, ``tool_call_id``), reasoning signatures, and embedded images or files (``data:`` URLs, ``bytes``) are left out. A recorded cassette holds the sanitized request; while recording, the recorder keeps the request as sent. + """ + for i, request in enumerate(_requests(source)): + names = _tool_names(request) + for key, value in (request.parameters or {}).items(): + yield from _leaves(value, f"request[{i}].system" if key in _SYSTEM_KEYS else f"request[{i}].parameters.{key}") + for j, message in enumerate(request.messages or []): + yield from _message(message, f"request[{i}].message[{j}]", names) + for tool in request.tools or []: + yield from _tool(tool, f"request[{i}].tool") diff --git a/agentverify/credentials.py b/agentverify/credentials.py new file mode 100644 index 0000000..00511fb --- /dev/null +++ b/agentverify/credentials.py @@ -0,0 +1,69 @@ +"""``assert_no_credential_urls``: no URL the model was sent carries a key, token, or signature.""" + +from __future__ import annotations + +import html +import re +from typing import Iterable, Optional +from urllib.parse import parse_qsl, urlsplit + +from agentverify.cassette.texts import Source, iter_request_texts +from agentverify.errors import CredentialURLError + +#: Query names that make a URL a credential (compared case-insensitively). ``key`` gives false alarms on APIs that use it for an ordinary value: pass ``ignore=["key"]``. +CREDENTIAL_QUERY_NAMES = frozenset( + { + "token", "access_token", "id_token", "refresh_token", "security_token", "session_token", "sessionid", + "api_key", "apikey", "key", "client_secret", "secret", "password", "passwd", "auth", "authorization", "jwt", + "sig", "signature", "x-amz-signature", "x-amz-security-token", "x-amz-credential", "x-goog-signature", "x-goog-credential", + } +) # fmt: skip +_URL = re.compile(r"https?://[^\s\"'<>\\]+", re.IGNORECASE) +_JWT = re.compile(r"eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+") + + +def _split(url: str) -> tuple[str, str, str, str]: + """(host, path, query, fragment); a URL urlsplit rejects (a bracketed placeholder host) is split by hand.""" + try: + parts = urlsplit(url) + return parts.hostname or "?", parts.path, parts.query, parts.fragment + except ValueError: + rest, _, fragment = url.partition("#") + rest, _, query = rest.partition("?") + return "?", rest, query, fragment + + +def _reasons(url: str, names: frozenset[str], extra: list[re.Pattern[str]]) -> list[str]: + _, path, query, fragment = _split(url) + # The query, and the fragment where implicit OAuth flows put access_token. + found = {name for part in (query, fragment) for name, _ in parse_qsl(part, keep_blank_values=True) if name.lower() in names} + reasons = sorted(found) + if any(_JWT.search(part) for part in (path, query, fragment)): + reasons.append("JWT") + reasons += [f"pattern {pattern.pattern!r}" for pattern in extra if pattern.search(url)] + return reasons + + +def assert_no_credential_urls(source: Source, extra_patterns: Optional[Iterable[str]] = None, ignore: Optional[Iterable[str]] = None) -> None: + """Verify that no URL in the requests the model was sent carries a credential. + + A URL carries one when a query name is in :data:`CREDENTIAL_QUERY_NAMES` (presigned download links, ``?access_token=``, ``X-Amz-Signature``, Azure SAS ``sig``), or a JWT sits in its path or query. Every text of the requests is searched, as :func:`iter_request_texts` walks them: tool results, tool definitions, and the system prompt included. + + Args: + source: A cassette path, an ``LLMCassetteRecorder`` or ``MockLLM`` after the run, or one ``NormalizedRequest``. + extra_patterns: Regular expressions; a URL any of them matches also fails (for example ``r"[?&]code="`` for OAuth codes). + ignore: Query names to drop from the defaults (for example ``["key"]``). + + Raises: + CredentialURLError: Listing where each URL was, its host, and why, never the values. + """ + names = CREDENTIAL_QUERY_NAMES - {name.lower() for name in ignore or []} + extra = [re.compile(pattern) for pattern in extra_patterns or []] + found = [] + for where, text in iter_request_texts(source): + for url in _URL.findall(html.unescape(text)): # & in HTML a tool returned separates parameters too + reasons = _reasons(url, names, extra) + if reasons: + found.append({"where": where, "host": _split(url)[0], "reasons": reasons}) + if found: + raise CredentialURLError(violations=found) diff --git a/agentverify/errors.py b/agentverify/errors.py index acdaa5d..650a16d 100644 --- a/agentverify/errors.py +++ b/agentverify/errors.py @@ -143,7 +143,10 @@ def _build_message(self) -> str: n = len(self.errors) lines = [f"{n} assertion{'s' if n != 1 else ''} failed:", ""] for i, err in enumerate(self.errors, start=1): - lines.append(f" [{i}] {type(err).__name__}: {err}") + first, *rest = str(err).split("\n") + lines.append(f" [{i}] {type(err).__name__}: {first}") + # Each failure's own lines sit under its number. + lines.extend(f" {line}" if line else "" for line in rest) lines.append("") return "\n".join(lines) @@ -166,6 +169,21 @@ class CassetteExpiredError(AgentVerifyError): pass +class CassetteDriftError(AgentVerifyError): + """Raised with ``drift="fail"`` when a replayed request's tool results, messages, or parameters differ from the recording. + + ``index`` is the request's position in the cassette, ``places`` the ``where`` of each difference (no values). + """ + + def __init__(self, cassette: str, index: int, places: list[str]) -> None: + self.cassette = cassette + self.index = index + self.places = places + lines = [f"{cassette}: request {index} differs from the recording", ""] + [f" {p}" for p in places] + lines += ["", "Re-record it with --cassette-mode=record, or leave the places that change on every run out with drift_ignore."] + super().__init__("\n".join(lines)) + + class CassetteUnsupportedCallError(AgentVerifyError): """Raised when an LLM call inside a cassette cannot be recorded or replayed. @@ -477,3 +495,27 @@ def _build_message(self) -> str: lines.append(f" #{v['position']} {v['tool_name']}({_truncate_repr(v['arguments'])}){call_id}") lines.extend(f" {reason}" for reason in v["reasons"]) return "\n".join(lines) + + +class CredentialURLError(AgentVerifyError): + """Raised by :func:`assert_no_credential_urls` when a request the model was sent holds a URL that carries a credential. + + ``violations`` lists each URL as a dict with ``where``, ``host``, and ``reasons`` (the credential query names, ``JWT``, or the extra pattern that matched). The values themselves are never included. + """ + + def __init__(self, violations: list[dict[str, Any]]) -> None: + self.violations = violations + super().__init__(self._build_message()) + + def _build_message(self) -> str: + n = len(self.violations) + lines = [f"{n} URL{'s' if n != 1 else ''} with a credential sent to the model", ""] + for v in self.violations: + lines.append(f" {v['where']}: {v['host']} ({', '.join(v['reasons'])})") + return "\n".join(lines) + + +def _own_error(excinfo: Any) -> bool: + """For ``__tracebackhide__``: hide agentverify's frames when it raised one of its own errors, and keep them for anything else (a bug to report).""" + return bool(excinfo.errisinstance(AgentVerifyError)) + diff --git a/agentverify/fixtures.py b/agentverify/fixtures.py index c448f35..6863663 100644 --- a/agentverify/fixtures.py +++ b/agentverify/fixtures.py @@ -17,6 +17,7 @@ from agentverify.cassette.sanitize import SanitizePattern STALE_PROPERTY = "agentverify_stale_cassettes" +NEW_PROPERTY = "agentverify_new_cassettes" #: Sentinel value to distinguish "caller didn't pass mode" from "caller #: explicitly passed CassetteMode.AUTO". @@ -51,14 +52,15 @@ def test_agent(cassette): By default the cassette file is stored in a ``cassettes/`` directory next to the test file. Override with the *cassette_dir* parameter. """ - from agentverify.cassette.recorder import _stale_cassettes + from agentverify.cassette.recorder import _new_cassettes, _stale_cassettes def _report_stale() -> None: - # The test's stale cassettes travel on its report, so the summary lists them under pytest-xdist too. - mine = [entry for entry in _stale_cassettes if entry[1] == request.node.nodeid] - if mine: - _stale_cassettes[:] = [entry for entry in _stale_cassettes if entry[1] != request.node.nodeid] - request.node.user_properties.append((STALE_PROPERTY, mine)) + # The test's stale and newly recorded cassettes travel on its report, so the summary lists them under pytest-xdist too. + for entries, name in ((_stale_cassettes, STALE_PROPERTY), (_new_cassettes, NEW_PROPERTY)): + mine = [entry for entry in entries if entry[1] == request.node.nodeid] + if mine: + entries[:] = [entry for entry in entries if entry[1] != request.node.nodeid] + request.node.user_properties.append((name, mine)) request.addfinalizer(_report_stale) @@ -74,6 +76,8 @@ def _cassette( match_ignore: Union[list[str], None] = None, max_age: Union[str, timedelta, None, object] = _MODE_NOT_SET, on_expired: Union[str, None] = None, + drift: Union[str, None] = None, + drift_ignore: Union[list[str], None] = None, ) -> LLMCassetteRecorder: # Resolve mode: explicit arg > CLI option > default AUTO if mode is _MODE_NOT_SET: @@ -100,6 +104,9 @@ def _cassette( max_age = request.config.getoption("--cassette-max-age", default=None) or _ini(request.config, "agentverify_cassette_max_age") if on_expired is None: on_expired = request.config.getoption("--cassette-expired", default=None) or "error" + # Resolve drift: explicit arg > --cassette-drift > the agentverify_cassette_drift ini setting > off + if drift is None: + drift = request.config.getoption("--cassette-drift", default=None) or _ini(request.config, "agentverify_cassette_drift") or "off" from agentverify.live import live_settings @@ -134,6 +141,8 @@ def _cassette( match_ignore=match_ignore, max_age=max_age, # type: ignore[arg-type] on_expired=on_expired, + drift=drift, + drift_ignore=drift_ignore, ) recorder.test_id = request.node.nodeid return recorder diff --git a/agentverify/plugin.py b/agentverify/plugin.py index a130efb..b9a4e8f 100644 --- a/agentverify/plugin.py +++ b/agentverify/plugin.py @@ -15,8 +15,8 @@ def pytest_addoption(parser): # type: ignore[no-untyped-def] parser.addoption( "--cassette-mode", default=None, - choices=["auto", "record", "replay"], - help="Override cassette mode for all tests (auto, record, replay).", + choices=["auto", "record", "replay", "record-missing"], + help="Override cassette mode for all tests (auto, record, replay, record-missing).", ) parser.addoption( "--no-cassette-match-requests", @@ -41,6 +41,17 @@ def pytest_addoption(parser): # type: ignore[no-untyped-def] default=False, help="List the cassettes next to the collected tests (recorded when, with which model, expired or not) instead of running the tests.", ) + parser.addoption( + "--cassette-drift", + default=None, + choices=["off", "warn", "fail"], + help="Compare replayed tool results, messages, and parameters with the recording: off (default), warn, or fail. Overrides the agentverify_cassette_drift ini setting.", + ) + parser.addini( + "agentverify_cassette_drift", + default="", + help="Compare replayed tool results, messages, and parameters with the recording: off (default), warn, or fail.", + ) parser.addini( "agentverify_cassette_max_age", default="", @@ -90,8 +101,8 @@ def pytest_runtest_protocol(item, nextitem): # type: ignore[no-untyped-def] def pytest_runtest_logreport(report): # type: ignore[no-untyped-def] - from agentverify.cassette.recorder import _stale_cassettes - from agentverify.fixtures import STALE_PROPERTY + from agentverify.cassette.recorder import _new_cassettes, _stale_cassettes + from agentverify.fixtures import NEW_PROPERTY, STALE_PROPERTY from agentverify.live import collect collect(report) @@ -99,14 +110,31 @@ def pytest_runtest_logreport(report): # type: ignore[no-untyped-def] for name, value in report.user_properties: if name == STALE_PROPERTY: _stale_cassettes.extend(tuple(entry) for entry in value) + elif name == NEW_PROPERTY: + _new_cassettes.extend(tuple(entry) for entry in value) + + +def _new_summary(terminalreporter, new): # type: ignore[no-untyped-def] + """The cassettes record-missing recorded in this run, to review and commit.""" + from agentverify.cassette.report import _relative + + if not new: + return + terminalreporter.section("agentverify: new cassettes") + root = terminalreporter.config.rootpath + for path in dict.fromkeys(path for path, _ in new): + terminalreporter.write_line(_relative(Path(path), root)) + new.clear() def pytest_terminal_summary(terminalreporter): # type: ignore[no-untyped-def] """List the cassettes that no longer match the requests the agent makes, with the command to re-record them, and the pass rates of live runs.""" - from agentverify.cassette.recorder import _stale_cassettes + from agentverify.cassette.recorder import _new_cassettes, _stale_cassettes + from agentverify.cassette.report import _relative from agentverify.live import summary summary(terminalreporter) + _new_summary(terminalreporter, _new_cassettes) if not _stale_cassettes: return @@ -119,12 +147,10 @@ def pytest_terminal_summary(terminalreporter): # type: ignore[no-untyped-def] tests.add(test_id) terminalreporter.section("agentverify: stale cassettes") for path, (fields, tests) in stale.items(): - try: - shown = str(Path(path).relative_to(root)) - except ValueError: - shown = path - changed = [f for f in sorted(fields) if not f.startswith("expired")] - reasons = ([f"{', '.join(changed)} changed"] if changed else []) + [f for f in sorted(fields) if f.startswith("expired")] + shown = _relative(Path(path), root) + verbatim = ("expired", "drift") + changed = [f for f in sorted(fields) if not f.startswith(verbatim)] + reasons = ([f"{', '.join(changed)} changed"] if changed else []) + [f for f in sorted(fields) if f.startswith(verbatim)] terminalreporter.write_line(f"{shown} ({'; '.join(reasons)})") every_test = sorted(set().union(*(tests for _, tests in stale.values()))) if every_test: diff --git a/docs/cassettes.md b/docs/cassettes.md new file mode 100644 index 0000000..9ab144f --- /dev/null +++ b/docs/cassettes.md @@ -0,0 +1,87 @@ +# Cassettes in Detail + +The details behind [Record & Replay with Cassettes](../README.md#record--replay-with-cassettes) in the README. + +## Recorded and Unsupported Calls + +Cassettes record chat calls, streamed or not, sync or async: OpenAI `chat.completions.create` and `responses.create` (and their `stream()` helpers), Anthropic `messages.create` and `messages.stream()`, Gemini `models.generate_content` and `generate_content_stream`, Bedrock `Converse` and `ConverseStream`, and LiteLLM `completion` / `acompletion`. Inside a cassette or `MockLLM`, other LLM calls are handled as follows. + +These raise `CassetteUnsupportedCallError`: +- Other streaming calls (OpenAI `responses.connect()` WebSocket sessions, Anthropic `messages.stream(output_format=...)`, Bedrock `InvokeModelWithResponseStream`, ...), in record and replay mode. +- In replay mode, every other request through an OpenAI, Anthropic, or Gemini SDK client (`parse()`, embeddings, beta resources, ...), Bedrock operations that generate (`InvokeModel`, `InvokeAgent`, `RetrieveAndGenerate`, ...), and LiteLLM `text_completion` and `responses`. + +These reach the real API: +- In record mode, those other requests. `parse()`, the Bedrock operations, and the LiteLLM calls warn that the cassette will not contain them; embeddings, beta resources, and WebSocket APIs do not. Replay then fails at that call. +- With no cassette file (`AUTO` passthrough), every call. Nothing is saved. + +OpenAI models on Amazon Bedrock can be reached three ways; record each with the provider that owns the client: + +| Route | Cassette provider | +|---|---| +| boto3 `bedrock-runtime` `converse` | `"bedrock"` | +| OpenAI SDK with `base_url="https://bedrock-runtime..amazonaws.com/openai/v1"` (`chat.completions.create`, `responses.create`) | `"openai"` | +| boto3 `invoke_model` | not recorded; raises in replay mode | + +## Streaming + +A streamed call is stored as the same response as a non-streamed one, so a cassette recorded either way replays either way. Frameworks that stream by default (Strands' `BedrockModel`, `Runner.run_streamed` in the OpenAI Agents SDK, LangChain's `stream()`) need no change. Replay yields the text in one chunk and each tool call in one chunk, not in the recorded chunk sizes. A stream the agent stops reading early is recorded with what it read. + +## OpenAI Responses API + +`responses.create` is recorded in the same `provider="openai"` cassette as Chat Completions, including the `with_raw_response` path that langchain-openai uses. The OpenAI Agents SDK uses it by default. Tool results sent back as `function_call_output` items become the step's `tool_results`, so `assert_step_uses_result_from` works the same way. Only function tools are recorded: a response with a client-executed computer, shell, apply-patch, or custom tool call raises `CassetteUnsupportedCallError`. + +With `previous_response_id` or `conversation`, the API keeps earlier turns on the server and each request carries only the new input. The cassette then misses those turns, and agentverify warns. Pass `store=False` and send the full input instead. + +## Async and Concurrent Calls + +Async clients of OpenAI, Anthropic, Gemini, LiteLLM, and Bedrock (`aiobotocore` / `aioboto3`) are recorded and replayed. agentverify does not depend on `pytest-asyncio` or `anyio`; use whichever you already have, or `asyncio.run()` in a sync test. + +Calls may overlap (`asyncio.gather`, threads). Replay matches each request to its recording on the model, tool names, system prompt, user text, and history length, so calls that finish in another order than when recorded still get their own responses; requests identical in all of these replay in recorded order. Concurrent agents keep their own `step_probe` steps and tool results. + +## Tool Replay + +- Tools are recorded through LangChain / LangGraph, Strands Agents, OpenAI Agents SDK, Pydantic AI, Google ADK, CrewAI, and MCP's `ClientSession.call_tool`, including agents created before the cassette. For a hand-written agent, decorate the tool function with `@cassette_tool`. +- Calls match on the tool name and arguments, in any order. A call with no recorded match raises `CassetteToolMismatchError`, and fails the test when the cassette closes, even if the framework passed the error to the model. +- A tool error replays as it was recorded: the error result the framework made of it, or the same exception type and message (`agentverify.cassette.tools.ReplayedToolError` when the type cannot be rebuilt from its message). +- Some calls run for real on replay too. Results that do not survive YAML (a LangGraph `Command`, binary content), CrewAI tools with `result_as_answer`, and LangGraph interrupts are marked `run_on_replay` in the cassette. Tools that steer the run (Google ADK `transfer_to_agent` / `exit_loop`, Strands `handoff_to_agent`) and the tool behind Strands' `structured_output_model` are not recorded at all. +- A replayed tool that called the LLM while recording (an agent used as a tool) skips those LLM calls on replay, so the outer agent's calls stay in step. +- Replay returns the recorded result only. What a tool does to the agent's own state is not replayed: Google ADK `tool_context.state`, Pydantic AI `deps`, an OpenAI Agents SDK context object, or anything else the tool changes in the process. LangChain tool callbacks (`on_tool_start` / `on_tool_end`) do not fire for a replayed call either. Pass `replay_tools=False` when a test depends on these. +- MCP servers still start on replay, since the agent lists their tools. +- Cassettes recorded before 0.7.0 have no `tool_executions`, and their tools run for real. + +## Request Matching + +Each replayed request is compared with the recorded one: +- **Model name** (an empty model on either side skips the check) +- **Tool names**, and each tool's **parameter schema** (a request with no tools on either side skips the check) +- **System prompt**: system and developer messages, and the providers' `system` / `instructions` parameters +- **User message text**. Tool results in their own messages or blocks are not compared, since a tool running for real may return something new. + +A field the cassette did not record (no system prompt, or a cassette from an older version) is not compared. The request is sanitized like the cassette before comparing. A difference raises `CassetteRequestMismatchError` with a diff, and fails the test when the cassette closes even if the agent's framework caught it. + +## Drift + +Request matching leaves tool results alone. Drift compares the rest: tool results (key by key, when they are JSON, so a new `null` counts), the number and roles of the messages, and the provider's other parameters. + +- `off` (default), `warn`, or `fail`, from the `agentverify_cassette_drift` setting, `--cassette-drift`, or `cassette(drift=...)` (the later ones win). It also applies with `match_requests=False`. +- `warn` adds the cassette and the places that differ (never the values) to the stale list at the end of the run; `fail` raises `CassetteDriftError`. +- `drift_ignore` takes globs over the places as `iter_request_texts` names them (`request[*].message[*].tool_result[*].now`), with or without the `(role)` and `(tool)` parts. `match_ignore` applies too. +- It is off by default because a tool that runs for real may return something new on every run. + +## Expiry and the Cassette Report + +- Replaying a cassette recorded longer ago than `max_age` raises `CassetteExpiredError` before the agent runs (`on_expired="warn"` or `--cassette-expired=warn` only warns), and the cassette joins the stale list. +- The age comes from the cassette's `metadata.recorded_at`; a value without a time zone is UTC, and a cassette without one counts as expired. +- The limit comes from `agentverify_cassette_max_age`, `--cassette-max-age`, or `cassette(max_age=...)` (the later ones win). The setting and the option apply to cassettes opened with the `cassette` fixture; an `LLMCassetteRecorder` you create yourself checks only the `max_age` you pass it. +- `pytest --cassette-report` runs no tests and lists the cassettes in the `cassettes/` directory next to each collected test file (not a custom `cassette_dir`): when and with which model each was recorded, and whether it is past the suite or run limit (not a `max_age=` passed to one cassette). Files there that are not cassettes are left out. It needs a run without pytest-xdist workers (`-p no:xdist`). + +## Checking What the Model Was Sent + +`iter_request_texts` reads a cassette path, an `LLMCassetteRecorder` or `MockLLM` after the run, or one `NormalizedRequest`. `where` reads like `request[0].system`, `request[0].message[2](assistant).tool_call[0](get_weather).arguments.city`, `request[0].message[3](tool).tool_result[0](get_weather).temp`, `request[0].tool[get_weather].schema.properties.unit.enum[1]`, or `request[0].parameters.temperature`. + +- Messages carry their role, so `(assistant)` picks out the model's own answers; tool results carry the tool's name. +- JSON tool arguments and results are read key by key, and numbers and booleans come as text. +- Provider ids (`toolUseId`, `tool_call_id`), reasoning signatures, and embedded images or files are left out of the provider's envelope; inside tool arguments, results, and schemas every key is kept. +- A saved cassette holds the sanitized request; while recording, the recorder keeps the request as sent. + +`assert_no_credential_urls` searches every one of those texts. A URL fails when a query or fragment name is in `agentverify.credentials.CREDENTIAL_QUERY_NAMES` (`token`, `access_token`, `security_token`, `api_key`, `key`, `secret`, `password`, `sig`, `signature`, the AWS and Google signature names, and more) or a JWT sits in its path, query, or fragment. HTML entities such as `&` are decoded first. `extra_patterns` adds regular expressions (`r"[?&]code="` for OAuth codes) and `ignore` drops default names (`key` gives false alarms on APIs that use it for ordinary values). The error lists where each URL was, its host, and why, never the values. diff --git a/docs/reference.md b/docs/reference.md new file mode 100644 index 0000000..f9aa099 --- /dev/null +++ b/docs/reference.md @@ -0,0 +1,124 @@ +# API Reference + +Every public name, what it is for, and where it is described. Names are imported from `agentverify` unless another module is given. + +## Index + +| Area | Names | Described in | +|---|---|---| +| Results | `ExecutionResult`, `Step`, `ToolCall`, `TokenUsage`, `Handoff` | [Build an ExecutionResult](../README.md#build-an-executionresult), [Result Objects](#result-objects) | +| Matchers | `ANY`, `MATCHES`, `OrderMode` | [Assertion Modes](../README.md#assertion-modes) | +| Tool call assertions | `assert_tool_calls`, `assert_no_tool_call`, `assert_tool_calls_allowed`, `assert_all` | [Assertion Modes](../README.md#assertion-modes), [Allowed Tools](../README.md#allowed-tools) | +| Budgets and output | `assert_cost`, `assert_latency`, `assert_final_output` | [Budgets and Final Output](../README.md#budgets-and-final-output) | +| Step assertions | `assert_step`, `assert_step_output`, `assert_step_uses_result_from`, `step_probe`, `ProbeHandle` | [Step-Level Assertions](../README.md#step-level-assertions), [`step_probe`](#step_probe) | +| Handoffs | `assert_handoffs`, `assert_no_handoff` | [Multi-Agent Handoffs](../README.md#multi-agent-handoffs) | +| Tool results | `assert_tool_invocation_succeeded`, `assert_no_tool_errors`, `assert_tool_result_matches`, `assert_retry_count` | [Tool Result Assertions](../README.md#tool-result-assertions), [tool-results.md](tool-results.md) | +| What the model was sent | `iter_request_texts`, `assert_no_credential_urls` (`agentverify.credentials.CREDENTIAL_QUERY_NAMES`) | [README](../README.md#checking-what-the-model-was-sent), [cassettes.md](cassettes.md#checking-what-the-model-was-sent) | +| Cassettes | the `cassette` fixture, `LLMCassetteRecorder`, `CassetteMode`, `cassette_tool`, `SanitizePattern`, `DEFAULT_PATTERNS` (`agentverify.cassette.recorder.OnMissingRequest`) | [Record & Replay](../README.md#record--replay-with-cassettes), [cassettes.md](cassettes.md), [below](#llmcassetterecorder-without-the-fixture) | +| Mocking | `MockLLM`, `mock_response` | [LLM Mocking with MockLLM](../README.md#llm-mocking-with-mockllm) | +| Framework adapters | `agentverify.frameworks..from_` | [Built-in Adapters](../README.md#built-in-adapters) | +| Traces | `agentverify.traces.from_otel` | [Production Traces](../README.md#production-traces) | +| pytest | the `agentverify` marker (`runs=`, `min_pass_rate=`), `--cassette-mode`, `--no-cassette-match-requests`, `--cassette-max-age`, `--cassette-expired`, `--cassette-drift`, `--cassette-report`, `--agentverify-live`, the `agentverify_cassette_max_age` and `agentverify_cassette_drift` settings | [Record & Replay](../README.md#record--replay-with-cassettes), [Live Runs](../README.md#live-runs-and-pass-rates), [cassettes.md](cassettes.md) | +| Errors | every `*Error` | [Errors](#errors) | + +The sections below cover what the README only mentions. + +## `LLMCassetteRecorder` Without the Fixture + +The `cassette` fixture builds an `LLMCassetteRecorder`; outside pytest, or to place the file yourself, build one directly. It takes the same options, and the pytest settings and command-line options (mode, expiry, drift) do not apply to it: + +```python +from agentverify import CassetteMode, LLMCassetteRecorder + +with LLMCassetteRecorder("tests/cassettes/weather.yaml", mode=CassetteMode.REPLAY, provider="bedrock") as rec: + run_my_agent("What's the weather in Seattle?") +result = rec.to_execution_result() +``` + +| Argument | Default | Meaning | +|---|---|---| +| `cassette_path` | | The cassette file (`.yaml` or `.json`) | +| `mode` | `CassetteMode.AUTO` | `AUTO`, `RECORD`, `REPLAY`, or `RECORD_MISSING` (see the [modes](../README.md#record--replay-with-cassettes)). The fixture also takes the values as strings (`mode="replay"`) | +| `provider` | `"openai"` | `"openai"`, `"anthropic"`, `"bedrock"`, `"gemini"`, `"litellm"`, or an `LLMProviderAdapter` instance | +| `on_missing` | `OnMissingRequest.ERROR` | What a replayed request or tool call with no recording does; see below | +| `match_requests` | `True` | [Request matching](cassettes.md#request-matching) | +| `match_ignore` | `None` | Regular expressions left out of request matching and drift | +| `sanitize` | `True` | [Sanitization](../README.md#cassette-sanitization): `True`, `False`, or a list of `SanitizePattern` | +| `replay_tools` | `True` | [Tool replay](cassettes.md#tool-replay) | +| `max_age` / `on_expired` | `None` / `"error"` | [Expiry](cassettes.md#expiry-and-the-cassette-report) | +| `drift` / `drift_ignore` | `"off"` / `None` | [Drift](cassettes.md#drift) | + +The fixture adds `cassette_dir` (default: a `cassettes/` directory next to the test file). + +### Requests With No Recording + +By default, a replayed LLM request the cassette has no response for raises `CassetteMissingRequestError` (the message gives the request number and how many responses the cassette has), and a tool call with no recorded result raises `CassetteToolMismatchError`. With `on_missing=OnMissingRequest.FALLBACK` (`on_missing="fallback"` in the fixture), both go to the real API or tool instead, and nothing new is saved: + +```python +with cassette("weather.yaml", provider="openai", on_missing="fallback") as rec: + run_my_agent("What's the weather in Tokyo and Paris?") # Paris was not recorded: it calls the API +``` + +## `@cassette_tool` + +For a hand-written agent whose tools no built-in hook covers. Outside a cassette the function runs as usual; inside one, its calls are recorded and replayed like a framework's tools. It works on sync and async functions and on methods (`self` / `cls` are not recorded). `name=` sets the recorded tool name (default: the function's name). Put it under a framework's own `@tool` decorator; the signature is kept for schema generation: + +```python +from agentverify import cassette_tool + +@cassette_tool +def get_weather(city: str) -> str: + return http_get(f"https://weather.example/{city}") + +@cassette_tool(name="fetch") +async def fetch_page(url: str) -> str: + ... +``` + +## `step_probe` + +`step_probe(name, output=None)` marks a step of your own in the agent's code ([example](../README.md#workflow-style-agents-with-step_probe)). It yields a `ProbeHandle`: + +- `handle.set_tool_result(result, is_error=False)`: attach a tool result to the step; `is_error=True` marks it a failed call for the [tool result assertions](tool-results.md) +- `handle.set_output(value)`: set the step's text output (the same as `output=`) + +LLM calls made inside the block join the step. Outside a cassette or `MockLLM`, the probe does nothing. + +## Result Objects + +- `ExecutionResult.from_dict()`, `from_json()`, `to_dict()`, `to_json()`: see [Build an ExecutionResult](../README.md#build-an-executionresult) +- `ExecutionResult.from_flat_tool_calls(tool_calls, *, token_usage=None, total_cost_usd=None, duration_ms=None, final_output=None)`: a single-step result from a list of `ToolCall`s +- `ExecutionResult.tool_calls`: every step's tool calls in order; `steps`, `handoffs`, `final_output`, `token_usage`, `total_cost_usd`, `duration_ms` +- `Step.has_tool_error()`: whether any tool result at the step is a known error; `Step.tool_result_is_error(i)`: `True`, `False`, or `None` (unknown) for result `i` +- `ToolCall(name, arguments, result=None, call_id=None)`: `call_id` is not compared +- `TokenUsage(input_tokens, output_tokens)` and its `total_tokens` +- `Handoff(from_agent, to_agent, step=None)` + +## Errors + +Every error extends `AgentVerifyError`, which extends `AssertionError`, so pytest reports them as test failures. All are in `agentverify.errors`; the ones marked ✓ are also exported from `agentverify`. + +| Error | Raised by | `agentverify` | +|---|---|---| +| `ToolCallSequenceError` | `assert_tool_calls`, and `assert_step` on the step's tool calls | | +| `SafetyRuleViolationError` | `assert_no_tool_call` | | +| `ToolPolicyError` | `assert_tool_calls_allowed` | ✓ | +| `CostBudgetError` | `assert_cost` | | +| `LatencyBudgetError` | `assert_latency` | | +| `FinalOutputError` | `assert_final_output` | | +| `MultipleAssertionError` | `assert_all`, with every failure | | +| `StepIndexError`, `StepNameNotFoundError`, `StepNameAmbiguousError` | step assertions given a step that does not exist or a name more than one step has | ✓ | +| `StepOutputError` | `assert_step_output` | ✓ | +| `StepAgentError` | `assert_step(agent=...)` | ✓ | +| `StepDependencyError` | `assert_step_uses_result_from` | ✓ | +| `HandoffError` | `assert_handoffs`, `assert_no_handoff` | ✓ | +| `ToolInvocationError` | `assert_tool_invocation_succeeded`, `assert_no_tool_errors` | ✓ | +| `ToolResultMatchError` | `assert_tool_result_matches` | ✓ | +| `RetryBudgetError` | `assert_retry_count` | ✓ | +| `CredentialURLError` | `assert_no_credential_urls` | ✓ | +| `CassetteRequestMismatchError` | replay, when the request changed | ✓ | +| `CassetteMissingRequestError` | replay or `MockLLM`, out of responses | ✓ | +| `CassetteToolMismatchError` | replay, a tool call with no recorded result | ✓ | +| `CassetteExpiredError` | replay, a cassette past its `max_age` | ✓ | +| `CassetteDriftError` | replay with `drift="fail"` | ✓ | +| `CassetteUnsupportedCallError` | an LLM call a cassette cannot record or replay | ✓ | diff --git a/docs/screenshot-error-output.png b/docs/screenshot-error-output.png deleted file mode 100644 index 8433c2c..0000000 Binary files a/docs/screenshot-error-output.png and /dev/null differ diff --git a/docs/screenshots/multi-agent.png b/docs/screenshots/multi-agent.png new file mode 100644 index 0000000..c4b9ede Binary files /dev/null and b/docs/screenshots/multi-agent.png differ diff --git a/docs/screenshots/safety.png b/docs/screenshots/safety.png new file mode 100644 index 0000000..ad02f65 Binary files /dev/null and b/docs/screenshots/safety.png differ diff --git a/docs/screenshots/simple.png b/docs/screenshots/simple.png new file mode 100644 index 0000000..7e6d483 Binary files /dev/null and b/docs/screenshots/simple.png differ diff --git a/docs/screenshots/stale-cassette.png b/docs/screenshots/stale-cassette.png new file mode 100644 index 0000000..d0bf91e Binary files /dev/null and b/docs/screenshots/stale-cassette.png differ diff --git a/docs/tool-results.md b/docs/tool-results.md new file mode 100644 index 0000000..e56683e --- /dev/null +++ b/docs/tool-results.md @@ -0,0 +1,18 @@ +# Tool Result Error Signals + +The details behind [Tool Result Assertions](../README.md#tool-result-assertions) in the README. + +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 SDK default failure and timeout messages +- Pydantic AI retry prompts and tool return outcomes +- CrewAI `tool_failures` +- error-shaped results such as ADK's `{"status": "error"}` + +Cassette replay reconstructs it from the recorded tool messages (OpenAI tool messages, Anthropic `is_error`, Bedrock `toolResult` status). + +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. + +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)`. diff --git a/examples/strands-weather-forecaster/README.md b/examples/strands-weather-forecaster/README.md index 6df1f2f..1eb0794 100644 --- a/examples/strands-weather-forecaster/README.md +++ b/examples/strands-weather-forecaster/README.md @@ -12,7 +12,7 @@ Two LLM calls, one piece of data flowing between them: the simplest shape of a R - `assert_step` for per-step tool verification - `assert_step_uses_result_from` to verify that step 1 actually consumes step 0's result -The main README's [Real-World Examples](../../README.md#real-world-examples) section walks through the tests in detail. This README covers setup and execution only. +The main README's [Real-World Examples](../../README.md#real-world-example) section walks through the tests in detail. This README covers setup and execution only. ## Prerequisites diff --git a/examples/strands-weather-forecaster/pyproject.toml b/examples/strands-weather-forecaster/pyproject.toml index 683c7f8..1ce334e 100644 --- a/examples/strands-weather-forecaster/pyproject.toml +++ b/examples/strands-weather-forecaster/pyproject.toml @@ -8,8 +8,7 @@ version = "0.1.0" description = "Strands Weather Forecaster example for agentverify" requires-python = ">=3.10" dependencies = [ - "strands-agents", - "strands-agents-tools", # http_request + "strands-agents>=1.61", # http_request is one of its vended tools (strands-agents-tools 0.9 dropped its own) "agentverify", ] diff --git a/examples/strands-weather-forecaster/tests/cassettes/weather_seattle.yaml b/examples/strands-weather-forecaster/tests/cassettes/weather_seattle.yaml index 02ff409..51e9c56 100644 --- a/examples/strands-weather-forecaster/tests/cassettes/weather_seattle.yaml +++ b/examples/strands-weather-forecaster/tests/cassettes/weather_seattle.yaml @@ -1,6 +1,6 @@ metadata: - agentverify_version: 0.6.0 - recorded_at: '2026-10-22T02:13:57.135320+00:00' + agentverify_version: 0.8.0 + recorded_at: '2026-11-05T13:57:23.923506+00:00' provider: bedrock model: us.anthropic.claude-sonnet-4-6 interactions: @@ -12,154 +12,43 @@ interactions: tools: - name: http_request parameters: - type: object properties: method: - type: string - description: HTTP method (GET, POST, PUT, DELETE, etc.) - url: - type: string - description: The URL to send the request to - auth_type: - type: string + description: 'HTTP method (``GET``, ``POST``, ``PUT``, ``DELETE``, + + ``PATCH``, ``HEAD``, ``OPTIONS``).' enum: - - Bearer - - token - - basic - - digest - - jwt - - aws_sig_v4 - - kerberos - - custom - - api_key - description: Authentication type to use - auth_token: + - GET + - POST + - PUT + - DELETE + - PATCH + - HEAD + - OPTIONS type: string - description: Authentication token (if not provided, will check auth_env_var - if configured) - auth_env_var: + url: + description: Absolute URL to request. type: string - description: Name of an environment variable containing the auth token. - The variable must be listed in HTTP_REQUEST_TOKEN_CONFIG with an allowed - domain that matches the request URL. headers: + default: null + description: Optional request headers. type: object - description: HTTP headers as key-value pairs body: + default: null + description: Optional request body as a string. type: string - description: Request body (for POST, PUT, etc.) - verify_ssl: - type: boolean - description: Whether to verify SSL certificates. Disabling may be restricted. - cookie: - type: string - description: Path to cookie file to use for the request - cookie_jar: - type: string - description: Path to cookie jar file to save cookies to - session_config: - type: object - description: Session configuration (cookies, keep-alive, etc) - properties: - keep_alive: - type: boolean - description: Property keep_alive - max_retries: - type: integer - description: Property max_retries - pool_size: - type: integer - description: Property pool_size - cookie_persistence: - type: boolean - description: Property cookie_persistence - required: [] - metrics: - type: boolean - description: Whether to collect request metrics - streaming: - type: boolean - description: Enable streaming response handling - allow_redirects: - type: boolean - description: 'Whether to follow redirects (default: True)' - max_redirects: - type: integer - description: 'Maximum number of redirects to follow (default: 30)' timeout: + default: null + description: 'Optional per-request timeout in seconds. When a client + + is provided, capped at the client''s configured timeout. + + When no client is provided, used as-is.' type: number - description: 'Request timeout in seconds (default: 30). Use a large value - for no timeout.' - convert_to_markdown: - type: boolean - description: 'Convert HTML responses to markdown format (default: False).' - aws_auth: - type: object - description: AWS auth configuration for SigV4 - properties: - service: - type: string - description: Property service - region: - type: string - description: Property region - access_key: - type: string - description: Property access_key - secret_key: - type: string - description: Property secret_key - session_token: - type: string - description: Property session_token - refresh_credentials: - type: boolean - description: Property refresh_credentials - required: [] - basic_auth: - type: object - description: Basic auth credentials - properties: - username: - type: string - description: Property username - password: - type: string - description: Property password - required: - - username - - password - digest_auth: - type: object - description: Digest auth credentials - properties: - username: - type: string - description: Property username - password: - type: string - description: Property password - realm: - type: string - description: Property realm - required: [] - jwt_config: - type: object - description: JWT configuration - properties: - secret: - type: string - description: Property secret - algorithm: - type: string - description: Property algorithm - expiry: - type: integer - description: Property expiry - required: [] required: - method - url + type: object parameters: system: - text: 'You are a weather assistant with HTTP capabilities. You can: @@ -191,254 +80,137 @@ interactions: Always explain the weather conditions clearly and provide context for the forecast.' - inferenceConfig: {} + inferenceConfig: + maxTokens: 128000 stream: true response: - content: I'll look up the weather for Seattle! Let me start by getting the grid + content: Let me look up the weather for Seattle! I'll start by fetching the grid information for Seattle's coordinates. tool_calls: - name: http_request arguments: '{"method": "GET", "url": "https://api.weather.gov/points/47.6062,-122.3321"}' - id: tooluse_MOWg0vh0zvr0fUVv4mJ7mZ + id: tooluse_0K0PMeVRv6DZT1iOiJLE17 token_usage: - input_tokens: 1731 - output_tokens: 111 + input_tokens: 939 + output_tokens: 112 - request: messages: - role: user content: What's the weather in Seattle? - role: assistant content: - - text: I'll look up the weather for Seattle! Let me start by getting the grid + - text: Let me look up the weather for Seattle! I'll start by fetching the grid information for Seattle's coordinates. - toolUse: input: method: GET url: https://api.weather.gov/points/47.6062,-122.3321 name: http_request - toolUseId: tooluse_MOWg0vh0zvr0fUVv4mJ7mZ + toolUseId: tooluse_0K0PMeVRv6DZT1iOiJLE17 - role: user content: - toolResult: content: - - text: 'Status Code: 200' - - text: 'Headers: {''Server'': ''nginx/1.28.3'', ''Content-Type'': ''application/geo+json'', - ''Content-Length'': ''1010'', ''Date'': ''Thu, 22 Oct 2026 02:13:48 - GMT''}' - - text: "Body: {\n \"@context\": [\n \"https://geojson.org/geojson-ld/geojson-context.jsonld\"\ - ,\n {\n \"@version\": \"1.1\",\n \"wx\"\ - : \"https://api.weather.gov/ontology#\",\n \"s\": \"https://schema.org/\"\ - ,\n \"geo\": \"http://www.opengis.net/ont/geosparql#\",\n\ - \ \"unit\": \"http://codes.wmo.int/common/unit/\",\n \ - \ \"@vocab\": \"https://api.weather.gov/ontology#\",\n \ - \ \"geometry\": {\n \"@id\": \"s:GeoCoordinates\"\ - ,\n \"@type\": \"geo:wktLiteral\"\n },\n \ - \ \"city\": \"s:addressLocality\",\n \"state\"\ - : \"s:addressRegion\",\n \"distance\": {\n \ - \ \"@id\": \"s:Distance\",\n \"@type\": \"s:QuantitativeValue\"\ - \n },\n \"bearing\": {\n \"@type\"\ - : \"s:QuantitativeValue\"\n },\n \"value\": {\n\ - \ \"@id\": \"s:value\"\n },\n \"\ - unitCode\": {\n \"@id\": \"s:unitCode\",\n \ - \ \"@type\": \"@id\"\n },\n \"forecastOffice\"\ - : {\n \"@type\": \"@id\"\n },\n \ - \ \"forecastGridData\": {\n \"@type\": \"@id\"\n \ - \ },\n \"publicZone\": {\n \"@type\"\ - : \"@id\"\n },\n \"county\": {\n \ - \ \"@type\": \"@id\"\n }\n }\n ],\n \"id\"\ - : \"https://api.weather.gov/points/47.6062,-122.3321\",\n \"type\"\ - : \"Feature\",\n \"geometry\": {\n \"type\": \"Point\",\n\ - \ \"coordinates\": [\n -122.3321,\n 47.6062\n\ - \ ]\n },\n \"properties\": {\n \"@id\": \"https://api.weather.gov/points/47.6062,-122.3321\"\ - ,\n \"@type\": \"wx:Point\",\n \"cwa\": \"SEW\",\n \ - \ \"type\": \"land\",\n \"forecastOffice\": \"https://api.weather.gov/offices/SEW\"\ - ,\n \"gridId\": \"SEW\",\n \"gridX\": 125,\n \"\ - gridY\": 68,\n \"forecast\": \"https://api.weather.gov/gridpoints/SEW/125,68/forecast\"\ - ,\n \"forecastHourly\": \"https://api.weather.gov/gridpoints/SEW/125,68/forecast/hourly\"\ - ,\n \"forecastGridData\": \"https://api.weather.gov/gridpoints/SEW/125,68\"\ - ,\n \"observationStations\": \"https://api.weather.gov/gridpoints/SEW/125,68/stations\"\ - ,\n \"relativeLocation\": {\n \"type\": \"Feature\"\ - ,\n \"geometry\": {\n \"type\": \"Point\"\ - ,\n \"coordinates\": [\n -122.3515382,\n\ - \ 47.6193352\n ]\n },\n\ - \ \"properties\": {\n \"city\": \"Seattle\"\ - ,\n \"state\": \"WA\",\n \"distance\"\ - : {\n \"unitCode\": \"wmoUnit:m\",\n \ - \ \"value\": 0\n },\n \"bearing\"\ - : {\n \"unitCode\": \"wmoUnit:degree_(angle)\",\n\ - \ \"value\": 0\n }\n }\n\ - \ },\n \"forecastZone\": \"https://api.weather.gov/zones/forecast/WAZ315\"\ - ,\n \"county\": \"https://api.weather.gov/zones/county/WAC033\"\ - ,\n \"fireWeatherZone\": \"https://api.weather.gov/zones/fire/WAZ654\"\ - ,\n \"timeZone\": \"America/Los_Angeles\",\n \"radarStation\"\ - : \"KATX\",\n \"astronomicalData\": {\n \"sunrise\"\ - : \"2026-10-21T07:37:27-07:00\",\n \"sunset\": \"2026-10-21T18:10:20-07:00\"\ - ,\n \"transit\": \"2026-10-21T12:53:53-07:00\",\n \ - \ \"civilTwilightBegin\": \"2026-10-21T07:06:09-07:00\",\n \ - \ \"civilTwilightEnd\": \"2026-10-21T18:41:38-07:00\",\n \ - \ \"nauticalTwilightBegin\": \"2026-10-21T06:30:18-07:00\",\n\ - \ \"nauticalTwilightEnd\": \"2026-10-21T19:17:28-07:00\"\ - ,\n \"astronomicalTwilightBegin\": \"2026-10-21T05:54:41-07:00\"\ - ,\n \"astronomicalTwilightEnd\": \"2026-10-21T19:53:05-07:00\"\ - \n },\n \"nwr\": {\n \"transmitter\": \"KHB60\"\ - ,\n \"sameCode\": \"053033\",\n \"areaBroadcast\"\ - : \"https://api.weather.gov/radio/KHB60/broadcast\",\n \"\ - pointBroadcast\": \"https://api.weather.gov/points/47.6062,-122.3321/radio\"\ - \n }\n }\n}" - toolUseId: tooluse_MOWg0vh0zvr0fUVv4mJ7mZ + - text: '{"status": 200, "status_text": "OK", "headers": {"server": "nginx/1.28.3", + "content-type": "application/geo+json", "access-control-allow-origin": + "*", "access-control-expose-headers": "X-Correlation-Id, X-Request-Id, + X-Server-Id", "x-request-id": "01a1ab11-3674-7259-adf1-794e6bbc2e1b", + "x-correlation-id": "ef964266", "x-server-id": "vm-cprk-api-ops-app7.ncep.noaa.gov", + "server-timing": "dtTrId;desc=\"60945c8fc6c47bb53425be37b19bc828\", + dtSInfo;desc=\"0\"", "content-encoding": "gzip", "content-length": "1012", + "cache-control": "public, max-age=70757, s-maxage=86400", "expires": + "Fri, 06 Nov 2026 09:36:34 GMT", "date": "Thu, 05 Nov 2026 13:57:17 + GMT", "connection": "keep-alive", "vary": "Accept-Encoding\nAccept,Feature-Flags,Accept-Language", + "x-edge-request-id": "3061809e", "strict-transport-security": "max-age=31536000 + ; includeSubDomains ; preload"}, "body": "{\n \"@context\": [\n \"https://geojson.org/geojson-ld/geojson-context.jsonld\",\n {\n \"@version\": + \"1.1\",\n \"wx\": \"https://api.weather.gov/ontology#\",\n \"s\": + \"https://schema.org/\",\n \"geo\": \"http://www.opengis.net/ont/geosparql#\",\n \"unit\": + \"http://codes.wmo.int/common/unit/\",\n \"@vocab\": \"https://api.weather.gov/ontology#\",\n \"geometry\": + {\n \"@id\": \"s:GeoCoordinates\",\n \"@type\": + \"geo:wktLiteral\"\n },\n \"city\": \"s:addressLocality\",\n \"state\": + \"s:addressRegion\",\n \"distance\": {\n \"@id\": + \"s:Distance\",\n \"@type\": \"s:QuantitativeValue\"\n },\n \"bearing\": + {\n \"@type\": \"s:QuantitativeValue\"\n },\n \"value\": + {\n \"@id\": \"s:value\"\n },\n \"unitCode\": + {\n \"@id\": \"s:unitCode\",\n \"@type\": + \"@id\"\n },\n \"forecastOffice\": {\n \"@type\": + \"@id\"\n },\n \"forecastGridData\": {\n \"@type\": + \"@id\"\n },\n \"publicZone\": {\n \"@type\": + \"@id\"\n },\n \"county\": {\n \"@type\": + \"@id\"\n }\n }\n ],\n \"id\": \"https://api.weather.gov/points/47.6062,-122.3321\",\n \"type\": + \"Feature\",\n \"geometry\": {\n \"type\": \"Point\",\n \"coordinates\": + [\n -122.3321,\n 47.6062\n ]\n },\n \"properties\": + {\n \"@id\": \"https://api.weather.gov/points/47.6062,-122.3321\",\n \"@type\": + \"wx:Point\",\n \"cwa\": \"SEW\",\n \"type\": \"land\",\n \"forecastOffice\": + \"https://api.weather.gov/offices/SEW\",\n \"gridId\": \"SEW\",\n \"gridX\": + 125,\n \"gridY\": 68,\n \"forecast\": \"https://api.weather.gov/gridpoints/SEW/125,68/forecast\",\n \"forecastHourly\": + \"https://api.weather.gov/gridpoints/SEW/125,68/forecast/hourly\",\n \"forecastGridData\": + \"https://api.weather.gov/gridpoints/SEW/125,68\",\n \"observationStations\": + \"https://api.weather.gov/gridpoints/SEW/125,68/stations\",\n \"relativeLocation\": + {\n \"type\": \"Feature\",\n \"geometry\": {\n \"type\": + \"Point\",\n \"coordinates\": [\n -122.3515382,\n 47.6193352\n ]\n },\n \"properties\": + {\n \"city\": \"Seattle\",\n \"state\": + \"WA\",\n \"distance\": {\n \"unitCode\": + \"wmoUnit:m\",\n \"value\": 0\n },\n \"bearing\": + {\n \"unitCode\": \"wmoUnit:degree_(angle)\",\n \"value\": + 0\n }\n }\n },\n \"forecastZone\": + \"https://api.weather.gov/zones/forecast/WAZ315\",\n \"county\": + \"https://api.weather.gov/zones/county/WAC033\",\n \"fireWeatherZone\": + \"https://api.weather.gov/zones/fire/WAZ654\",\n \"timeZone\": + \"America/Los_Angeles\",\n \"radarStation\": \"KATX\",\n \"astronomicalData\": + {\n \"sunrise\": \"2026-11-05T06:59:58-08:00\",\n \"sunset\": + \"2026-11-05T16:45:52-08:00\",\n \"transit\": \"2026-11-05T11:52:55-08:00\",\n \"civilTwilightBegin\": + \"2026-11-05T06:27:28-08:00\",\n \"civilTwilightEnd\": \"2026-11-05T17:18:22-08:00\",\n \"nauticalTwilightBegin\": + \"2026-11-05T05:50:48-08:00\",\n \"nauticalTwilightEnd\": + \"2026-11-05T17:55:02-08:00\",\n \"astronomicalTwilightBegin\": + \"2026-11-05T05:14:54-08:00\",\n \"astronomicalTwilightEnd\": + \"2026-11-05T18:30:56-08:00\"\n },\n \"nwr\": {\n \"transmitter\": + \"KHB60\",\n \"sameCode\": \"053033\",\n \"areaBroadcast\": + \"https://api.weather.gov/radio/KHB60/broadcast\",\n \"pointBroadcast\": + \"https://api.weather.gov/points/47.6062,-122.3321/radio\"\n }\n }\n}"}' + toolUseId: tooluse_0K0PMeVRv6DZT1iOiJLE17 status: success model: us.anthropic.claude-sonnet-4-6 tools: - name: http_request parameters: - type: object properties: method: - type: string - description: HTTP method (GET, POST, PUT, DELETE, etc.) - url: - type: string - description: The URL to send the request to - auth_type: - type: string + description: 'HTTP method (``GET``, ``POST``, ``PUT``, ``DELETE``, + + ``PATCH``, ``HEAD``, ``OPTIONS``).' enum: - - Bearer - - token - - basic - - digest - - jwt - - aws_sig_v4 - - kerberos - - custom - - api_key - description: Authentication type to use - auth_token: + - GET + - POST + - PUT + - DELETE + - PATCH + - HEAD + - OPTIONS type: string - description: Authentication token (if not provided, will check auth_env_var - if configured) - auth_env_var: + url: + description: Absolute URL to request. type: string - description: Name of an environment variable containing the auth token. - The variable must be listed in HTTP_REQUEST_TOKEN_CONFIG with an allowed - domain that matches the request URL. headers: + default: null + description: Optional request headers. type: object - description: HTTP headers as key-value pairs body: + default: null + description: Optional request body as a string. type: string - description: Request body (for POST, PUT, etc.) - verify_ssl: - type: boolean - description: Whether to verify SSL certificates. Disabling may be restricted. - cookie: - type: string - description: Path to cookie file to use for the request - cookie_jar: - type: string - description: Path to cookie jar file to save cookies to - session_config: - type: object - description: Session configuration (cookies, keep-alive, etc) - properties: - keep_alive: - type: boolean - description: Property keep_alive - max_retries: - type: integer - description: Property max_retries - pool_size: - type: integer - description: Property pool_size - cookie_persistence: - type: boolean - description: Property cookie_persistence - required: [] - metrics: - type: boolean - description: Whether to collect request metrics - streaming: - type: boolean - description: Enable streaming response handling - allow_redirects: - type: boolean - description: 'Whether to follow redirects (default: True)' - max_redirects: - type: integer - description: 'Maximum number of redirects to follow (default: 30)' timeout: + default: null + description: 'Optional per-request timeout in seconds. When a client + + is provided, capped at the client''s configured timeout. + + When no client is provided, used as-is.' type: number - description: 'Request timeout in seconds (default: 30). Use a large value - for no timeout.' - convert_to_markdown: - type: boolean - description: 'Convert HTML responses to markdown format (default: False).' - aws_auth: - type: object - description: AWS auth configuration for SigV4 - properties: - service: - type: string - description: Property service - region: - type: string - description: Property region - access_key: - type: string - description: Property access_key - secret_key: - type: string - description: Property secret_key - session_token: - type: string - description: Property session_token - refresh_credentials: - type: boolean - description: Property refresh_credentials - required: [] - basic_auth: - type: object - description: Basic auth credentials - properties: - username: - type: string - description: Property username - password: - type: string - description: Property password - required: - - username - - password - digest_auth: - type: object - description: Digest auth credentials - properties: - username: - type: string - description: Property username - password: - type: string - description: Property password - realm: - type: string - description: Property realm - required: [] - jwt_config: - type: object - description: JWT configuration - properties: - secret: - type: string - description: Property secret - algorithm: - type: string - description: Property algorithm - expiry: - type: integer - description: Property expiry - required: [] required: - method - url + type: object parameters: system: - text: 'You are a weather assistant with HTTP capabilities. You can: @@ -470,16 +242,17 @@ interactions: Always explain the weather conditions clearly and provide context for the forecast.' - inferenceConfig: {} + inferenceConfig: + maxTokens: 128000 stream: true response: content: Got the grid info! Now let me fetch the actual forecast. tool_calls: - name: http_request arguments: '{"method": "GET", "url": "https://api.weather.gov/gridpoints/SEW/125,68/forecast"}' - id: tooluse_hQ7aLgJ3oNcxQEhy2pLZFY + id: tooluse_ZrMW9yi5T45gQACjKswpX7 token_usage: - input_tokens: 3213 + input_tokens: 2974 output_tokens: 102 - request: messages: @@ -487,83 +260,76 @@ interactions: content: What's the weather in Seattle? - role: assistant content: - - text: I'll look up the weather for Seattle! Let me start by getting the grid + - text: Let me look up the weather for Seattle! I'll start by fetching the grid information for Seattle's coordinates. - toolUse: input: method: GET url: https://api.weather.gov/points/47.6062,-122.3321 name: http_request - toolUseId: tooluse_MOWg0vh0zvr0fUVv4mJ7mZ + toolUseId: tooluse_0K0PMeVRv6DZT1iOiJLE17 - role: user content: - toolResult: content: - - text: 'Status Code: 200' - - text: 'Headers: {''Server'': ''nginx/1.28.3'', ''Content-Type'': ''application/geo+json'', - ''Content-Length'': ''1010'', ''Date'': ''Thu, 22 Oct 2026 02:13:48 - GMT''}' - - text: "Body: {\n \"@context\": [\n \"https://geojson.org/geojson-ld/geojson-context.jsonld\"\ - ,\n {\n \"@version\": \"1.1\",\n \"wx\"\ - : \"https://api.weather.gov/ontology#\",\n \"s\": \"https://schema.org/\"\ - ,\n \"geo\": \"http://www.opengis.net/ont/geosparql#\",\n\ - \ \"unit\": \"http://codes.wmo.int/common/unit/\",\n \ - \ \"@vocab\": \"https://api.weather.gov/ontology#\",\n \ - \ \"geometry\": {\n \"@id\": \"s:GeoCoordinates\"\ - ,\n \"@type\": \"geo:wktLiteral\"\n },\n \ - \ \"city\": \"s:addressLocality\",\n \"state\"\ - : \"s:addressRegion\",\n \"distance\": {\n \ - \ \"@id\": \"s:Distance\",\n \"@type\": \"s:QuantitativeValue\"\ - \n },\n \"bearing\": {\n \"@type\"\ - : \"s:QuantitativeValue\"\n },\n \"value\": {\n\ - \ \"@id\": \"s:value\"\n },\n \"\ - unitCode\": {\n \"@id\": \"s:unitCode\",\n \ - \ \"@type\": \"@id\"\n },\n \"forecastOffice\"\ - : {\n \"@type\": \"@id\"\n },\n \ - \ \"forecastGridData\": {\n \"@type\": \"@id\"\n \ - \ },\n \"publicZone\": {\n \"@type\"\ - : \"@id\"\n },\n \"county\": {\n \ - \ \"@type\": \"@id\"\n }\n }\n ],\n \"id\"\ - : \"https://api.weather.gov/points/47.6062,-122.3321\",\n \"type\"\ - : \"Feature\",\n \"geometry\": {\n \"type\": \"Point\",\n\ - \ \"coordinates\": [\n -122.3321,\n 47.6062\n\ - \ ]\n },\n \"properties\": {\n \"@id\": \"https://api.weather.gov/points/47.6062,-122.3321\"\ - ,\n \"@type\": \"wx:Point\",\n \"cwa\": \"SEW\",\n \ - \ \"type\": \"land\",\n \"forecastOffice\": \"https://api.weather.gov/offices/SEW\"\ - ,\n \"gridId\": \"SEW\",\n \"gridX\": 125,\n \"\ - gridY\": 68,\n \"forecast\": \"https://api.weather.gov/gridpoints/SEW/125,68/forecast\"\ - ,\n \"forecastHourly\": \"https://api.weather.gov/gridpoints/SEW/125,68/forecast/hourly\"\ - ,\n \"forecastGridData\": \"https://api.weather.gov/gridpoints/SEW/125,68\"\ - ,\n \"observationStations\": \"https://api.weather.gov/gridpoints/SEW/125,68/stations\"\ - ,\n \"relativeLocation\": {\n \"type\": \"Feature\"\ - ,\n \"geometry\": {\n \"type\": \"Point\"\ - ,\n \"coordinates\": [\n -122.3515382,\n\ - \ 47.6193352\n ]\n },\n\ - \ \"properties\": {\n \"city\": \"Seattle\"\ - ,\n \"state\": \"WA\",\n \"distance\"\ - : {\n \"unitCode\": \"wmoUnit:m\",\n \ - \ \"value\": 0\n },\n \"bearing\"\ - : {\n \"unitCode\": \"wmoUnit:degree_(angle)\",\n\ - \ \"value\": 0\n }\n }\n\ - \ },\n \"forecastZone\": \"https://api.weather.gov/zones/forecast/WAZ315\"\ - ,\n \"county\": \"https://api.weather.gov/zones/county/WAC033\"\ - ,\n \"fireWeatherZone\": \"https://api.weather.gov/zones/fire/WAZ654\"\ - ,\n \"timeZone\": \"America/Los_Angeles\",\n \"radarStation\"\ - : \"KATX\",\n \"astronomicalData\": {\n \"sunrise\"\ - : \"2026-10-21T07:37:27-07:00\",\n \"sunset\": \"2026-10-21T18:10:20-07:00\"\ - ,\n \"transit\": \"2026-10-21T12:53:53-07:00\",\n \ - \ \"civilTwilightBegin\": \"2026-10-21T07:06:09-07:00\",\n \ - \ \"civilTwilightEnd\": \"2026-10-21T18:41:38-07:00\",\n \ - \ \"nauticalTwilightBegin\": \"2026-10-21T06:30:18-07:00\",\n\ - \ \"nauticalTwilightEnd\": \"2026-10-21T19:17:28-07:00\"\ - ,\n \"astronomicalTwilightBegin\": \"2026-10-21T05:54:41-07:00\"\ - ,\n \"astronomicalTwilightEnd\": \"2026-10-21T19:53:05-07:00\"\ - \n },\n \"nwr\": {\n \"transmitter\": \"KHB60\"\ - ,\n \"sameCode\": \"053033\",\n \"areaBroadcast\"\ - : \"https://api.weather.gov/radio/KHB60/broadcast\",\n \"\ - pointBroadcast\": \"https://api.weather.gov/points/47.6062,-122.3321/radio\"\ - \n }\n }\n}" - toolUseId: tooluse_MOWg0vh0zvr0fUVv4mJ7mZ + - text: '{"status": 200, "status_text": "OK", "headers": {"server": "nginx/1.28.3", + "content-type": "application/geo+json", "access-control-allow-origin": + "*", "access-control-expose-headers": "X-Correlation-Id, X-Request-Id, + X-Server-Id", "x-request-id": "01a1ab11-3674-7259-adf1-794e6bbc2e1b", + "x-correlation-id": "ef964266", "x-server-id": "vm-cprk-api-ops-app7.ncep.noaa.gov", + "server-timing": "dtTrId;desc=\"60945c8fc6c47bb53425be37b19bc828\", + dtSInfo;desc=\"0\"", "content-encoding": "gzip", "content-length": "1012", + "cache-control": "public, max-age=70757, s-maxage=86400", "expires": + "Fri, 06 Nov 2026 09:36:34 GMT", "date": "Thu, 05 Nov 2026 13:57:17 + GMT", "connection": "keep-alive", "vary": "Accept-Encoding\nAccept,Feature-Flags,Accept-Language", + "x-edge-request-id": "3061809e", "strict-transport-security": "max-age=31536000 + ; includeSubDomains ; preload"}, "body": "{\n \"@context\": [\n \"https://geojson.org/geojson-ld/geojson-context.jsonld\",\n {\n \"@version\": + \"1.1\",\n \"wx\": \"https://api.weather.gov/ontology#\",\n \"s\": + \"https://schema.org/\",\n \"geo\": \"http://www.opengis.net/ont/geosparql#\",\n \"unit\": + \"http://codes.wmo.int/common/unit/\",\n \"@vocab\": \"https://api.weather.gov/ontology#\",\n \"geometry\": + {\n \"@id\": \"s:GeoCoordinates\",\n \"@type\": + \"geo:wktLiteral\"\n },\n \"city\": \"s:addressLocality\",\n \"state\": + \"s:addressRegion\",\n \"distance\": {\n \"@id\": + \"s:Distance\",\n \"@type\": \"s:QuantitativeValue\"\n },\n \"bearing\": + {\n \"@type\": \"s:QuantitativeValue\"\n },\n \"value\": + {\n \"@id\": \"s:value\"\n },\n \"unitCode\": + {\n \"@id\": \"s:unitCode\",\n \"@type\": + \"@id\"\n },\n \"forecastOffice\": {\n \"@type\": + \"@id\"\n },\n \"forecastGridData\": {\n \"@type\": + \"@id\"\n },\n \"publicZone\": {\n \"@type\": + \"@id\"\n },\n \"county\": {\n \"@type\": + \"@id\"\n }\n }\n ],\n \"id\": \"https://api.weather.gov/points/47.6062,-122.3321\",\n \"type\": + \"Feature\",\n \"geometry\": {\n \"type\": \"Point\",\n \"coordinates\": + [\n -122.3321,\n 47.6062\n ]\n },\n \"properties\": + {\n \"@id\": \"https://api.weather.gov/points/47.6062,-122.3321\",\n \"@type\": + \"wx:Point\",\n \"cwa\": \"SEW\",\n \"type\": \"land\",\n \"forecastOffice\": + \"https://api.weather.gov/offices/SEW\",\n \"gridId\": \"SEW\",\n \"gridX\": + 125,\n \"gridY\": 68,\n \"forecast\": \"https://api.weather.gov/gridpoints/SEW/125,68/forecast\",\n \"forecastHourly\": + \"https://api.weather.gov/gridpoints/SEW/125,68/forecast/hourly\",\n \"forecastGridData\": + \"https://api.weather.gov/gridpoints/SEW/125,68\",\n \"observationStations\": + \"https://api.weather.gov/gridpoints/SEW/125,68/stations\",\n \"relativeLocation\": + {\n \"type\": \"Feature\",\n \"geometry\": {\n \"type\": + \"Point\",\n \"coordinates\": [\n -122.3515382,\n 47.6193352\n ]\n },\n \"properties\": + {\n \"city\": \"Seattle\",\n \"state\": + \"WA\",\n \"distance\": {\n \"unitCode\": + \"wmoUnit:m\",\n \"value\": 0\n },\n \"bearing\": + {\n \"unitCode\": \"wmoUnit:degree_(angle)\",\n \"value\": + 0\n }\n }\n },\n \"forecastZone\": + \"https://api.weather.gov/zones/forecast/WAZ315\",\n \"county\": + \"https://api.weather.gov/zones/county/WAC033\",\n \"fireWeatherZone\": + \"https://api.weather.gov/zones/fire/WAZ654\",\n \"timeZone\": + \"America/Los_Angeles\",\n \"radarStation\": \"KATX\",\n \"astronomicalData\": + {\n \"sunrise\": \"2026-11-05T06:59:58-08:00\",\n \"sunset\": + \"2026-11-05T16:45:52-08:00\",\n \"transit\": \"2026-11-05T11:52:55-08:00\",\n \"civilTwilightBegin\": + \"2026-11-05T06:27:28-08:00\",\n \"civilTwilightEnd\": \"2026-11-05T17:18:22-08:00\",\n \"nauticalTwilightBegin\": + \"2026-11-05T05:50:48-08:00\",\n \"nauticalTwilightEnd\": + \"2026-11-05T17:55:02-08:00\",\n \"astronomicalTwilightBegin\": + \"2026-11-05T05:14:54-08:00\",\n \"astronomicalTwilightEnd\": + \"2026-11-05T18:30:56-08:00\"\n },\n \"nwr\": {\n \"transmitter\": + \"KHB60\",\n \"sameCode\": \"053033\",\n \"areaBroadcast\": + \"https://api.weather.gov/radio/KHB60/broadcast\",\n \"pointBroadcast\": + \"https://api.weather.gov/points/47.6062,-122.3321/radio\"\n }\n }\n}"}' + toolUseId: tooluse_0K0PMeVRv6DZT1iOiJLE17 status: success - role: assistant content: @@ -573,375 +339,211 @@ interactions: method: GET url: https://api.weather.gov/gridpoints/SEW/125,68/forecast name: http_request - toolUseId: tooluse_hQ7aLgJ3oNcxQEhy2pLZFY + toolUseId: tooluse_ZrMW9yi5T45gQACjKswpX7 - role: user content: - toolResult: content: - - text: 'Status Code: 200' - - text: 'Headers: {''Server'': ''nginx/1.28.3'', ''Content-Type'': ''application/geo+json'', - ''Content-Length'': ''1500'', ''Date'': ''Thu, 22 Oct 2026 02:13:50 - GMT''}' - - text: "Body: {\n \"@context\": [\n \"https://geojson.org/geojson-ld/geojson-context.jsonld\"\ - ,\n {\n \"@version\": \"1.1\",\n \"wx\"\ - : \"https://api.weather.gov/ontology#\",\n \"geo\": \"http://www.opengis.net/ont/geosparql#\"\ - ,\n \"unit\": \"http://codes.wmo.int/common/unit/\",\n \ - \ \"@vocab\": \"https://api.weather.gov/ontology#\"\n \ - \ }\n ],\n \"type\": \"Feature\",\n \"geometry\": {\n \ - \ \"type\": \"Polygon\",\n \"coordinates\": [\n \ - \ [\n [\n -122.3017,\n \ - \ 47.5996\n ],\n [\n \ - \ -122.3079,\n 47.6202\n \ - \ ],\n [\n -122.3383,\n \ - \ 47.616\n ],\n [\n \ - \ -122.3321,\n 47.5954\n \ - \ ],\n [\n -122.3017,\n \ - \ 47.5996\n ]\n ]\n ]\n\ - \ },\n \"properties\": {\n \"units\": \"us\",\n \ - \ \"forecastGenerator\": \"BaselineForecastGenerator\",\n \"\ - generatedAt\": \"2026-10-22T01:08:40+00:00\",\n \"updateTime\"\ - : \"2026-10-21T18:26:43+00:00\",\n \"validTimes\": \"2026-10-21T12:00:00+00:00/P7DT13H\"\ - ,\n \"elevation\": {\n \"unitCode\": \"wmoUnit:m\"\ - ,\n \"value\": 73.152\n },\n \"periods\": [\n\ - \ {\n \"number\": 1,\n \"name\"\ - : \"Tonight\",\n \"startTime\": \"2026-10-21T18:00:00-07:00\"\ - ,\n \"endTime\": \"2026-10-22T06:00:00-07:00\",\n \ - \ \"isDaytime\": false,\n \"temperature\"\ - : 48,\n \"temperatureUnit\": \"F\",\n \ - \ \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\"\ - : {\n \"unitCode\": \"wmoUnit:percent\",\n \ - \ \"value\": 1\n },\n \"\ - windSpeed\": \"2 mph\",\n \"windDirection\": \"NNE\"\ - ,\n \"icon\": \"https://api.weather.gov/icons/land/night/sct?size=medium\"\ - ,\n \"shortForecast\": \"Partly Cloudy\",\n \ - \ \"detailedForecast\": \"Partly cloudy, with a low around 48.\ - \ North northeast wind around 2 mph.\"\n },\n \ - \ {\n \"number\": 2,\n \"name\": \"Thursday\"\ - ,\n \"startTime\": \"2026-10-22T06:00:00-07:00\",\n \ - \ \"endTime\": \"2026-10-22T18:00:00-07:00\",\n \ - \ \"isDaytime\": true,\n \"temperature\": 58,\n\ - \ \"temperatureUnit\": \"F\",\n \"temperatureTrend\"\ - : null,\n \"probabilityOfPrecipitation\": {\n \ - \ \"unitCode\": \"wmoUnit:percent\",\n \ - \ \"value\": 19\n },\n \"windSpeed\"\ - : \"1 to 5 mph\",\n \"windDirection\": \"NNE\",\n \ - \ \"icon\": \"https://api.weather.gov/icons/land/day/sct/rain,20?size=medium\"\ - ,\n \"shortForecast\": \"Mostly Sunny then Slight Chance\ - \ Light Rain\",\n \"detailedForecast\": \"A slight chance\ - \ of rain after 5pm. Mostly sunny. High near 58, with temperatures falling\ - \ to around 56 in the afternoon. North northeast wind 1 to 5 mph. Chance\ - \ of precipitation is 20%.\"\n },\n {\n \ - \ \"number\": 3,\n \"name\": \"Thursday Night\"\ - ,\n \"startTime\": \"2026-10-22T18:00:00-07:00\",\n \ - \ \"endTime\": \"2026-10-23T06:00:00-07:00\",\n \ - \ \"isDaytime\": false,\n \"temperature\": 47,\n\ - \ \"temperatureUnit\": \"F\",\n \"temperatureTrend\"\ - : null,\n \"probabilityOfPrecipitation\": {\n \ - \ \"unitCode\": \"wmoUnit:percent\",\n \ - \ \"value\": 13\n },\n \"windSpeed\"\ - : \"3 mph\",\n \"windDirection\": \"NNW\",\n \ - \ \"icon\": \"https://api.weather.gov/icons/land/night/bkn?size=medium\"\ - ,\n \"shortForecast\": \"Mostly Cloudy\",\n \ - \ \"detailedForecast\": \"Mostly cloudy, with a low around 47.\ - \ North northwest wind around 3 mph.\"\n },\n \ - \ {\n \"number\": 4,\n \"name\": \"Friday\"\ - ,\n \"startTime\": \"2026-10-23T06:00:00-07:00\",\n \ - \ \"endTime\": \"2026-10-23T18:00:00-07:00\",\n \ - \ \"isDaytime\": true,\n \"temperature\": 56,\n\ - \ \"temperatureUnit\": \"F\",\n \"temperatureTrend\"\ - : null,\n \"probabilityOfPrecipitation\": {\n \ - \ \"unitCode\": \"wmoUnit:percent\",\n \ - \ \"value\": 1\n },\n \"windSpeed\"\ - : \"3 mph\",\n \"windDirection\": \"NW\",\n \ - \ \"icon\": \"https://api.weather.gov/icons/land/day/sct?size=medium\"\ - ,\n \"shortForecast\": \"Mostly Sunny\",\n \ - \ \"detailedForecast\": \"Mostly sunny, with a high near 56. Northwest\ - \ wind around 3 mph.\"\n },\n {\n \ - \ \"number\": 5,\n \"name\": \"Friday Night\",\n \ - \ \"startTime\": \"2026-10-23T18:00:00-07:00\",\n \ - \ \"endTime\": \"2026-10-24T06:00:00-07:00\",\n \ - \ \"isDaytime\": false,\n \"temperature\": 44,\n\ - \ \"temperatureUnit\": \"F\",\n \"temperatureTrend\"\ - : null,\n \"probabilityOfPrecipitation\": {\n \ - \ \"unitCode\": \"wmoUnit:percent\",\n \ - \ \"value\": 6\n },\n \"windSpeed\"\ - : \"2 mph\",\n \"windDirection\": \"ESE\",\n \ - \ \"icon\": \"https://api.weather.gov/icons/land/night/sct?size=medium\"\ - ,\n \"shortForecast\": \"Partly Cloudy\",\n \ - \ \"detailedForecast\": \"Partly cloudy, with a low around 44.\ - \ East southeast wind around 2 mph.\"\n },\n {\n\ - \ \"number\": 6,\n \"name\": \"Saturday\"\ - ,\n \"startTime\": \"2026-10-24T06:00:00-07:00\",\n \ - \ \"endTime\": \"2026-10-24T18:00:00-07:00\",\n \ - \ \"isDaytime\": true,\n \"temperature\": 54,\n\ - \ \"temperatureUnit\": \"F\",\n \"temperatureTrend\"\ - : null,\n \"probabilityOfPrecipitation\": {\n \ - \ \"unitCode\": \"wmoUnit:percent\",\n \ - \ \"value\": 62\n },\n \"windSpeed\"\ - : \"3 mph\",\n \"windDirection\": \"S\",\n \ - \ \"icon\": \"https://api.weather.gov/icons/land/day/rain,20/rain,60?size=medium\"\ - ,\n \"shortForecast\": \"Light Rain Likely\",\n \ - \ \"detailedForecast\": \"Rain likely after 11am. Mostly cloudy,\ - \ with a high near 54. Chance of precipitation is 60%. New rainfall\ - \ amounts less than a tenth of an inch possible.\"\n },\n\ - \ {\n \"number\": 7,\n \"name\"\ - : \"Saturday Night\",\n \"startTime\": \"2026-10-24T18:00:00-07:00\"\ - ,\n \"endTime\": \"2026-10-25T06:00:00-07:00\",\n \ - \ \"isDaytime\": false,\n \"temperature\"\ - : 46,\n \"temperatureUnit\": \"F\",\n \ - \ \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\"\ - : {\n \"unitCode\": \"wmoUnit:percent\",\n \ - \ \"value\": 62\n },\n \"\ - windSpeed\": \"5 mph\",\n \"windDirection\": \"ENE\"\ - ,\n \"icon\": \"https://api.weather.gov/icons/land/night/rain,60/rain,50?size=medium\"\ - ,\n \"shortForecast\": \"Light Rain Likely\",\n \ - \ \"detailedForecast\": \"Rain likely. Mostly cloudy, with\ - \ a low around 46.\"\n },\n {\n \ - \ \"number\": 8,\n \"name\": \"Sunday\",\n \ - \ \"startTime\": \"2026-10-25T06:00:00-07:00\",\n \ - \ \"endTime\": \"2026-10-25T18:00:00-07:00\",\n \"\ - isDaytime\": true,\n \"temperature\": 57,\n \ - \ \"temperatureUnit\": \"F\",\n \"temperatureTrend\"\ - : null,\n \"probabilityOfPrecipitation\": {\n \ - \ \"unitCode\": \"wmoUnit:percent\",\n \ - \ \"value\": 34\n },\n \"windSpeed\"\ - : \"5 mph\",\n \"windDirection\": \"NE\",\n \ - \ \"icon\": \"https://api.weather.gov/icons/land/day/rain,30?size=medium\"\ - ,\n \"shortForecast\": \"Chance Light Rain\",\n \ - \ \"detailedForecast\": \"A chance of rain. Mostly cloudy,\ - \ with a high near 57.\"\n },\n {\n \ - \ \"number\": 9,\n \"name\": \"Sunday Night\",\n\ - \ \"startTime\": \"2026-10-25T18:00:00-07:00\",\n \ - \ \"endTime\": \"2026-10-26T06:00:00-07:00\",\n \ - \ \"isDaytime\": false,\n \"temperature\": 47,\n\ - \ \"temperatureUnit\": \"F\",\n \"temperatureTrend\"\ - : null,\n \"probabilityOfPrecipitation\": {\n \ - \ \"unitCode\": \"wmoUnit:percent\",\n \ - \ \"value\": 34\n },\n \"windSpeed\"\ - : \"3 mph\",\n \"windDirection\": \"NNE\",\n \ - \ \"icon\": \"https://api.weather.gov/icons/land/night/rain,30?size=medium\"\ - ,\n \"shortForecast\": \"Chance Light Rain\",\n \ - \ \"detailedForecast\": \"A chance of rain. Mostly cloudy,\ - \ with a low around 47.\"\n },\n {\n \ - \ \"number\": 10,\n \"name\": \"Monday\",\n \ - \ \"startTime\": \"2026-10-26T06:00:00-07:00\",\n \ - \ \"endTime\": \"2026-10-26T18:00:00-07:00\",\n \ - \ \"isDaytime\": true,\n \"temperature\": 57,\n \ - \ \"temperatureUnit\": \"F\",\n \"temperatureTrend\"\ - : null,\n \"probabilityOfPrecipitation\": {\n \ - \ \"unitCode\": \"wmoUnit:percent\",\n \ - \ \"value\": 28\n },\n \"windSpeed\"\ - : \"3 mph\",\n \"windDirection\": \"N\",\n \ - \ \"icon\": \"https://api.weather.gov/icons/land/day/rain,20/rain,30?size=medium\"\ - ,\n \"shortForecast\": \"Chance Light Rain\",\n \ - \ \"detailedForecast\": \"A chance of rain. Partly sunny,\ - \ with a high near 57.\"\n },\n {\n \ - \ \"number\": 11,\n \"name\": \"Monday Night\",\n\ - \ \"startTime\": \"2026-10-26T18:00:00-07:00\",\n \ - \ \"endTime\": \"2026-10-27T06:00:00-07:00\",\n \ - \ \"isDaytime\": false,\n \"temperature\": 46,\n\ - \ \"temperatureUnit\": \"F\",\n \"temperatureTrend\"\ - : null,\n \"probabilityOfPrecipitation\": {\n \ - \ \"unitCode\": \"wmoUnit:percent\",\n \ - \ \"value\": 28\n },\n \"windSpeed\"\ - : \"3 mph\",\n \"windDirection\": \"ENE\",\n \ - \ \"icon\": \"https://api.weather.gov/icons/land/night/rain,30/rain,20?size=medium\"\ - ,\n \"shortForecast\": \"Chance Light Rain\",\n \ - \ \"detailedForecast\": \"A chance of rain. Mostly cloudy,\ - \ with a low around 46.\"\n },\n {\n \ - \ \"number\": 12,\n \"name\": \"Tuesday\",\n \ - \ \"startTime\": \"2026-10-27T06:00:00-07:00\",\n \ - \ \"endTime\": \"2026-10-27T18:00:00-07:00\",\n \ - \ \"isDaytime\": true,\n \"temperature\": 56,\n\ - \ \"temperatureUnit\": \"F\",\n \"temperatureTrend\"\ - : null,\n \"probabilityOfPrecipitation\": {\n \ - \ \"unitCode\": \"wmoUnit:percent\",\n \ - \ \"value\": 23\n },\n \"windSpeed\"\ - : \"3 mph\",\n \"windDirection\": \"SW\",\n \ - \ \"icon\": \"https://api.weather.gov/icons/land/day/rain,20?size=medium\"\ - ,\n \"shortForecast\": \"Slight Chance Light Rain\",\n\ - \ \"detailedForecast\": \"A slight chance of rain. Partly\ - \ sunny, with a high near 56.\"\n },\n {\n \ - \ \"number\": 13,\n \"name\": \"Tuesday Night\"\ - ,\n \"startTime\": \"2026-10-27T18:00:00-07:00\",\n \ - \ \"endTime\": \"2026-10-28T06:00:00-07:00\",\n \ - \ \"isDaytime\": false,\n \"temperature\": 45,\n\ - \ \"temperatureUnit\": \"F\",\n \"temperatureTrend\"\ - : null,\n \"probabilityOfPrecipitation\": {\n \ - \ \"unitCode\": \"wmoUnit:percent\",\n \ - \ \"value\": 23\n },\n \"windSpeed\"\ - : \"3 mph\",\n \"windDirection\": \"SSW\",\n \ - \ \"icon\": \"https://api.weather.gov/icons/land/night/rain,20?size=medium\"\ - ,\n \"shortForecast\": \"Slight Chance Light Rain\",\n\ - \ \"detailedForecast\": \"A slight chance of rain. Partly\ - \ cloudy, with a low around 45.\"\n },\n {\n \ - \ \"number\": 14,\n \"name\": \"Wednesday\"\ - ,\n \"startTime\": \"2026-10-28T06:00:00-07:00\",\n \ - \ \"endTime\": \"2026-10-28T18:00:00-07:00\",\n \ - \ \"isDaytime\": true,\n \"temperature\": 55,\n\ - \ \"temperatureUnit\": \"F\",\n \"temperatureTrend\"\ - : null,\n \"probabilityOfPrecipitation\": {\n \ - \ \"unitCode\": \"wmoUnit:percent\",\n \ - \ \"value\": 20\n },\n \"windSpeed\"\ - : \"5 mph\",\n \"windDirection\": \"NNE\",\n \ - \ \"icon\": \"https://api.weather.gov/icons/land/day/rain,20?size=medium\"\ - ,\n \"shortForecast\": \"Slight Chance Light Rain\",\n\ - \ \"detailedForecast\": \"A slight chance of rain. Mostly\ - \ sunny, with a high near 55.\"\n }\n ]\n }\n}" - toolUseId: tooluse_hQ7aLgJ3oNcxQEhy2pLZFY + - text: '{"status": 200, "status_text": "OK", "headers": {"server": "nginx/1.28.3", + "content-type": "application/geo+json", "last-modified": "Thu, 05 Nov + 2026 06:26:49 GMT", "access-control-allow-origin": "*", "access-control-expose-headers": + "X-Correlation-Id, X-Request-Id, X-Server-Id", "x-request-id": "01a1abd0-bb7c-7272-85cd-ccecd6e97121", + "x-correlation-id": "f49bdaa8", "x-server-id": "vm-cprk-api-ops-app14.ncep.noaa.gov", + "etag": "W/\"1793860011:dtagent10337260504112723F6xZ:dtagent10337260504112723F6xZ\"", + "server-timing": "dtTrId;desc=\"0f5efddfbabb1763576faabf607c16f9\", + dtSInfo;desc=\"0\"", "content-encoding": "gzip", "content-length": "1588", + "cache-control": "public, max-age=507, s-maxage=3600", "expires": "Thu, + 05 Nov 2026 14:05:45 GMT", "date": "Thu, 05 Nov 2026 13:57:18 GMT", + "connection": "keep-alive", "vary": "Accept-Encoding\nAccept,Feature-Flags,Accept-Language", + "x-edge-request-id": "2f85403a", "strict-transport-security": "max-age=31536000 + ; includeSubDomains ; preload"}, "body": "{\n \"@context\": [\n \"https://geojson.org/geojson-ld/geojson-context.jsonld\",\n {\n \"@version\": + \"1.1\",\n \"wx\": \"https://api.weather.gov/ontology#\",\n \"geo\": + \"http://www.opengis.net/ont/geosparql#\",\n \"unit\": \"http://codes.wmo.int/common/unit/\",\n \"@vocab\": + \"https://api.weather.gov/ontology#\"\n }\n ],\n \"type\": + \"Feature\",\n \"geometry\": {\n \"type\": \"Polygon\",\n \"coordinates\": + [\n [\n [\n -122.3017,\n 47.5996\n ],\n [\n -122.3079,\n 47.6202\n ],\n [\n -122.3383,\n 47.616\n ],\n [\n -122.3321,\n 47.5954\n ],\n [\n -122.3017,\n 47.5996\n ]\n ]\n ]\n },\n \"properties\": + {\n \"units\": \"us\",\n \"forecastGenerator\": \"BaselineForecastGenerator\",\n \"generatedAt\": + \"2026-11-05T13:05:45+00:00\",\n \"updateTime\": \"2026-11-05T06:26:51+00:00\",\n \"validTimes\": + \"2026-11-05T00:00:00+00:00/P8DT1H\",\n \"elevation\": {\n \"unitCode\": + \"wmoUnit:m\",\n \"value\": 73.152\n },\n \"periods\": + [\n {\n \"number\": 1,\n \"name\": + \"Overnight\",\n \"startTime\": \"2026-11-05T05:00:00-08:00\",\n \"endTime\": + \"2026-11-05T06:00:00-08:00\",\n \"isDaytime\": false,\n \"temperature\": + 50,\n \"temperatureUnit\": \"F\",\n \"temperatureTrend\": + null,\n \"probabilityOfPrecipitation\": {\n \"unitCode\": + \"wmoUnit:percent\",\n \"value\": 4\n },\n \"windSpeed\": + \"6 mph\",\n \"windDirection\": \"S\",\n \"icon\": + \"https://api.weather.gov/icons/land/night/sct?size=medium\",\n \"shortForecast\": + \"Partly Cloudy\",\n \"detailedForecast\": \"Partly cloudy, + with a low around 50. South wind around 6 mph.\"\n },\n {\n \"number\": + 2,\n \"name\": \"Thursday\",\n \"startTime\": + \"2026-11-05T06:00:00-08:00\",\n \"endTime\": \"2026-11-05T18:00:00-08:00\",\n \"isDaytime\": + true,\n \"temperature\": 56,\n \"temperatureUnit\": + \"F\",\n \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\": + {\n \"unitCode\": \"wmoUnit:percent\",\n \"value\": + 4\n },\n \"windSpeed\": \"3 to 9 mph\",\n \"windDirection\": + \"S\",\n \"icon\": \"https://api.weather.gov/icons/land/day/bkn?size=medium\",\n \"shortForecast\": + \"Partly Sunny\",\n \"detailedForecast\": \"Partly sunny. + High near 56, with temperatures falling to around 54 in the afternoon. + South wind 3 to 9 mph.\"\n },\n {\n \"number\": + 3,\n \"name\": \"Thursday Night\",\n \"startTime\": + \"2026-11-05T18:00:00-08:00\",\n \"endTime\": \"2026-11-06T06:00:00-08:00\",\n \"isDaytime\": + false,\n \"temperature\": 47,\n \"temperatureUnit\": + \"F\",\n \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\": + {\n \"unitCode\": \"wmoUnit:percent\",\n \"value\": + 39\n },\n \"windSpeed\": \"7 mph\",\n \"windDirection\": + \"SSE\",\n \"icon\": \"https://api.weather.gov/icons/land/night/bkn/rain,40?size=medium\",\n \"shortForecast\": + \"Mostly Cloudy then Chance Light Rain\",\n \"detailedForecast\": + \"A chance of rain after 4am. Mostly cloudy. Low around 47, with temperatures + rising to around 49 overnight. South southeast wind around 7 mph. Chance + of precipitation is 40%. New rainfall amounts less than a tenth of an + inch possible.\"\n },\n {\n \"number\": + 4,\n \"name\": \"Friday\",\n \"startTime\": + \"2026-11-06T06:00:00-08:00\",\n \"endTime\": \"2026-11-06T18:00:00-08:00\",\n \"isDaytime\": + true,\n \"temperature\": 55,\n \"temperatureUnit\": + \"F\",\n \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\": + {\n \"unitCode\": \"wmoUnit:percent\",\n \"value\": + 80\n },\n \"windSpeed\": \"8 mph\",\n \"windDirection\": + \"S\",\n \"icon\": \"https://api.weather.gov/icons/land/day/rain,20/rain,80?size=medium\",\n \"shortForecast\": + \"Light Rain\",\n \"detailedForecast\": \"Rain. Cloudy, + with a high near 55. South wind around 8 mph. Chance of precipitation + is 80%. New rainfall amounts between a tenth and quarter of an inch + possible.\"\n },\n {\n \"number\": + 5,\n \"name\": \"Friday Night\",\n \"startTime\": + \"2026-11-06T18:00:00-08:00\",\n \"endTime\": \"2026-11-07T06:00:00-08:00\",\n \"isDaytime\": + false,\n \"temperature\": 51,\n \"temperatureUnit\": + \"F\",\n \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\": + {\n \"unitCode\": \"wmoUnit:percent\",\n \"value\": + 80\n },\n \"windSpeed\": \"2 to 8 mph\",\n \"windDirection\": + \"SSE\",\n \"icon\": \"https://api.weather.gov/icons/land/night/rain,80/rain,60?size=medium\",\n \"shortForecast\": + \"Light Rain\",\n \"detailedForecast\": \"Rain. Cloudy, + with a low around 51. South southeast wind 2 to 8 mph. Chance of precipitation + is 80%. New rainfall amounts less than a tenth of an inch possible.\"\n },\n {\n \"number\": + 6,\n \"name\": \"Saturday\",\n \"startTime\": + \"2026-11-07T06:00:00-08:00\",\n \"endTime\": \"2026-11-07T18:00:00-08:00\",\n \"isDaytime\": + true,\n \"temperature\": 63,\n \"temperatureUnit\": + \"F\",\n \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\": + {\n \"unitCode\": \"wmoUnit:percent\",\n \"value\": + 61\n },\n \"windSpeed\": \"2 to 6 mph\",\n \"windDirection\": + \"SSE\",\n \"icon\": \"https://api.weather.gov/icons/land/day/rain,40/rain,60?size=medium\",\n \"shortForecast\": + \"Light Rain Likely\",\n \"detailedForecast\": \"Rain + likely. Mostly cloudy, with a high near 63. Chance of precipitation + is 60%. New rainfall amounts less than a tenth of an inch possible.\"\n },\n {\n \"number\": + 7,\n \"name\": \"Saturday Night\",\n \"startTime\": + \"2026-11-07T18:00:00-08:00\",\n \"endTime\": \"2026-11-08T06:00:00-08:00\",\n \"isDaytime\": + false,\n \"temperature\": 51,\n \"temperatureUnit\": + \"F\",\n \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\": + {\n \"unitCode\": \"wmoUnit:percent\",\n \"value\": + 96\n },\n \"windSpeed\": \"6 to 20 mph\",\n \"windDirection\": + \"SSW\",\n \"icon\": \"https://api.weather.gov/icons/land/night/rain,100?size=medium\",\n \"shortForecast\": + \"Light Rain\",\n \"detailedForecast\": \"Rain. Mostly + cloudy, with a low around 51.\"\n },\n {\n \"number\": + 8,\n \"name\": \"Sunday\",\n \"startTime\": + \"2026-11-08T06:00:00-08:00\",\n \"endTime\": \"2026-11-08T18:00:00-08:00\",\n \"isDaytime\": + true,\n \"temperature\": 55,\n \"temperatureUnit\": + \"F\",\n \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\": + {\n \"unitCode\": \"wmoUnit:percent\",\n \"value\": + 50\n },\n \"windSpeed\": \"5 to 17 mph\",\n \"windDirection\": + \"SSW\",\n \"icon\": \"https://api.weather.gov/icons/land/day/rain,50/rain,20?size=medium\",\n \"shortForecast\": + \"Chance Light Rain\",\n \"detailedForecast\": \"A chance + of rain before 4pm. Partly sunny, with a high near 55.\"\n },\n {\n \"number\": + 9,\n \"name\": \"Sunday Night\",\n \"startTime\": + \"2026-11-08T18:00:00-08:00\",\n \"endTime\": \"2026-11-09T06:00:00-08:00\",\n \"isDaytime\": + false,\n \"temperature\": 44,\n \"temperatureUnit\": + \"F\",\n \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\": + {\n \"unitCode\": \"wmoUnit:percent\",\n \"value\": + 9\n },\n \"windSpeed\": \"5 mph\",\n \"windDirection\": + \"SE\",\n \"icon\": \"https://api.weather.gov/icons/land/night/sct?size=medium\",\n \"shortForecast\": + \"Partly Cloudy\",\n \"detailedForecast\": \"Partly cloudy, + with a low around 44.\"\n },\n {\n \"number\": + 10,\n \"name\": \"Monday\",\n \"startTime\": + \"2026-11-09T06:00:00-08:00\",\n \"endTime\": \"2026-11-09T18:00:00-08:00\",\n \"isDaytime\": + true,\n \"temperature\": 55,\n \"temperatureUnit\": + \"F\",\n \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\": + {\n \"unitCode\": \"wmoUnit:percent\",\n \"value\": + 54\n },\n \"windSpeed\": \"3 mph\",\n \"windDirection\": + \"SE\",\n \"icon\": \"https://api.weather.gov/icons/land/day/rain,20/rain,50?size=medium\",\n \"shortForecast\": + \"Chance Light Rain\",\n \"detailedForecast\": \"A chance + of rain after 10am. Mostly cloudy, with a high near 55.\"\n },\n {\n \"number\": + 11,\n \"name\": \"Monday Night\",\n \"startTime\": + \"2026-11-09T18:00:00-08:00\",\n \"endTime\": \"2026-11-10T06:00:00-08:00\",\n \"isDaytime\": + false,\n \"temperature\": 50,\n \"temperatureUnit\": + \"F\",\n \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\": + {\n \"unitCode\": \"wmoUnit:percent\",\n \"value\": + 75\n },\n \"windSpeed\": \"3 to 13 mph\",\n \"windDirection\": + \"SSE\",\n \"icon\": \"https://api.weather.gov/icons/land/night/rain,60/rain,80?size=medium\",\n \"shortForecast\": + \"Light Rain\",\n \"detailedForecast\": \"Rain. Mostly + cloudy, with a low around 50.\"\n },\n {\n \"number\": + 12,\n \"name\": \"Tuesday\",\n \"startTime\": + \"2026-11-10T06:00:00-08:00\",\n \"endTime\": \"2026-11-10T18:00:00-08:00\",\n \"isDaytime\": + true,\n \"temperature\": 58,\n \"temperatureUnit\": + \"F\",\n \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\": + {\n \"unitCode\": \"wmoUnit:percent\",\n \"value\": + 75\n },\n \"windSpeed\": \"8 to 14 mph\",\n \"windDirection\": + \"S\",\n \"icon\": \"https://api.weather.gov/icons/land/day/rain,80/rain,70?size=medium\",\n \"shortForecast\": + \"Light Rain\",\n \"detailedForecast\": \"Rain. Mostly + cloudy, with a high near 58.\"\n },\n {\n \"number\": + 13,\n \"name\": \"Tuesday Night\",\n \"startTime\": + \"2026-11-10T18:00:00-08:00\",\n \"endTime\": \"2026-11-11T06:00:00-08:00\",\n \"isDaytime\": + false,\n \"temperature\": 52,\n \"temperatureUnit\": + \"F\",\n \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\": + {\n \"unitCode\": \"wmoUnit:percent\",\n \"value\": + 71\n },\n \"windSpeed\": \"8 to 13 mph\",\n \"windDirection\": + \"S\",\n \"icon\": \"https://api.weather.gov/icons/land/night/rain,70/rain,60?size=medium\",\n \"shortForecast\": + \"Light Rain Likely\",\n \"detailedForecast\": \"Rain + likely. Mostly cloudy, with a low around 52.\"\n },\n {\n \"number\": + 14,\n \"name\": \"Veterans Day\",\n \"startTime\": + \"2026-11-11T06:00:00-08:00\",\n \"endTime\": \"2026-11-11T18:00:00-08:00\",\n \"isDaytime\": + true,\n \"temperature\": 60,\n \"temperatureUnit\": + \"F\",\n \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\": + {\n \"unitCode\": \"wmoUnit:percent\",\n \"value\": + 56\n },\n \"windSpeed\": \"6 to 10 mph\",\n \"windDirection\": + \"S\",\n \"icon\": \"https://api.weather.gov/icons/land/day/rain,60/rain,50?size=medium\",\n \"shortForecast\": + \"Light Rain Likely\",\n \"detailedForecast\": \"Rain + likely. Mostly cloudy, with a high near 60.\"\n }\n ]\n }\n}"}' + toolUseId: tooluse_ZrMW9yi5T45gQACjKswpX7 status: success model: us.anthropic.claude-sonnet-4-6 tools: - name: http_request parameters: - type: object properties: method: - type: string - description: HTTP method (GET, POST, PUT, DELETE, etc.) - url: - type: string - description: The URL to send the request to - auth_type: - type: string + description: 'HTTP method (``GET``, ``POST``, ``PUT``, ``DELETE``, + + ``PATCH``, ``HEAD``, ``OPTIONS``).' enum: - - Bearer - - token - - basic - - digest - - jwt - - aws_sig_v4 - - kerberos - - custom - - api_key - description: Authentication type to use - auth_token: + - GET + - POST + - PUT + - DELETE + - PATCH + - HEAD + - OPTIONS type: string - description: Authentication token (if not provided, will check auth_env_var - if configured) - auth_env_var: + url: + description: Absolute URL to request. type: string - description: Name of an environment variable containing the auth token. - The variable must be listed in HTTP_REQUEST_TOKEN_CONFIG with an allowed - domain that matches the request URL. headers: + default: null + description: Optional request headers. type: object - description: HTTP headers as key-value pairs body: + default: null + description: Optional request body as a string. type: string - description: Request body (for POST, PUT, etc.) - verify_ssl: - type: boolean - description: Whether to verify SSL certificates. Disabling may be restricted. - cookie: - type: string - description: Path to cookie file to use for the request - cookie_jar: - type: string - description: Path to cookie jar file to save cookies to - session_config: - type: object - description: Session configuration (cookies, keep-alive, etc) - properties: - keep_alive: - type: boolean - description: Property keep_alive - max_retries: - type: integer - description: Property max_retries - pool_size: - type: integer - description: Property pool_size - cookie_persistence: - type: boolean - description: Property cookie_persistence - required: [] - metrics: - type: boolean - description: Whether to collect request metrics - streaming: - type: boolean - description: Enable streaming response handling - allow_redirects: - type: boolean - description: 'Whether to follow redirects (default: True)' - max_redirects: - type: integer - description: 'Maximum number of redirects to follow (default: 30)' timeout: + default: null + description: 'Optional per-request timeout in seconds. When a client + + is provided, capped at the client''s configured timeout. + + When no client is provided, used as-is.' type: number - description: 'Request timeout in seconds (default: 30). Use a large value - for no timeout.' - convert_to_markdown: - type: boolean - description: 'Convert HTML responses to markdown format (default: False).' - aws_auth: - type: object - description: AWS auth configuration for SigV4 - properties: - service: - type: string - description: Property service - region: - type: string - description: Property region - access_key: - type: string - description: Property access_key - secret_key: - type: string - description: Property secret_key - session_token: - type: string - description: Property session_token - refresh_credentials: - type: boolean - description: Property refresh_credentials - required: [] - basic_auth: - type: object - description: Basic auth credentials - properties: - username: - type: string - description: Property username - password: - type: string - description: Property password - required: - - username - - password - digest_auth: - type: object - description: Digest auth credentials - properties: - username: - type: string - description: Property username - password: - type: string - description: Property password - realm: - type: string - description: Property realm - required: [] - jwt_config: - type: object - description: JWT configuration - properties: - secret: - type: string - description: Property secret - algorithm: - type: string - description: Property algorithm - expiry: - type: integer - description: Property expiry - required: [] required: - method - url + type: object parameters: system: - text: 'You are a weather assistant with HTTP capabilities. You can: @@ -973,74 +575,73 @@ interactions: Always explain the weather conditions clearly and provide context for the forecast.' - inferenceConfig: {} + inferenceConfig: + maxTokens: 128000 stream: true response: - content: 'Here''s the weather forecast for **Seattle, WA** 🌲☁️ + content: 'Here''s the weather forecast for **Seattle, WA** 🌧️ --- - ## 🌙 Tonight + ### 🌤️ Today (Thursday) + + - **Conditions:** Partly Sunny + + - **High:** 56°F | **Overnight Low:** 50°F - - **Partly Cloudy** | Low: **48°F** + - **Wind:** South 3–9 mph - - 💨 Wind: NNE at 2 mph | 🌧️ Precip chance: ~1% + - **Precipitation:** Very low chance (4%) --- - ## 📅 7-Day Forecast + ### 📅 7-Day Forecast - | Day | Conditions | High/Low | Rain Chance | Wind | + | Day | Conditions | High | Low | 🌧️ Rain Chance | - |-----|-----------|----------|-------------|------| + |---|---|---|---|---| - | **Thursday** | ⛅ Mostly Sunny → Slight Chance of Rain | 58°F / 47°F | 20% - | NNE 1–5 mph | + | **Thursday Night** | Mostly Cloudy → Light Rain Late | — | 47°F | 40% | - | **Friday** | ☀️ Mostly Sunny | 56°F / 44°F | <10% | NW 3 mph | + | **Friday** | 🌧️ Rain | 55°F | 51°F | **80%** | - | **Saturday** | 🌧️ Rain Likely | 54°F / 46°F | **60%** | S 3 mph | + | **Saturday** | 🌧️ Rain Likely | 63°F | 51°F | 60% | - | **Sunday** | 🌦️ Chance of Light Rain | 57°F / 47°F | 34% | NE 5 mph | + | **Saturday Night** | 🌧️ Rain | — | 51°F | **96%** | - | **Monday** | 🌦️ Chance of Light Rain | 57°F / 46°F | 28% | N 3 mph | + | **Sunday** | Chance of Rain | 55°F | 44°F | 50% | - | **Tuesday** | 🌤️ Slight Chance of Light Rain | 56°F / 45°F | 23% | SW 3 mph - | + | **Monday** | Chance of Rain | 55°F | 50°F | 54% | - | **Wednesday** | ☀️ Mostly Sunny, Slight Chance of Rain | 55°F / — | 20% | - NNE 5 mph | + | **Tuesday** | 🌧️ Rain | 58°F | 52°F | **75%** | --- - ### 🔍 Key Takeaways: + ### 🔑 Key Takeaways - - **Tonight through Friday** looks pleasant — relatively dry with temps in the - mid-to-upper 50s during the day. + - **Today is your best day** this week — enjoy the partly sunny skies while + they last! - - **Saturday** is the wet day to watch out for, with a **60% chance of rain** - — classic Seattle fall weather! ☔ + - **Rain moves in Thursday night** and sticks around through most of next week + — very typical Seattle fall weather. 🍂 - - The **weekend into next week** stays mostly cloudy with on-and-off light rain - chances. + - **Saturday night** has the highest rain chance at **96%**, so plan accordingly. - - Temperatures are mild for late October, ranging from the **mid-40s at night** - to the **upper 50s during the day**. + - Temperatures will remain mild, mostly in the **mid-50s to low 60s°F**. - Typical autumn conditions for Seattle — pack a light jacket and keep an umbrella - handy for the weekend! 🧥' + Don''t forget your umbrella if you''re heading out Friday through Tuesday! ☂️' tool_calls: null token_usage: - input_tokens: 7251 - output_tokens: 559 + input_tokens: 8151 + output_tokens: 450 tool_executions: - name: http_request arguments: @@ -1050,64 +651,56 @@ tool_executions: result: status: success content: - - text: 'Status Code: 200' - - text: 'Headers: {''Server'': ''nginx/1.28.3'', ''Content-Type'': ''application/geo+json'', - ''Content-Length'': ''1010'', ''Date'': ''Thu, 22 Oct 2026 02:13:48 GMT''}' - - text: "Body: {\n \"@context\": [\n \"https://geojson.org/geojson-ld/geojson-context.jsonld\"\ - ,\n {\n \"@version\": \"1.1\",\n \"wx\": \"https://api.weather.gov/ontology#\"\ - ,\n \"s\": \"https://schema.org/\",\n \"geo\": \"http://www.opengis.net/ont/geosparql#\"\ - ,\n \"unit\": \"http://codes.wmo.int/common/unit/\",\n \ - \ \"@vocab\": \"https://api.weather.gov/ontology#\",\n \"geometry\"\ - : {\n \"@id\": \"s:GeoCoordinates\",\n \"@type\"\ - : \"geo:wktLiteral\"\n },\n \"city\": \"s:addressLocality\"\ - ,\n \"state\": \"s:addressRegion\",\n \"distance\":\ - \ {\n \"@id\": \"s:Distance\",\n \"@type\":\ - \ \"s:QuantitativeValue\"\n },\n \"bearing\": {\n \ - \ \"@type\": \"s:QuantitativeValue\"\n },\n \ - \ \"value\": {\n \"@id\": \"s:value\"\n },\n\ - \ \"unitCode\": {\n \"@id\": \"s:unitCode\",\n \ - \ \"@type\": \"@id\"\n },\n \"forecastOffice\"\ - : {\n \"@type\": \"@id\"\n },\n \"forecastGridData\"\ - : {\n \"@type\": \"@id\"\n },\n \"publicZone\"\ - : {\n \"@type\": \"@id\"\n },\n \"county\"\ - : {\n \"@type\": \"@id\"\n }\n }\n ],\n\ - \ \"id\": \"https://api.weather.gov/points/47.6062,-122.3321\",\n \"\ - type\": \"Feature\",\n \"geometry\": {\n \"type\": \"Point\",\n\ - \ \"coordinates\": [\n -122.3321,\n 47.6062\n\ - \ ]\n },\n \"properties\": {\n \"@id\": \"https://api.weather.gov/points/47.6062,-122.3321\"\ - ,\n \"@type\": \"wx:Point\",\n \"cwa\": \"SEW\",\n \"\ - type\": \"land\",\n \"forecastOffice\": \"https://api.weather.gov/offices/SEW\"\ - ,\n \"gridId\": \"SEW\",\n \"gridX\": 125,\n \"gridY\"\ - : 68,\n \"forecast\": \"https://api.weather.gov/gridpoints/SEW/125,68/forecast\"\ - ,\n \"forecastHourly\": \"https://api.weather.gov/gridpoints/SEW/125,68/forecast/hourly\"\ - ,\n \"forecastGridData\": \"https://api.weather.gov/gridpoints/SEW/125,68\"\ - ,\n \"observationStations\": \"https://api.weather.gov/gridpoints/SEW/125,68/stations\"\ - ,\n \"relativeLocation\": {\n \"type\": \"Feature\",\n \ - \ \"geometry\": {\n \"type\": \"Point\",\n \ - \ \"coordinates\": [\n -122.3515382,\n \ - \ 47.6193352\n ]\n },\n \"\ - properties\": {\n \"city\": \"Seattle\",\n \"\ - state\": \"WA\",\n \"distance\": {\n \"\ - unitCode\": \"wmoUnit:m\",\n \"value\": 0\n \ - \ },\n \"bearing\": {\n \"unitCode\"\ - : \"wmoUnit:degree_(angle)\",\n \"value\": 0\n \ - \ }\n }\n },\n \"forecastZone\": \"https://api.weather.gov/zones/forecast/WAZ315\"\ - ,\n \"county\": \"https://api.weather.gov/zones/county/WAC033\",\n\ - \ \"fireWeatherZone\": \"https://api.weather.gov/zones/fire/WAZ654\"\ - ,\n \"timeZone\": \"America/Los_Angeles\",\n \"radarStation\"\ - : \"KATX\",\n \"astronomicalData\": {\n \"sunrise\": \"\ - 2026-10-21T07:37:27-07:00\",\n \"sunset\": \"2026-10-21T18:10:20-07:00\"\ - ,\n \"transit\": \"2026-10-21T12:53:53-07:00\",\n \"\ - civilTwilightBegin\": \"2026-10-21T07:06:09-07:00\",\n \"civilTwilightEnd\"\ - : \"2026-10-21T18:41:38-07:00\",\n \"nauticalTwilightBegin\": \"\ - 2026-10-21T06:30:18-07:00\",\n \"nauticalTwilightEnd\": \"2026-10-21T19:17:28-07:00\"\ - ,\n \"astronomicalTwilightBegin\": \"2026-10-21T05:54:41-07:00\"\ - ,\n \"astronomicalTwilightEnd\": \"2026-10-21T19:53:05-07:00\"\n\ - \ },\n \"nwr\": {\n \"transmitter\": \"KHB60\",\n\ - \ \"sameCode\": \"053033\",\n \"areaBroadcast\": \"\ - https://api.weather.gov/radio/KHB60/broadcast\",\n \"pointBroadcast\"\ - : \"https://api.weather.gov/points/47.6062,-122.3321/radio\"\n }\n\ - \ }\n}" + - text: '{"status": 200, "status_text": "OK", "headers": {"server": "nginx/1.28.3", + "content-type": "application/geo+json", "access-control-allow-origin": "*", + "access-control-expose-headers": "X-Correlation-Id, X-Request-Id, X-Server-Id", + "x-request-id": "01a1ab11-3674-7259-adf1-794e6bbc2e1b", "x-correlation-id": + "ef964266", "x-server-id": "vm-cprk-api-ops-app7.ncep.noaa.gov", "server-timing": + "dtTrId;desc=\"60945c8fc6c47bb53425be37b19bc828\", dtSInfo;desc=\"0\"", "content-encoding": + "gzip", "content-length": "1012", "cache-control": "public, max-age=70757, + s-maxage=86400", "expires": "Fri, 06 Nov 2026 09:36:34 GMT", "date": "Thu, + 05 Nov 2026 13:57:17 GMT", "connection": "keep-alive", "vary": "Accept-Encoding\nAccept,Feature-Flags,Accept-Language", + "x-edge-request-id": "3061809e", "strict-transport-security": "max-age=31536000 + ; includeSubDomains ; preload"}, "body": "{\n \"@context\": [\n \"https://geojson.org/geojson-ld/geojson-context.jsonld\",\n {\n \"@version\": + \"1.1\",\n \"wx\": \"https://api.weather.gov/ontology#\",\n \"s\": + \"https://schema.org/\",\n \"geo\": \"http://www.opengis.net/ont/geosparql#\",\n \"unit\": + \"http://codes.wmo.int/common/unit/\",\n \"@vocab\": \"https://api.weather.gov/ontology#\",\n \"geometry\": + {\n \"@id\": \"s:GeoCoordinates\",\n \"@type\": + \"geo:wktLiteral\"\n },\n \"city\": \"s:addressLocality\",\n \"state\": + \"s:addressRegion\",\n \"distance\": {\n \"@id\": + \"s:Distance\",\n \"@type\": \"s:QuantitativeValue\"\n },\n \"bearing\": + {\n \"@type\": \"s:QuantitativeValue\"\n },\n \"value\": + {\n \"@id\": \"s:value\"\n },\n \"unitCode\": + {\n \"@id\": \"s:unitCode\",\n \"@type\": \"@id\"\n },\n \"forecastOffice\": + {\n \"@type\": \"@id\"\n },\n \"forecastGridData\": + {\n \"@type\": \"@id\"\n },\n \"publicZone\": + {\n \"@type\": \"@id\"\n },\n \"county\": + {\n \"@type\": \"@id\"\n }\n }\n ],\n \"id\": + \"https://api.weather.gov/points/47.6062,-122.3321\",\n \"type\": \"Feature\",\n \"geometry\": + {\n \"type\": \"Point\",\n \"coordinates\": [\n -122.3321,\n 47.6062\n ]\n },\n \"properties\": + {\n \"@id\": \"https://api.weather.gov/points/47.6062,-122.3321\",\n \"@type\": + \"wx:Point\",\n \"cwa\": \"SEW\",\n \"type\": \"land\",\n \"forecastOffice\": + \"https://api.weather.gov/offices/SEW\",\n \"gridId\": \"SEW\",\n \"gridX\": + 125,\n \"gridY\": 68,\n \"forecast\": \"https://api.weather.gov/gridpoints/SEW/125,68/forecast\",\n \"forecastHourly\": + \"https://api.weather.gov/gridpoints/SEW/125,68/forecast/hourly\",\n \"forecastGridData\": + \"https://api.weather.gov/gridpoints/SEW/125,68\",\n \"observationStations\": + \"https://api.weather.gov/gridpoints/SEW/125,68/stations\",\n \"relativeLocation\": + {\n \"type\": \"Feature\",\n \"geometry\": {\n \"type\": + \"Point\",\n \"coordinates\": [\n -122.3515382,\n 47.6193352\n ]\n },\n \"properties\": + {\n \"city\": \"Seattle\",\n \"state\": \"WA\",\n \"distance\": + {\n \"unitCode\": \"wmoUnit:m\",\n \"value\": + 0\n },\n \"bearing\": {\n \"unitCode\": + \"wmoUnit:degree_(angle)\",\n \"value\": 0\n }\n }\n },\n \"forecastZone\": + \"https://api.weather.gov/zones/forecast/WAZ315\",\n \"county\": \"https://api.weather.gov/zones/county/WAC033\",\n \"fireWeatherZone\": + \"https://api.weather.gov/zones/fire/WAZ654\",\n \"timeZone\": \"America/Los_Angeles\",\n \"radarStation\": + \"KATX\",\n \"astronomicalData\": {\n \"sunrise\": \"2026-11-05T06:59:58-08:00\",\n \"sunset\": + \"2026-11-05T16:45:52-08:00\",\n \"transit\": \"2026-11-05T11:52:55-08:00\",\n \"civilTwilightBegin\": + \"2026-11-05T06:27:28-08:00\",\n \"civilTwilightEnd\": \"2026-11-05T17:18:22-08:00\",\n \"nauticalTwilightBegin\": + \"2026-11-05T05:50:48-08:00\",\n \"nauticalTwilightEnd\": \"2026-11-05T17:55:02-08:00\",\n \"astronomicalTwilightBegin\": + \"2026-11-05T05:14:54-08:00\",\n \"astronomicalTwilightEnd\": \"2026-11-05T18:30:56-08:00\"\n },\n \"nwr\": + {\n \"transmitter\": \"KHB60\",\n \"sameCode\": \"053033\",\n \"areaBroadcast\": + \"https://api.weather.gov/radio/KHB60/broadcast\",\n \"pointBroadcast\": + \"https://api.weather.gov/points/47.6062,-122.3321/radio\"\n }\n }\n}"}' - name: http_request arguments: method: GET @@ -1116,188 +709,156 @@ tool_executions: result: status: success content: - - text: 'Status Code: 200' - - text: 'Headers: {''Server'': ''nginx/1.28.3'', ''Content-Type'': ''application/geo+json'', - ''Content-Length'': ''1500'', ''Date'': ''Thu, 22 Oct 2026 02:13:50 GMT''}' - - text: "Body: {\n \"@context\": [\n \"https://geojson.org/geojson-ld/geojson-context.jsonld\"\ - ,\n {\n \"@version\": \"1.1\",\n \"wx\": \"https://api.weather.gov/ontology#\"\ - ,\n \"geo\": \"http://www.opengis.net/ont/geosparql#\",\n \ - \ \"unit\": \"http://codes.wmo.int/common/unit/\",\n \"@vocab\"\ - : \"https://api.weather.gov/ontology#\"\n }\n ],\n \"type\":\ - \ \"Feature\",\n \"geometry\": {\n \"type\": \"Polygon\",\n \ - \ \"coordinates\": [\n [\n [\n \ - \ -122.3017,\n 47.5996\n ],\n \ - \ [\n -122.3079,\n 47.6202\n\ - \ ],\n [\n -122.3383,\n \ - \ 47.616\n ],\n [\n \ - \ -122.3321,\n 47.5954\n ],\n\ - \ [\n -122.3017,\n 47.5996\n\ - \ ]\n ]\n ]\n },\n \"properties\":\ - \ {\n \"units\": \"us\",\n \"forecastGenerator\": \"BaselineForecastGenerator\"\ - ,\n \"generatedAt\": \"2026-10-22T01:08:40+00:00\",\n \"updateTime\"\ - : \"2026-10-21T18:26:43+00:00\",\n \"validTimes\": \"2026-10-21T12:00:00+00:00/P7DT13H\"\ - ,\n \"elevation\": {\n \"unitCode\": \"wmoUnit:m\",\n \ - \ \"value\": 73.152\n },\n \"periods\": [\n \ - \ {\n \"number\": 1,\n \"name\": \"Tonight\"\ - ,\n \"startTime\": \"2026-10-21T18:00:00-07:00\",\n \ - \ \"endTime\": \"2026-10-22T06:00:00-07:00\",\n \"\ - isDaytime\": false,\n \"temperature\": 48,\n \ - \ \"temperatureUnit\": \"F\",\n \"temperatureTrend\": null,\n\ - \ \"probabilityOfPrecipitation\": {\n \"\ - unitCode\": \"wmoUnit:percent\",\n \"value\": 1\n \ - \ },\n \"windSpeed\": \"2 mph\",\n \ - \ \"windDirection\": \"NNE\",\n \"icon\": \"https://api.weather.gov/icons/land/night/sct?size=medium\"\ - ,\n \"shortForecast\": \"Partly Cloudy\",\n \ - \ \"detailedForecast\": \"Partly cloudy, with a low around 48. North northeast\ - \ wind around 2 mph.\"\n },\n {\n \"\ - number\": 2,\n \"name\": \"Thursday\",\n \"\ - startTime\": \"2026-10-22T06:00:00-07:00\",\n \"endTime\":\ - \ \"2026-10-22T18:00:00-07:00\",\n \"isDaytime\": true,\n \ - \ \"temperature\": 58,\n \"temperatureUnit\"\ - : \"F\",\n \"temperatureTrend\": null,\n \"\ - probabilityOfPrecipitation\": {\n \"unitCode\": \"wmoUnit:percent\"\ - ,\n \"value\": 19\n },\n \ - \ \"windSpeed\": \"1 to 5 mph\",\n \"windDirection\": \"NNE\"\ - ,\n \"icon\": \"https://api.weather.gov/icons/land/day/sct/rain,20?size=medium\"\ - ,\n \"shortForecast\": \"Mostly Sunny then Slight Chance Light\ - \ Rain\",\n \"detailedForecast\": \"A slight chance of rain\ - \ after 5pm. Mostly sunny. High near 58, with temperatures falling to around\ - \ 56 in the afternoon. North northeast wind 1 to 5 mph. Chance of precipitation\ - \ is 20%.\"\n },\n {\n \"number\": 3,\n\ - \ \"name\": \"Thursday Night\",\n \"startTime\"\ - : \"2026-10-22T18:00:00-07:00\",\n \"endTime\": \"2026-10-23T06:00:00-07:00\"\ - ,\n \"isDaytime\": false,\n \"temperature\"\ - : 47,\n \"temperatureUnit\": \"F\",\n \"temperatureTrend\"\ - : null,\n \"probabilityOfPrecipitation\": {\n \ - \ \"unitCode\": \"wmoUnit:percent\",\n \"value\"\ - : 13\n },\n \"windSpeed\": \"3 mph\",\n \ - \ \"windDirection\": \"NNW\",\n \"icon\": \"https://api.weather.gov/icons/land/night/bkn?size=medium\"\ - ,\n \"shortForecast\": \"Mostly Cloudy\",\n \ - \ \"detailedForecast\": \"Mostly cloudy, with a low around 47. North northwest\ - \ wind around 3 mph.\"\n },\n {\n \"\ - number\": 4,\n \"name\": \"Friday\",\n \"startTime\"\ - : \"2026-10-23T06:00:00-07:00\",\n \"endTime\": \"2026-10-23T18:00:00-07:00\"\ - ,\n \"isDaytime\": true,\n \"temperature\":\ - \ 56,\n \"temperatureUnit\": \"F\",\n \"temperatureTrend\"\ - : null,\n \"probabilityOfPrecipitation\": {\n \ - \ \"unitCode\": \"wmoUnit:percent\",\n \"value\"\ - : 1\n },\n \"windSpeed\": \"3 mph\",\n \ - \ \"windDirection\": \"NW\",\n \"icon\": \"https://api.weather.gov/icons/land/day/sct?size=medium\"\ - ,\n \"shortForecast\": \"Mostly Sunny\",\n \"\ - detailedForecast\": \"Mostly sunny, with a high near 56. Northwest wind around\ - \ 3 mph.\"\n },\n {\n \"number\": 5,\n\ - \ \"name\": \"Friday Night\",\n \"startTime\"\ - : \"2026-10-23T18:00:00-07:00\",\n \"endTime\": \"2026-10-24T06:00:00-07:00\"\ - ,\n \"isDaytime\": false,\n \"temperature\"\ - : 44,\n \"temperatureUnit\": \"F\",\n \"temperatureTrend\"\ - : null,\n \"probabilityOfPrecipitation\": {\n \ - \ \"unitCode\": \"wmoUnit:percent\",\n \"value\"\ - : 6\n },\n \"windSpeed\": \"2 mph\",\n \ - \ \"windDirection\": \"ESE\",\n \"icon\": \"https://api.weather.gov/icons/land/night/sct?size=medium\"\ - ,\n \"shortForecast\": \"Partly Cloudy\",\n \ - \ \"detailedForecast\": \"Partly cloudy, with a low around 44. East southeast\ - \ wind around 2 mph.\"\n },\n {\n \"\ - number\": 6,\n \"name\": \"Saturday\",\n \"\ - startTime\": \"2026-10-24T06:00:00-07:00\",\n \"endTime\":\ - \ \"2026-10-24T18:00:00-07:00\",\n \"isDaytime\": true,\n \ - \ \"temperature\": 54,\n \"temperatureUnit\"\ - : \"F\",\n \"temperatureTrend\": null,\n \"\ - probabilityOfPrecipitation\": {\n \"unitCode\": \"wmoUnit:percent\"\ - ,\n \"value\": 62\n },\n \ - \ \"windSpeed\": \"3 mph\",\n \"windDirection\": \"S\",\n \ - \ \"icon\": \"https://api.weather.gov/icons/land/day/rain,20/rain,60?size=medium\"\ - ,\n \"shortForecast\": \"Light Rain Likely\",\n \ - \ \"detailedForecast\": \"Rain likely after 11am. Mostly cloudy, with\ - \ a high near 54. Chance of precipitation is 60%. New rainfall amounts less\ - \ than a tenth of an inch possible.\"\n },\n {\n \ - \ \"number\": 7,\n \"name\": \"Saturday Night\"\ - ,\n \"startTime\": \"2026-10-24T18:00:00-07:00\",\n \ - \ \"endTime\": \"2026-10-25T06:00:00-07:00\",\n \"\ - isDaytime\": false,\n \"temperature\": 46,\n \ - \ \"temperatureUnit\": \"F\",\n \"temperatureTrend\": null,\n\ - \ \"probabilityOfPrecipitation\": {\n \"\ - unitCode\": \"wmoUnit:percent\",\n \"value\": 62\n \ - \ },\n \"windSpeed\": \"5 mph\",\n \ - \ \"windDirection\": \"ENE\",\n \"icon\": \"https://api.weather.gov/icons/land/night/rain,60/rain,50?size=medium\"\ - ,\n \"shortForecast\": \"Light Rain Likely\",\n \ - \ \"detailedForecast\": \"Rain likely. Mostly cloudy, with a low around\ - \ 46.\"\n },\n {\n \"number\": 8,\n \ - \ \"name\": \"Sunday\",\n \"startTime\": \"2026-10-25T06:00:00-07:00\"\ - ,\n \"endTime\": \"2026-10-25T18:00:00-07:00\",\n \ - \ \"isDaytime\": true,\n \"temperature\": 57,\n \ - \ \"temperatureUnit\": \"F\",\n \"temperatureTrend\"\ - : null,\n \"probabilityOfPrecipitation\": {\n \ - \ \"unitCode\": \"wmoUnit:percent\",\n \"value\"\ - : 34\n },\n \"windSpeed\": \"5 mph\",\n \ - \ \"windDirection\": \"NE\",\n \"icon\": \"https://api.weather.gov/icons/land/day/rain,30?size=medium\"\ - ,\n \"shortForecast\": \"Chance Light Rain\",\n \ - \ \"detailedForecast\": \"A chance of rain. Mostly cloudy, with a high\ - \ near 57.\"\n },\n {\n \"number\": 9,\n\ - \ \"name\": \"Sunday Night\",\n \"startTime\"\ - : \"2026-10-25T18:00:00-07:00\",\n \"endTime\": \"2026-10-26T06:00:00-07:00\"\ - ,\n \"isDaytime\": false,\n \"temperature\"\ - : 47,\n \"temperatureUnit\": \"F\",\n \"temperatureTrend\"\ - : null,\n \"probabilityOfPrecipitation\": {\n \ - \ \"unitCode\": \"wmoUnit:percent\",\n \"value\"\ - : 34\n },\n \"windSpeed\": \"3 mph\",\n \ - \ \"windDirection\": \"NNE\",\n \"icon\": \"https://api.weather.gov/icons/land/night/rain,30?size=medium\"\ - ,\n \"shortForecast\": \"Chance Light Rain\",\n \ - \ \"detailedForecast\": \"A chance of rain. Mostly cloudy, with a low\ - \ around 47.\"\n },\n {\n \"number\"\ - : 10,\n \"name\": \"Monday\",\n \"startTime\"\ - : \"2026-10-26T06:00:00-07:00\",\n \"endTime\": \"2026-10-26T18:00:00-07:00\"\ - ,\n \"isDaytime\": true,\n \"temperature\":\ - \ 57,\n \"temperatureUnit\": \"F\",\n \"temperatureTrend\"\ - : null,\n \"probabilityOfPrecipitation\": {\n \ - \ \"unitCode\": \"wmoUnit:percent\",\n \"value\"\ - : 28\n },\n \"windSpeed\": \"3 mph\",\n \ - \ \"windDirection\": \"N\",\n \"icon\": \"https://api.weather.gov/icons/land/day/rain,20/rain,30?size=medium\"\ - ,\n \"shortForecast\": \"Chance Light Rain\",\n \ - \ \"detailedForecast\": \"A chance of rain. Partly sunny, with a high\ - \ near 57.\"\n },\n {\n \"number\": 11,\n\ - \ \"name\": \"Monday Night\",\n \"startTime\"\ - : \"2026-10-26T18:00:00-07:00\",\n \"endTime\": \"2026-10-27T06:00:00-07:00\"\ - ,\n \"isDaytime\": false,\n \"temperature\"\ - : 46,\n \"temperatureUnit\": \"F\",\n \"temperatureTrend\"\ - : null,\n \"probabilityOfPrecipitation\": {\n \ - \ \"unitCode\": \"wmoUnit:percent\",\n \"value\"\ - : 28\n },\n \"windSpeed\": \"3 mph\",\n \ - \ \"windDirection\": \"ENE\",\n \"icon\": \"https://api.weather.gov/icons/land/night/rain,30/rain,20?size=medium\"\ - ,\n \"shortForecast\": \"Chance Light Rain\",\n \ - \ \"detailedForecast\": \"A chance of rain. Mostly cloudy, with a low\ - \ around 46.\"\n },\n {\n \"number\"\ - : 12,\n \"name\": \"Tuesday\",\n \"startTime\"\ - : \"2026-10-27T06:00:00-07:00\",\n \"endTime\": \"2026-10-27T18:00:00-07:00\"\ - ,\n \"isDaytime\": true,\n \"temperature\":\ - \ 56,\n \"temperatureUnit\": \"F\",\n \"temperatureTrend\"\ - : null,\n \"probabilityOfPrecipitation\": {\n \ - \ \"unitCode\": \"wmoUnit:percent\",\n \"value\"\ - : 23\n },\n \"windSpeed\": \"3 mph\",\n \ - \ \"windDirection\": \"SW\",\n \"icon\": \"https://api.weather.gov/icons/land/day/rain,20?size=medium\"\ - ,\n \"shortForecast\": \"Slight Chance Light Rain\",\n \ - \ \"detailedForecast\": \"A slight chance of rain. Partly sunny,\ - \ with a high near 56.\"\n },\n {\n \"\ - number\": 13,\n \"name\": \"Tuesday Night\",\n \ - \ \"startTime\": \"2026-10-27T18:00:00-07:00\",\n \"endTime\"\ - : \"2026-10-28T06:00:00-07:00\",\n \"isDaytime\": false,\n\ - \ \"temperature\": 45,\n \"temperatureUnit\"\ - : \"F\",\n \"temperatureTrend\": null,\n \"\ - probabilityOfPrecipitation\": {\n \"unitCode\": \"wmoUnit:percent\"\ - ,\n \"value\": 23\n },\n \ - \ \"windSpeed\": \"3 mph\",\n \"windDirection\": \"SSW\",\n\ - \ \"icon\": \"https://api.weather.gov/icons/land/night/rain,20?size=medium\"\ - ,\n \"shortForecast\": \"Slight Chance Light Rain\",\n \ - \ \"detailedForecast\": \"A slight chance of rain. Partly cloudy,\ - \ with a low around 45.\"\n },\n {\n \ - \ \"number\": 14,\n \"name\": \"Wednesday\",\n \ - \ \"startTime\": \"2026-10-28T06:00:00-07:00\",\n \"endTime\"\ - : \"2026-10-28T18:00:00-07:00\",\n \"isDaytime\": true,\n \ - \ \"temperature\": 55,\n \"temperatureUnit\"\ - : \"F\",\n \"temperatureTrend\": null,\n \"\ - probabilityOfPrecipitation\": {\n \"unitCode\": \"wmoUnit:percent\"\ - ,\n \"value\": 20\n },\n \ - \ \"windSpeed\": \"5 mph\",\n \"windDirection\": \"NNE\",\n\ - \ \"icon\": \"https://api.weather.gov/icons/land/day/rain,20?size=medium\"\ - ,\n \"shortForecast\": \"Slight Chance Light Rain\",\n \ - \ \"detailedForecast\": \"A slight chance of rain. Mostly sunny,\ - \ with a high near 55.\"\n }\n ]\n }\n}" + - text: '{"status": 200, "status_text": "OK", "headers": {"server": "nginx/1.28.3", + "content-type": "application/geo+json", "last-modified": "Thu, 05 Nov 2026 + 06:26:49 GMT", "access-control-allow-origin": "*", "access-control-expose-headers": + "X-Correlation-Id, X-Request-Id, X-Server-Id", "x-request-id": "01a1abd0-bb7c-7272-85cd-ccecd6e97121", + "x-correlation-id": "f49bdaa8", "x-server-id": "vm-cprk-api-ops-app14.ncep.noaa.gov", + "etag": "W/\"1793860011:dtagent10337260504112723F6xZ:dtagent10337260504112723F6xZ\"", + "server-timing": "dtTrId;desc=\"0f5efddfbabb1763576faabf607c16f9\", dtSInfo;desc=\"0\"", + "content-encoding": "gzip", "content-length": "1588", "cache-control": "public, + max-age=507, s-maxage=3600", "expires": "Thu, 05 Nov 2026 14:05:45 GMT", "date": + "Thu, 05 Nov 2026 13:57:18 GMT", "connection": "keep-alive", "vary": "Accept-Encoding\nAccept,Feature-Flags,Accept-Language", + "x-edge-request-id": "2f85403a", "strict-transport-security": "max-age=31536000 + ; includeSubDomains ; preload"}, "body": "{\n \"@context\": [\n \"https://geojson.org/geojson-ld/geojson-context.jsonld\",\n {\n \"@version\": + \"1.1\",\n \"wx\": \"https://api.weather.gov/ontology#\",\n \"geo\": + \"http://www.opengis.net/ont/geosparql#\",\n \"unit\": \"http://codes.wmo.int/common/unit/\",\n \"@vocab\": + \"https://api.weather.gov/ontology#\"\n }\n ],\n \"type\": \"Feature\",\n \"geometry\": + {\n \"type\": \"Polygon\",\n \"coordinates\": [\n [\n [\n -122.3017,\n 47.5996\n ],\n [\n -122.3079,\n 47.6202\n ],\n [\n -122.3383,\n 47.616\n ],\n [\n -122.3321,\n 47.5954\n ],\n [\n -122.3017,\n 47.5996\n ]\n ]\n ]\n },\n \"properties\": + {\n \"units\": \"us\",\n \"forecastGenerator\": \"BaselineForecastGenerator\",\n \"generatedAt\": + \"2026-11-05T13:05:45+00:00\",\n \"updateTime\": \"2026-11-05T06:26:51+00:00\",\n \"validTimes\": + \"2026-11-05T00:00:00+00:00/P8DT1H\",\n \"elevation\": {\n \"unitCode\": + \"wmoUnit:m\",\n \"value\": 73.152\n },\n \"periods\": + [\n {\n \"number\": 1,\n \"name\": + \"Overnight\",\n \"startTime\": \"2026-11-05T05:00:00-08:00\",\n \"endTime\": + \"2026-11-05T06:00:00-08:00\",\n \"isDaytime\": false,\n \"temperature\": + 50,\n \"temperatureUnit\": \"F\",\n \"temperatureTrend\": + null,\n \"probabilityOfPrecipitation\": {\n \"unitCode\": + \"wmoUnit:percent\",\n \"value\": 4\n },\n \"windSpeed\": + \"6 mph\",\n \"windDirection\": \"S\",\n \"icon\": + \"https://api.weather.gov/icons/land/night/sct?size=medium\",\n \"shortForecast\": + \"Partly Cloudy\",\n \"detailedForecast\": \"Partly cloudy, + with a low around 50. South wind around 6 mph.\"\n },\n {\n \"number\": + 2,\n \"name\": \"Thursday\",\n \"startTime\": + \"2026-11-05T06:00:00-08:00\",\n \"endTime\": \"2026-11-05T18:00:00-08:00\",\n \"isDaytime\": + true,\n \"temperature\": 56,\n \"temperatureUnit\": + \"F\",\n \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\": + {\n \"unitCode\": \"wmoUnit:percent\",\n \"value\": + 4\n },\n \"windSpeed\": \"3 to 9 mph\",\n \"windDirection\": + \"S\",\n \"icon\": \"https://api.weather.gov/icons/land/day/bkn?size=medium\",\n \"shortForecast\": + \"Partly Sunny\",\n \"detailedForecast\": \"Partly sunny. High + near 56, with temperatures falling to around 54 in the afternoon. South wind + 3 to 9 mph.\"\n },\n {\n \"number\": + 3,\n \"name\": \"Thursday Night\",\n \"startTime\": + \"2026-11-05T18:00:00-08:00\",\n \"endTime\": \"2026-11-06T06:00:00-08:00\",\n \"isDaytime\": + false,\n \"temperature\": 47,\n \"temperatureUnit\": + \"F\",\n \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\": + {\n \"unitCode\": \"wmoUnit:percent\",\n \"value\": + 39\n },\n \"windSpeed\": \"7 mph\",\n \"windDirection\": + \"SSE\",\n \"icon\": \"https://api.weather.gov/icons/land/night/bkn/rain,40?size=medium\",\n \"shortForecast\": + \"Mostly Cloudy then Chance Light Rain\",\n \"detailedForecast\": + \"A chance of rain after 4am. Mostly cloudy. Low around 47, with temperatures + rising to around 49 overnight. South southeast wind around 7 mph. Chance of + precipitation is 40%. New rainfall amounts less than a tenth of an inch possible.\"\n },\n {\n \"number\": + 4,\n \"name\": \"Friday\",\n \"startTime\": + \"2026-11-06T06:00:00-08:00\",\n \"endTime\": \"2026-11-06T18:00:00-08:00\",\n \"isDaytime\": + true,\n \"temperature\": 55,\n \"temperatureUnit\": + \"F\",\n \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\": + {\n \"unitCode\": \"wmoUnit:percent\",\n \"value\": + 80\n },\n \"windSpeed\": \"8 mph\",\n \"windDirection\": + \"S\",\n \"icon\": \"https://api.weather.gov/icons/land/day/rain,20/rain,80?size=medium\",\n \"shortForecast\": + \"Light Rain\",\n \"detailedForecast\": \"Rain. Cloudy, with + a high near 55. South wind around 8 mph. Chance of precipitation is 80%. New + rainfall amounts between a tenth and quarter of an inch possible.\"\n },\n {\n \"number\": + 5,\n \"name\": \"Friday Night\",\n \"startTime\": + \"2026-11-06T18:00:00-08:00\",\n \"endTime\": \"2026-11-07T06:00:00-08:00\",\n \"isDaytime\": + false,\n \"temperature\": 51,\n \"temperatureUnit\": + \"F\",\n \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\": + {\n \"unitCode\": \"wmoUnit:percent\",\n \"value\": + 80\n },\n \"windSpeed\": \"2 to 8 mph\",\n \"windDirection\": + \"SSE\",\n \"icon\": \"https://api.weather.gov/icons/land/night/rain,80/rain,60?size=medium\",\n \"shortForecast\": + \"Light Rain\",\n \"detailedForecast\": \"Rain. Cloudy, with + a low around 51. South southeast wind 2 to 8 mph. Chance of precipitation + is 80%. New rainfall amounts less than a tenth of an inch possible.\"\n },\n {\n \"number\": + 6,\n \"name\": \"Saturday\",\n \"startTime\": + \"2026-11-07T06:00:00-08:00\",\n \"endTime\": \"2026-11-07T18:00:00-08:00\",\n \"isDaytime\": + true,\n \"temperature\": 63,\n \"temperatureUnit\": + \"F\",\n \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\": + {\n \"unitCode\": \"wmoUnit:percent\",\n \"value\": + 61\n },\n \"windSpeed\": \"2 to 6 mph\",\n \"windDirection\": + \"SSE\",\n \"icon\": \"https://api.weather.gov/icons/land/day/rain,40/rain,60?size=medium\",\n \"shortForecast\": + \"Light Rain Likely\",\n \"detailedForecast\": \"Rain likely. + Mostly cloudy, with a high near 63. Chance of precipitation is 60%. New rainfall + amounts less than a tenth of an inch possible.\"\n },\n {\n \"number\": + 7,\n \"name\": \"Saturday Night\",\n \"startTime\": + \"2026-11-07T18:00:00-08:00\",\n \"endTime\": \"2026-11-08T06:00:00-08:00\",\n \"isDaytime\": + false,\n \"temperature\": 51,\n \"temperatureUnit\": + \"F\",\n \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\": + {\n \"unitCode\": \"wmoUnit:percent\",\n \"value\": + 96\n },\n \"windSpeed\": \"6 to 20 mph\",\n \"windDirection\": + \"SSW\",\n \"icon\": \"https://api.weather.gov/icons/land/night/rain,100?size=medium\",\n \"shortForecast\": + \"Light Rain\",\n \"detailedForecast\": \"Rain. Mostly cloudy, + with a low around 51.\"\n },\n {\n \"number\": + 8,\n \"name\": \"Sunday\",\n \"startTime\": + \"2026-11-08T06:00:00-08:00\",\n \"endTime\": \"2026-11-08T18:00:00-08:00\",\n \"isDaytime\": + true,\n \"temperature\": 55,\n \"temperatureUnit\": + \"F\",\n \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\": + {\n \"unitCode\": \"wmoUnit:percent\",\n \"value\": + 50\n },\n \"windSpeed\": \"5 to 17 mph\",\n \"windDirection\": + \"SSW\",\n \"icon\": \"https://api.weather.gov/icons/land/day/rain,50/rain,20?size=medium\",\n \"shortForecast\": + \"Chance Light Rain\",\n \"detailedForecast\": \"A chance of + rain before 4pm. Partly sunny, with a high near 55.\"\n },\n {\n \"number\": + 9,\n \"name\": \"Sunday Night\",\n \"startTime\": + \"2026-11-08T18:00:00-08:00\",\n \"endTime\": \"2026-11-09T06:00:00-08:00\",\n \"isDaytime\": + false,\n \"temperature\": 44,\n \"temperatureUnit\": + \"F\",\n \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\": + {\n \"unitCode\": \"wmoUnit:percent\",\n \"value\": + 9\n },\n \"windSpeed\": \"5 mph\",\n \"windDirection\": + \"SE\",\n \"icon\": \"https://api.weather.gov/icons/land/night/sct?size=medium\",\n \"shortForecast\": + \"Partly Cloudy\",\n \"detailedForecast\": \"Partly cloudy, + with a low around 44.\"\n },\n {\n \"number\": + 10,\n \"name\": \"Monday\",\n \"startTime\": + \"2026-11-09T06:00:00-08:00\",\n \"endTime\": \"2026-11-09T18:00:00-08:00\",\n \"isDaytime\": + true,\n \"temperature\": 55,\n \"temperatureUnit\": + \"F\",\n \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\": + {\n \"unitCode\": \"wmoUnit:percent\",\n \"value\": + 54\n },\n \"windSpeed\": \"3 mph\",\n \"windDirection\": + \"SE\",\n \"icon\": \"https://api.weather.gov/icons/land/day/rain,20/rain,50?size=medium\",\n \"shortForecast\": + \"Chance Light Rain\",\n \"detailedForecast\": \"A chance of + rain after 10am. Mostly cloudy, with a high near 55.\"\n },\n {\n \"number\": + 11,\n \"name\": \"Monday Night\",\n \"startTime\": + \"2026-11-09T18:00:00-08:00\",\n \"endTime\": \"2026-11-10T06:00:00-08:00\",\n \"isDaytime\": + false,\n \"temperature\": 50,\n \"temperatureUnit\": + \"F\",\n \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\": + {\n \"unitCode\": \"wmoUnit:percent\",\n \"value\": + 75\n },\n \"windSpeed\": \"3 to 13 mph\",\n \"windDirection\": + \"SSE\",\n \"icon\": \"https://api.weather.gov/icons/land/night/rain,60/rain,80?size=medium\",\n \"shortForecast\": + \"Light Rain\",\n \"detailedForecast\": \"Rain. Mostly cloudy, + with a low around 50.\"\n },\n {\n \"number\": + 12,\n \"name\": \"Tuesday\",\n \"startTime\": + \"2026-11-10T06:00:00-08:00\",\n \"endTime\": \"2026-11-10T18:00:00-08:00\",\n \"isDaytime\": + true,\n \"temperature\": 58,\n \"temperatureUnit\": + \"F\",\n \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\": + {\n \"unitCode\": \"wmoUnit:percent\",\n \"value\": + 75\n },\n \"windSpeed\": \"8 to 14 mph\",\n \"windDirection\": + \"S\",\n \"icon\": \"https://api.weather.gov/icons/land/day/rain,80/rain,70?size=medium\",\n \"shortForecast\": + \"Light Rain\",\n \"detailedForecast\": \"Rain. Mostly cloudy, + with a high near 58.\"\n },\n {\n \"number\": + 13,\n \"name\": \"Tuesday Night\",\n \"startTime\": + \"2026-11-10T18:00:00-08:00\",\n \"endTime\": \"2026-11-11T06:00:00-08:00\",\n \"isDaytime\": + false,\n \"temperature\": 52,\n \"temperatureUnit\": + \"F\",\n \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\": + {\n \"unitCode\": \"wmoUnit:percent\",\n \"value\": + 71\n },\n \"windSpeed\": \"8 to 13 mph\",\n \"windDirection\": + \"S\",\n \"icon\": \"https://api.weather.gov/icons/land/night/rain,70/rain,60?size=medium\",\n \"shortForecast\": + \"Light Rain Likely\",\n \"detailedForecast\": \"Rain likely. + Mostly cloudy, with a low around 52.\"\n },\n {\n \"number\": + 14,\n \"name\": \"Veterans Day\",\n \"startTime\": + \"2026-11-11T06:00:00-08:00\",\n \"endTime\": \"2026-11-11T18:00:00-08:00\",\n \"isDaytime\": + true,\n \"temperature\": 60,\n \"temperatureUnit\": + \"F\",\n \"temperatureTrend\": null,\n \"probabilityOfPrecipitation\": + {\n \"unitCode\": \"wmoUnit:percent\",\n \"value\": + 56\n },\n \"windSpeed\": \"6 to 10 mph\",\n \"windDirection\": + \"S\",\n \"icon\": \"https://api.weather.gov/icons/land/day/rain,60/rain,50?size=medium\",\n \"shortForecast\": + \"Light Rain Likely\",\n \"detailedForecast\": \"Rain likely. + Mostly cloudy, with a high near 60.\"\n }\n ]\n }\n}"}' diff --git a/examples/strands-weather-forecaster/weather_agent.py b/examples/strands-weather-forecaster/weather_agent.py index 8d16419..385084b 100644 --- a/examples/strands-weather-forecaster/weather_agent.py +++ b/examples/strands-weather-forecaster/weather_agent.py @@ -7,7 +7,7 @@ from strands import Agent from strands.models.bedrock import BedrockModel -from strands_tools import http_request +from strands.vended_tools import http_request WEATHER_SYSTEM_PROMPT = """You are a weather assistant with HTTP capabilities. You can: 1. Make HTTP requests to the National Weather Service API diff --git a/pyproject.toml b/pyproject.toml index aa86ce3..4f2e403 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "agentverify" -version = "0.8.0" +version = "0.9.0" description = "Deterministic testing for AI agents. Assert agent actions, not vibes." readme = "README.md" license = {text = "MIT"} diff --git a/tests/test_cassette_expiry.py b/tests/test_cassette_expiry.py index 47c2eb9..08a6634 100644 --- a/tests/test_cassette_expiry.py +++ b/tests/test_cassette_expiry.py @@ -117,7 +117,10 @@ def test_fresh(cassette): _cassette(cassettes / "old.yaml", days_ago=40) _cassette(cassettes / "fresh.yaml", days_ago=0.5) (cassettes / "notes.json").write_text("not json") - (cassettes / "legacy.yaml").write_text("metadata: legacy\n") + (cassettes / "legacy.yaml").write_text("interactions: []\nmetadata: legacy\n") + (cassettes / "approvals.json").write_text('[{"kind": "digits"}]') # not a cassette: left out + (cassettes / "notes.yaml").write_text("owner: someone\n") # not a cassette either + (cassettes / "empty.yaml").write_text("") # a cassette cut short return pytester.runpytest_inprocess("-p", "agentverify", *args) @@ -143,7 +146,9 @@ def test_report_lists_cassettes_without_running_tests(self, pytester): assert "status (max age 30d)" in out and "openai" in out lines = {line.split()[0]: line for line in out.splitlines() if line.startswith("cassettes/")} assert "expired: recorded" in lines["cassettes/old.yaml"] and lines["cassettes/fresh.yaml"].rstrip().endswith("ok") - assert "unreadable: " in lines["cassettes/notes.json"] and "unreadable: TypeError" in lines["cassettes/legacy.yaml"] + assert "unreadable: " in lines["cassettes/notes.json"] and "metadata is not a mapping" in lines["cassettes/legacy.yaml"] + assert "cassettes/approvals.json" not in lines and "cassettes/notes.yaml" not in lines + assert "unreadable: empty" in lines["cassettes/empty.yaml"] def test_report_without_a_limit_or_cassettes(self, pytester): result = _run(pytester, "--cassette-report", "--cassette-max-age=12h") diff --git a/tests/test_credential_urls.py b/tests/test_credential_urls.py new file mode 100644 index 0000000..6e77371 --- /dev/null +++ b/tests/test_credential_urls.py @@ -0,0 +1,55 @@ +"""assert_no_credential_urls: no URL the model was sent carries a key, token, or signature.""" + +from __future__ import annotations + +import pytest + +from agentverify import CredentialURLError, assert_no_credential_urls +from agentverify.cassette.adapters.base import NormalizedRequest + +PRESIGNED = "https://download-ring.amazon.dev/v1/download?X-Amz-Date=20261105&X-Amz-Expires=900&security_token=SECRET1&X-Amz-Signature=SECRET2" +JWT = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.c2lnbmF0dXJl" + + +def _request(*tool_results, tools=None): + messages = [{"role": "assistant", "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "history", "arguments": "{}"}}]}] + messages += [{"role": "tool", "tool_call_id": "c1", "content": r} for r in tool_results] + return NormalizedRequest(model="m", messages=messages, tools=tools) + + +def test_clean_requests_pass(): + assert_no_credential_urls(_request('{"events": [{"at": "now", "link": "https://example.com/events?page=2"}]}')) + + +def test_presigned_and_token_urls_fail_without_showing_values(): + request = _request(f'{{"visualizations": "{PRESIGNED}"}}', f"see https://api.example.com/v1/{JWT}/x and https://h.example/cb?Access_Token=abc") + with pytest.raises(CredentialURLError) as error: + assert_no_credential_urls(request) + message = str(error.value) + assert message.startswith("3 URLs with a credential sent to the model") + assert "request[0].message[1](tool).tool_result[0](history).visualizations: download-ring.amazon.dev (X-Amz-Signature, security_token)" in message + assert "api.example.com (JWT)" in message and "h.example (Access_Token)" in message + assert "SECRET1" not in message and "SECRET2" not in message and JWT not in message and "abc" not in message + + +def test_tool_definitions_are_searched_and_options_apply(): + tools = [{"name": "f", "description": "Docs at https://docs.example/?key=public-value"}] + with pytest.raises(CredentialURLError, match=r"tool\[f\]\.description: docs\.example \(key\)"): + assert_no_credential_urls(_request(tools=tools)) + assert_no_credential_urls(_request(tools=tools), ignore=["KEY"]) + with pytest.raises(CredentialURLError, match=r"pattern '\[\?&\]code='"): + assert_no_credential_urls(_request("https://app.example/callback?code=xyz"), extra_patterns=[r"[?&]code="]) + assert_no_credential_urls(_request("https://app.example/callback?code=xyz")) # code is not in the defaults + with pytest.raises(CredentialURLError, match=r"\?"): + assert_no_credential_urls(_request("http://?token=1")) # no host + + +def test_review_fixes(): + """Fragments, HTML-escaped separators, and hosts urlsplit rejects.""" + with pytest.raises(CredentialURLError, match=r"app\.example \(access_token\)"): + assert_no_credential_urls(_request("https://app.example/cb#access_token=ya29&token_type=bearer")) + with pytest.raises(CredentialURLError, match=r"x\.blob\.core\.windows\.net \(sig\)"): + assert_no_credential_urls(_request("")) + assert_no_credential_urls(_request("template: http://[placeholder]/path")) # no crash, nothing to flag + with pytest.raises(CredentialURLError, match=r": \? \(token\)"): + assert_no_credential_urls(_request("http://[placeholder]/p?token=1#frag")) diff --git a/tests/test_drift.py b/tests/test_drift.py new file mode 100644 index 0000000..c98c643 --- /dev/null +++ b/tests/test_drift.py @@ -0,0 +1,127 @@ +"""Drift: replayed tool results, messages, and parameters compared with the recording (off by default).""" + +from __future__ import annotations + +import pytest + +from agentverify import CassetteDriftError +from agentverify.cassette.adapters.base import NormalizedRequest, NormalizedResponse +from agentverify.cassette.drift import compile_ignore, describe, drift +from agentverify.cassette.io import save_cassette +from agentverify.cassette.recorder import CassetteMode, LLMCassetteRecorder, _stale_cassettes + +pytest_plugins = ["pytester"] + + +@pytest.fixture(autouse=True) +def _clear(): + _stale_cassettes.clear() + yield + _stale_cassettes.clear() + + +def _request(result: str, extra=(), **parameters): + messages = [ + {"role": "user", "content": "events?"}, + {"role": "assistant", "content": None, "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "camera_events", "arguments": "{}"}}]}, + {"role": "tool", "tool_call_id": "c1", "content": result}, + *extra, + ] + return NormalizedRequest(model="m", messages=messages, parameters=parameters) + + +RECORDED = _request('{"events": [{"kind": "motion"}], "now": "10:00"}', temperature=0) + + +class TestCompare: + def test_what_differs(self): + assert drift(RECORDED, RECORDED, 3, []) == [] + changed = _request('{"events": [{"kind": "motion", "description": null}], "now": "10:05"}', temperature=1) + assert drift(RECORDED, changed, 3, []) == [ + "request[3].message[2](tool).tool_result[0](camera_events).events[0].description", # a new null counts + "request[3].message[2](tool).tool_result[0](camera_events).now", + "request[3].parameters.temperature", + ] + assert drift(RECORDED, changed, 3, compile_ignore(["request[*].message[*].tool_result[*].now", "*.temperature", "*.description"])) == [] + longer = _request('{"events": [{"kind": "motion"}], "now": "10:00"}', extra=[{"role": "assistant", "content": "done"}], temperature=0) + assert drift(RECORDED, longer, 0, []) == ["request[0].messages (roles user,assistant,tool → user,assistant,tool,assistant)"] + + def test_brackets_in_globs_are_literal_and_describe_truncates(self): + [pattern] = compile_ignore(["request[1].x"]) + assert pattern.match("request[1].x") and not pattern.match("request1.x") + assert describe([str(i) for i in range(7)]) == "0, 1, 2, 3, 4, and 2 more" + + +class TestRecorder: + def _cassette(self, tmp_path): + path = tmp_path / "c.yaml" + save_cassette(path, [(RECORDED, NormalizedResponse(content="ok"))], provider="openai") + return path + + def test_off_by_default(self, tmp_path): + with LLMCassetteRecorder(self._cassette(tmp_path), mode=CassetteMode.REPLAY) as rec: + rec.lookup(_request('{"events": [], "now": "11:00"}', temperature=0)) + assert _stale_cassettes == [] + + def test_warn_lists_and_fail_raises(self, tmp_path): + path = self._cassette(tmp_path) + now = _request('{"events": [{"kind": "motion"}], "now": "11:00"}', temperature=0) + with LLMCassetteRecorder(path, mode=CassetteMode.REPLAY, drift="warn") as rec: + assert rec.lookup(now).content == "ok" + assert _stale_cassettes[0][2] == "drift: request[0].message[2](tool).tool_result[0](camera_events).now" + with pytest.raises(CassetteDriftError, match=r"request 0 differs from the recording\n\n request\[0\]\.message\[2\]"): + with LLMCassetteRecorder(path, mode=CassetteMode.REPLAY, drift="fail") as rec: + try: + rec.lookup(now) + except CassetteDriftError: + pass # a framework catching it; the cassette raises it again on exit + with LLMCassetteRecorder(path, mode=CassetteMode.REPLAY, drift="fail", drift_ignore=["*.now"]) as rec: + rec.lookup(now) + with LLMCassetteRecorder(path, mode=CassetteMode.REPLAY, drift="fail", match_ignore=[r"\d\d:\d\d"]) as rec: + rec.lookup(now) # match_ignore applies too + with pytest.raises(ValueError, match="drift must be one of"): + LLMCassetteRecorder(path, drift="loud") + + +def test_pytest_settings_and_summary(pytester): + pytester.makepyfile( + """ +from agentverify.cassette.adapters.base import NormalizedRequest, NormalizedResponse +from agentverify.cassette.io import save_cassette +import pathlib + +def _request(now): + return NormalizedRequest(model="m", messages=[{"role": "tool", "tool_call_id": "c", "content": now}]) + +def _setup(): + path = pathlib.Path(__file__).parent / "cassettes" / "d.yaml" + path.parent.mkdir(exist_ok=True) + save_cassette(path, [(_request("10:00"), NormalizedResponse(content="ok"))], provider="openai") + +def test_default(cassette): + _setup() + with cassette("d.yaml") as rec: + rec.lookup(_request("11:00")) + +def test_strict(cassette): + _setup() + with cassette("d.yaml", drift="fail") as rec: + rec.lookup(_request("11:00")) +""" + ) + pytester.makeini("[pytest]\nagentverify_cassette_drift = warn\n") + result = pytester.runpytest_inprocess("-p", "agentverify") + result.assert_outcomes(passed=1, failed=1) + out = result.stdout.str() + assert "CassetteDriftError" in out and "cassettes/d.yaml (drift: request[0].message[0](tool).tool_result[0](?))" in out + result = pytester.runpytest_inprocess("-p", "agentverify", "--cassette-drift=off", "-k", "default") + result.assert_outcomes(passed=1) + assert "stale cassettes" not in result.stdout.str() + + +def test_drift_works_without_request_matching(tmp_path): + path = tmp_path / "c.yaml" + save_cassette(path, [(RECORDED, NormalizedResponse(content="ok"))], provider="openai") + with pytest.raises(CassetteDriftError): + with LLMCassetteRecorder(path, mode=CassetteMode.REPLAY, match_requests=False, drift="fail") as rec: + rec.lookup(_request('{"events": [], "now": "10:00"}', model="other", temperature=0)) diff --git a/tests/test_failure_output.py b/tests/test_failure_output.py new file mode 100644 index 0000000..132b5be --- /dev/null +++ b/tests/test_failure_output.py @@ -0,0 +1,61 @@ +"""How failures read: pytest points at the test's line, and assert_all indents each failure under its number.""" + +from __future__ import annotations + +import pytest + +from agentverify import ExecutionResult, ToolCall, assert_all, assert_cost, assert_tool_calls +from agentverify.errors import MultipleAssertionError + +pytest_plugins = ["pytester"] + + +def test_tracebacks_stop_at_the_test(pytester): + pytester.makepyfile( + """ +from agentverify import ExecutionResult, ToolCall, assert_step, assert_tool_calls + +def test_x(): + result = ExecutionResult.from_dict({"steps": [{"index": 0, "tool_calls": [{"name": "a"}]}]}) + assert_step(result, step=0, expected_tool=ToolCall("b")) +""" + ) + out = pytester.runpytest_inprocess("--tb=short").stdout.str() + assert "ToolCallSequenceError" in out and "assertions.py" not in out + + +def test_assert_all_indents_each_failure(): + result = ExecutionResult.from_dict({"tool_calls": [{"name": "a"}], "token_usage": {"input_tokens": 10, "output_tokens": 0}}) + with pytest.raises(MultipleAssertionError) as error: + assert_all(result, lambda r: assert_tool_calls(r, expected=[ToolCall("b")]), lambda r: assert_cost(r, max_tokens=1)) + lines = str(error.value).split("\n") + assert lines[0] == "2 assertions failed:" + first = lines.index(next(line for line in lines if line.startswith(" [1] ToolCallSequenceError"))) + assert lines[first + 2] == " Expected:" and any(line.startswith(" [2] CostBudgetError") for line in lines) + assert " Exceeded by: 9 tokens (900.0%)" in lines + + +def test_cassette_errors_hide_agentverify_frames_but_other_errors_keep_them(pytester): + pytester.makepyfile( + """ +from agentverify.cassette.adapters.base import NormalizedRequest, NormalizedResponse +from agentverify.cassette.io import save_cassette +from agentverify.cassette.recorder import CassetteMode, LLMCassetteRecorder + +def test_stale(tmp_path): + path = tmp_path / "c.yaml" + save_cassette(path, [(NormalizedRequest(messages=[{"role": "user", "content": "a"}], model="m"), NormalizedResponse(content="ok"))], provider="openai") + with LLMCassetteRecorder(path, mode=CassetteMode.REPLAY) as rec: + rec.lookup(NormalizedRequest(messages=[{"role": "user", "content": "b"}], model="m")) + +def test_bug(tmp_path): + path = tmp_path / "c.yaml" + save_cassette(path, [(NormalizedRequest(messages=[], model="m"), NormalizedResponse(content="ok"))], provider="openai") + with LLMCassetteRecorder(path, mode=CassetteMode.REPLAY) as rec: + rec.lookup(None) # not a request: an error from inside agentverify, whose frames stay +""" + ) + out = pytester.runpytest_inprocess("--tb=short", "-p", "no:agentverify").stdout.str() + stale, bug = out.split("_ test_bug _") + assert "CassetteRequestMismatchError" in stale and "recorder.py" not in stale + assert "recorder.py" in bug diff --git a/tests/test_plugin.py b/tests/test_plugin.py index fef6ec0..eb611a7 100644 --- a/tests/test_plugin.py +++ b/tests/test_plugin.py @@ -28,9 +28,10 @@ def test_pytest_addoption_registers_cassette_mode(): "--cassette-max-age", "--cassette-expired", "--cassette-report", + "--cassette-drift", "--agentverify-live", } - parser.addini.assert_called_once() + assert {c.args[0] for c in parser.addini.call_args_list} == {"agentverify_cassette_max_age", "agentverify_cassette_drift"} # First call: --cassette-mode first_call = parser.addoption.call_args_list[0] diff --git a/tests/test_record_missing.py b/tests/test_record_missing.py new file mode 100644 index 0000000..b7c1d2d --- /dev/null +++ b/tests/test_record_missing.py @@ -0,0 +1,63 @@ +"""--cassette-mode=record-missing: replay the cassettes that exist, record the ones that do not.""" + +from __future__ import annotations + +import pytest + +from agentverify.cassette.adapters.base import NormalizedRequest, NormalizedResponse +from agentverify.cassette.io import load_document, save_cassette +from agentverify.cassette.recorder import CassetteMode, LLMCassetteRecorder, _new_cassettes + +pytest_plugins = ["pytester"] + + +@pytest.fixture(autouse=True) +def _clear(): + _new_cassettes.clear() + yield + _new_cassettes.clear() + + +def test_the_recorder_replays_or_records(tmp_path): + existing = tmp_path / "existing.yaml" + save_cassette(existing, [(NormalizedRequest(messages=[], model="m"), NormalizedResponse(content="recorded"))], provider="openai") + with LLMCassetteRecorder(existing, mode=CassetteMode.RECORD_MISSING) as rec: + assert rec.mode == CassetteMode.REPLAY + assert rec.lookup(NormalizedRequest(messages=[], model="m")).content == "recorded" + missing = tmp_path / "missing.yaml" + with LLMCassetteRecorder(missing, mode=CassetteMode.RECORD_MISSING, sanitize=True) as rec: + assert rec.mode == CassetteMode.RECORD + rec.record(NormalizedRequest(messages=[{"role": "user", "content": "key sk-abcdefghijklmnopqrstuvwxyz0123"}], model="m"), NormalizedResponse(content="live")) + document = load_document(missing) + assert "sk-abcdefghijklmnopqrstuvwxyz0123" not in str(document) # sanitized like any recording + assert [path for path, _ in _new_cassettes] == [str(missing)] + + +def test_pytest_lists_the_new_cassettes(pytester): + pytester.makepyfile( + """ +from agentverify.cassette.adapters.base import NormalizedRequest, NormalizedResponse + +def test_one(cassette): + with cassette("one.yaml") as rec: + if rec.mode.value == "record": + rec.record(NormalizedRequest(messages=[], model="m"), NormalizedResponse(content="hi")) + else: + assert rec.lookup(NormalizedRequest(messages=[], model="m")).content == "hi" +""" + ) + first = pytester.runpytest_inprocess("-p", "agentverify", "--cassette-mode=record-missing") + first.assert_outcomes(passed=1) + assert "agentverify: new cassettes" in first.stdout.str() and "cassettes/one.yaml" in first.stdout.str() + second = pytester.runpytest_inprocess("-p", "agentverify", "--cassette-mode=record-missing") + second.assert_outcomes(passed=1) + assert "new cassettes" not in second.stdout.str() + + +def test_a_failed_recording_is_not_kept(tmp_path): + path = tmp_path / "cut.yaml" + with pytest.raises(RuntimeError): + with LLMCassetteRecorder(path, mode=CassetteMode.RECORD_MISSING) as rec: + rec.record(NormalizedRequest(messages=[], model="m"), NormalizedResponse(content="half")) + raise RuntimeError("rate limited") + assert not path.exists() and _new_cassettes == [] diff --git a/tests/test_request_texts.py b/tests/test_request_texts.py new file mode 100644 index 0000000..25d4d91 --- /dev/null +++ b/tests/test_request_texts.py @@ -0,0 +1,126 @@ +"""iter_request_texts: every text a request sends the model, with where it sits, across provider shapes.""" + +from __future__ import annotations + +import pytest + +from agentverify import MockLLM, iter_request_texts, mock_response +from agentverify.cassette.adapters.base import NormalizedRequest, NormalizedResponse +from agentverify.cassette.io import save_cassette +from agentverify.cassette.recorder import CassetteMode, LLMCassetteRecorder + + +def _texts(request): + return dict(iter_request_texts(request)) + + +def test_openai_and_litellm_shapes(): + request = NormalizedRequest( + model="m", + messages=[ + {"role": "system", "content": "be brief"}, + {"role": "user", "content": "weather?"}, + {"role": "assistant", "content": None, "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "get_weather", "arguments": '{"city": "Tokyo"}'}}]}, + {"role": "tool", "tool_call_id": "c1", "content": '{"temp": 22, "url": "data:image/png;base64,AAAA"}'}, + {"role": "user", "content": [{"type": "text", "text": "and?"}, {"type": "image_url", "image_url": {"url": "https://x/a.png?sig=1"}}]}, + ], + tools=[{"name": "get_weather", "description": "Weather.", "parameters": {"properties": {"unit": {"enum": ["C", 1]}}}}], + parameters={"temperature": 0.2, "instructions": "be kind"}, + ) + texts = _texts(request) + assert texts["request[0].message[0](system).text"] == "be brief" + assert texts["request[0].message[2](assistant).tool_call[0](get_weather).arguments.city"] == "Tokyo" + assert texts["request[0].message[3](tool).tool_result[0](get_weather).temp"] == "22" + assert "request[0].message[3](tool).tool_result[0](get_weather).url" not in texts # an embedded image + assert texts["request[0].message[4](user).content[1].image_url.url"] == "https://x/a.png?sig=1" + assert texts["request[0].tool[get_weather].description"] == "Weather." and texts["request[0].tool[get_weather].schema.properties.unit.enum[1]"] == "1" + assert texts["request[0].parameters.temperature"] == "0.2" and texts["request[0].system"] == "be kind" + assert not any(t == "c1" for t in texts.values()) # ids are not text the agent sent + + +def test_anthropic_bedrock_and_gemini_shapes(): + anthropic = NormalizedRequest(model="m", messages=[ + {"role": "assistant", "content": [{"type": "thinking", "thinking": "hmm", "signature": "SIG"}, {"type": "tool_use", "id": "t1", "name": "add", "input": {"a": 1}}]}, + {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": [{"type": "text", "text": "2"}]}]}, + ], parameters={"system": [{"type": "text", "text": "sys"}]}) + texts = _texts(anthropic) + assert texts["request[0].message[0](assistant).tool_call[0](add).arguments.a"] == "1" + assert texts["request[0].message[1](user).tool_result[0](add)[0].text"] == "2" + assert texts["request[0].message[0](assistant).content[0].thinking"] == "hmm" and "SIG" not in texts.values() + assert texts["request[0].system[0].text"] == "sys" + + bedrock = NormalizedRequest(model="m", messages=[ + {"role": "assistant", "content": [{"reasoningContent": {"reasoningText": {"text": "think", "signature": "S"}}}, {"toolUse": {"toolUseId": "u1", "name": "f", "input": {"q": "x"}}}]}, + {"role": "user", "content": [{"toolResult": {"toolUseId": "u1", "content": [{"json": {"k": "v"}}], "status": "success"}}, {"image": {"format": "png", "source": {"bytes": "AAAA"}}}]}, + ]) + texts = _texts(bedrock) + assert texts["request[0].message[0](assistant).tool_call[0](f).arguments.q"] == "x" + assert texts["request[0].message[1](user).tool_result[0](f)[0].json.k"] == "v" + assert "S" not in texts.values() and "AAAA" not in texts.values() + + gemini = NormalizedRequest(model="m", messages=[ + {"role": "model", "parts": [{"function_call": {"name": "f", "args": {"q": "y"}}}, "plain"]}, + {"role": "user", "parts": [{"function_response": {"name": "f", "response": {"r": "z"}}}, {"text": "go"}]}, + ], parameters={"system_instruction": {"parts": [{"text": "sys"}]}}) + texts = _texts(gemini) + assert texts["request[0].message[0](model).tool_call[0](f).arguments.q"] == "y" and texts["request[0].message[0](model).content[1]"] == "plain" + assert texts["request[0].message[1](user).tool_result[0](f).r"] == "z" and texts["request[0].message[1](user).content[1].text"] == "go" + assert texts["request[0].system.parts[0].text"] == "sys" + + +def test_responses_api_items_and_odd_values(): + request = NormalizedRequest(model="m", messages=[ + {"type": "function_call", "call_id": "c9", "name": "lookup", "arguments": '{"k": "v"}'}, + {"type": "function_call_output", "call_id": "c9", "output": "found"}, + {"type": "reasoning", "summary": [{"text": "s"}], "encrypted_content": "ENC"}, + "a bare string", + {"role": "tool", "tool_call_id": "unknown", "content": "x"}, + ], tools=[{"type": "function", "function": {"name": "lookup", "parameters": {"type": "object"}}}, {"toolSpec": {"name": "b", "inputSchema": {"json": {}}}}, "odd", {"name": "c", "strict": True, "parameters": "{not json"}]) + texts = _texts(request) + assert texts["request[0].message[0](function_call).tool_call[0](lookup).arguments.k"] == "v" + assert texts["request[0].message[1](function_call_output).tool_result[0](lookup)"] == "found" + assert texts["request[0].message[2](reasoning).summary[0].text"] == "s" and "ENC" not in texts.values() + assert texts["request[0].message[3]"] == "a bare string" and texts["request[0].message[4](tool).tool_result[0](?)"] == "x" + assert texts["request[0].tool[lookup].schema.type"] == "object" and texts["request[0].tool[b].name"] == "b" + assert texts["request[0].tool"] == "odd" and texts["request[0].tool[c].strict"] == "True" and texts["request[0].tool[c].schema"] == "{not json" + + +def test_sources(tmp_path): + request = NormalizedRequest(model="m", messages=[{"role": "user", "content": "hi"}]) + path = tmp_path / "c.yaml" + save_cassette(path, [(request, NormalizedResponse(content="ok"))], provider="openai") + assert list(iter_request_texts(path)) == list(iter_request_texts(str(path))) == [("request[0].message[0](user).text", "hi")] + with LLMCassetteRecorder(path, mode=CassetteMode.REPLAY) as rec: + rec.lookup(request) + assert list(iter_request_texts(rec)) == [("request[0].message[0](user).text", "hi")] + mock = MockLLM([mock_response(content="x")], provider="openai") + mock.lookup(request) + assert list(iter_request_texts(mock)) == [("request[0].message[0](user).text", "hi")] + with pytest.raises(TypeError, match="cassette path"): + list(iter_request_texts(object())) + + +def test_malformed_tool_calls_are_skipped(): + request = NormalizedRequest(model="m", messages=[{"role": "assistant", "tool_calls": ["bad", {"function": "x"}], "content": ["text", 3]}]) + assert _texts(request) == {"request[0].message[0](assistant).content[0]": "text", "request[0].message[0](assistant).content[1]": "3"} + + +def test_review_fixes(): + """Payload keys named like envelope fields, SDK objects, and OpenAI tool messages with parts.""" + from dataclasses import dataclass + + @dataclass + class Part: + type: str + text: str + + request = NormalizedRequest(model="m", messages=[ + {"role": "assistant", "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "dl", "arguments": '{"id": 7}'}}]}, + {"role": "tool", "tool_call_id": "c1", "content": [{"type": "text", "text": '{"data": {"download": "https://s3/x?sig=1"}}'}]}, + {"role": "user", "content": [Part("text", "from an SDK object")]}, + ], tools=[{"name": "dl", "parameters": {"properties": {"id": {"type": "string"}}}}]) + texts = _texts(request) + assert texts["request[0].message[0](assistant).tool_call[0](dl).arguments.id"] == "7" + assert texts["request[0].message[1](tool).tool_result[0](dl)[0].text.data.download"] == "https://s3/x?sig=1" + assert texts["request[0].message[2](user).content[0].text"] == "from an SDK object" + assert texts["request[0].tool[dl].schema.properties.id.type"] == "string"