mirror of
https://github.com/anthropics/skills
synced 2026-12-03 04:10:48 +00:00
Compare commits
2 Commits
dbd4588f9e
...
rlm/claude
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1e242283a1 | ||
|
|
22442b1335 |
@@ -32,7 +32,7 @@ Never mix the two - don't reach for `requests`/`fetch` in a Python or TypeScript
|
|||||||
|
|
||||||
Unless the user requests otherwise:
|
Unless the user requests otherwise:
|
||||||
|
|
||||||
For the Claude model version, please use Claude Opus 5, which you can access via the exact model string `claude-opus-5`. Please default to using adaptive thinking (`thinking: {type: "adaptive"}`) for anything remotely complicated. And finally, please default to streaming for any request that may involve long input, long output, or high `max_tokens` - it prevents hitting request timeouts. Use the SDK's `.get_final_message()` / `.finalMessage()` helper to get the complete response if you don't need to handle individual stream events
|
For the Claude model version, please use Claude Opus 5, which you can access via the exact model string `claude-opus-5`. Please default to using adaptive thinking (`thinking: {type: "adaptive"}`) for anything remotely complicated. And finally, please default to streaming for any request that may involve long input, long output, or high `max_tokens` - it prevents hitting request timeouts. Use the SDK's `.get_final_message()` / `.finalMessage()` helper to get the complete response if you don't need to handle individual stream events. When a streaming request defines user-defined (client) tools, set `eager_input_streaming: true` on each of those tools so large tool inputs (file contents, code, documents) stream as they are generated instead of arriving in one burst after the server finishes buffering them; the client then owns validation: the SDKs' tolerant parsers can return a silently truncated input instead of raising, so validate each parsed tool input against its schema before running it (the typed runner helpers such as `betaZodTool` / typed `@beta_tool` do this; `betaTool()` JSON-Schema tools and manual loops must validate themselves), treat a failure like invalid JSON (`INVALID_JSON` error `tool_result` when you hold the block, re-issue otherwise), check `max_tokens` / `refusal` stop reasons before running tools, and catch only the SDK's JSON error, never its typed API errors - pattern in `shared/tool-use-concepts.md` -> Eager input streaming. Leave it off for non-streaming requests, for server tools, and when the request goes through a proxy or an older Bedrock model deployment that rejects the field.
|
||||||
|
|
||||||
## Warning: API Drift - Your Training Prior May Be Stale
|
## Warning: API Drift - Your Training Prior May Be Stale
|
||||||
|
|
||||||
@@ -60,6 +60,8 @@ If the User Request at the bottom of this prompt is a bare subcommand string (no
|
|||||||
| `prompt-audit` | Audit existing prompts, skills, and tool descriptions for dated patterns ("cruft") written for older models. **Read `shared/prompt-audit.md` immediately** and follow it in order: Step 0 (establish scope and target model from the request and the repository - state the assumptions in the report, do not stop to ask), inventory, provenance, then the pattern scan. Produce both deliverables in full - the audit report (findings with `file:line`, pattern, why it's obsolete for the target model, confidence) and a proposed diff - without pausing for confirmation; apply edits only if the request explicitly asked for them. Do not summarize the guide - execute it. |
|
| `prompt-audit` | Audit existing prompts, skills, and tool descriptions for dated patterns ("cruft") written for older models. **Read `shared/prompt-audit.md` immediately** and follow it in order: Step 0 (establish scope and target model from the request and the repository - state the assumptions in the report, do not stop to ask), inventory, provenance, then the pattern scan. Produce both deliverables in full - the audit report (findings with `file:line`, pattern, why it's obsolete for the target model, confidence) and a proposed diff - without pausing for confirmation; apply edits only if the request explicitly asked for them. Do not summarize the guide - execute it. |
|
||||||
| `upgrade` | Upgrade the project's Anthropic SDK dependency across a major version - currently the Python SDK, `anthropic` 0.x -> 1.x. Trailing words may name the language and/or a scope (`upgrade python`, `upgrade python sdk src/`). **Read `python/claude-api/sdk-upgrade.md` immediately** and follow it in order: Step 0 (confirm scope, then establish the current and target versions - a published 1.x must exist before you write a pin), the Step 1 inventory, each numbered section, then verification and the report. Do not summarize the guide - execute it. If the detected or named language has no `sdk-upgrade.md` in this skill, say that no major-version upgrade guide is bundled for that SDK yet and point the user at that SDK's CHANGELOG (repositories in `shared/live-sources.md`); do not improvise one from the Python guide. This is not model migration - to move code to a newer Claude model, use `migrate`. |
|
| `upgrade` | Upgrade the project's Anthropic SDK dependency across a major version - currently the Python SDK, `anthropic` 0.x -> 1.x. Trailing words may name the language and/or a scope (`upgrade python`, `upgrade python sdk src/`). **Read `python/claude-api/sdk-upgrade.md` immediately** and follow it in order: Step 0 (confirm scope, then establish the current and target versions - a published 1.x must exist before you write a pin), the Step 1 inventory, each numbered section, then verification and the report. Do not summarize the guide - execute it. If the detected or named language has no `sdk-upgrade.md` in this skill, say that no major-version upgrade guide is bundled for that SDK yet and point the user at that SDK's CHANGELOG (repositories in `shared/live-sources.md`); do not improvise one from the Python guide. This is not model migration - to move code to a newer Claude model, use `migrate`. |
|
||||||
| `cost-optimize` | Reduce what existing Claude API code costs to run, without sacrificing output quality. **Read `shared/cost-optimization.md` immediately** and follow it in order: Step 0 (establish scope, quality bar, and baseline), the token profile - measured through the Usage and Cost Admin API when the user has an Admin API key, from the app's own `response.usage` logs when it has those (ask), or estimated from the code otherwise - then a savings-ranked shortlist of levers (quoted in dollars, % of bill, or relative buckets depending on which of those data sources you have), free wins (caching, input-token hygiene, loop hygiene, output-token hygiene, batch) before tradeoffs (budgets, effort, model choice, multi-model); any lever that earns a place becomes its own diff - proposed by default, applied and measured against the eval covering the traffic it touches when the user asks and approves - and "no changes recommended" is a valid outcome. Two standing rules: every run that exercises the model spends real money, so get the user's approval first; and when context for a lever is missing, work through it interactively with the user - this workflow is not expected to one-shot the audit. Do not summarize the guide - execute it; presenting the profile and the ranked plan to the user is part of executing it. |
|
| `cost-optimize` | Reduce what existing Claude API code costs to run, without sacrificing output quality. **Read `shared/cost-optimization.md` immediately** and follow it in order: Step 0 (establish scope, quality bar, and baseline), the token profile - measured through the Usage and Cost Admin API when the user has an Admin API key, from the app's own `response.usage` logs when it has those (ask), or estimated from the code otherwise - then a savings-ranked shortlist of levers (quoted in dollars, % of bill, or relative buckets depending on which of those data sources you have), free wins (caching, input-token hygiene, loop hygiene, output-token hygiene, batch) before tradeoffs (budgets, effort, model choice, multi-model); any lever that earns a place becomes its own diff - proposed by default, applied and measured against the eval covering the traffic it touches when the user asks and approves - and "no changes recommended" is a valid outcome. Two standing rules: every run that exercises the model spends real money, so get the user's approval first; and when context for a lever is missing, work through it interactively with the user - this workflow is not expected to one-shot the audit. Do not summarize the guide - execute it; presenting the profile and the ranked plan to the user is part of executing it. |
|
||||||
|
| `build-eval` | Help the user build an eval set for their Claude-powered app. **Read `shared/evals/build-eval.md` immediately** and run its interview: Step 0 (what's being evaluated), Step 1 (source the prompts - existing eval / transcripts / synthesized), Step 2 (grading method), Step 3 (runnable script + measured cost). Get the user's explicit sign-off on the inputs, the grading method, and the cost before producing the eval. |
|
||||||
|
| `hillclimb` | Iteratively improve the user's app against an existing eval. **Read `shared/evals/eval-hillclimb.md` immediately** and follow it: Step 0 (confirm a runnable eval exists - if not, route to `build-eval`), Step 1 (what to change / what's off-limits), Step 2 (budget + stopping condition from measured per-run cost), get the plan approved, then the read->propose->apply->run->record loop with on-disk state and a train/validation/test split. |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -69,31 +71,31 @@ Before reading code examples, determine which language the user is working in (e
|
|||||||
|
|
||||||
1. **Look at project files** to infer the language:
|
1. **Look at project files** to infer the language:
|
||||||
|
|
||||||
- `*.py`, `requirements.txt`, `pyproject.toml`, `setup.py`, `Pipfile` -> **Python** - read from `python/`
|
- `*.py`, `requirements.txt`, `pyproject.toml`, `setup.py`, `Pipfile` -> **Python** - read from `python/`
|
||||||
- `*.ts`, `*.tsx`, `package.json`, `tsconfig.json` -> **TypeScript** - read from `typescript/`
|
- `*.ts`, `*.tsx`, `package.json`, `tsconfig.json` -> **TypeScript** - read from `typescript/`
|
||||||
- `*.js`, `*.jsx` (no `.ts` files present) -> **TypeScript** - JS uses the same SDK, read from `typescript/`
|
- `*.js`, `*.jsx` (no `.ts` files present) -> **TypeScript** - JS uses the same SDK, read from `typescript/`
|
||||||
- `*.java`, `pom.xml`, `build.gradle` -> **Java** - read from `java/`
|
- `*.java`, `pom.xml`, `build.gradle` -> **Java** - read from `java/`
|
||||||
- `*.kt`, `*.kts`, `build.gradle.kts` -> **Java** - Kotlin uses the Java SDK, read from `java/`
|
- `*.kt`, `*.kts`, `build.gradle.kts` -> **Java** - Kotlin uses the Java SDK, read from `java/`
|
||||||
- `*.scala`, `build.sbt` -> **Java** - Scala uses the Java SDK, read from `java/`
|
- `*.scala`, `build.sbt` -> **Java** - Scala uses the Java SDK, read from `java/`
|
||||||
- `*.go`, `go.mod` -> **Go** - read from `go/`
|
- `*.go`, `go.mod` -> **Go** - read from `go/`
|
||||||
- `*.rb`, `Gemfile` -> **Ruby** - read from `ruby/`
|
- `*.rb`, `Gemfile` -> **Ruby** - read from `ruby/`
|
||||||
- `*.cs`, `*.csproj` -> **C#** - read from `csharp/`
|
- `*.cs`, `*.csproj` -> **C#** - read from `csharp/`
|
||||||
- `*.php`, `composer.json` -> **PHP** - read from `php/`
|
- `*.php`, `composer.json` -> **PHP** - read from `php/`
|
||||||
|
|
||||||
2. **If multiple languages detected** (e.g., both Python and TypeScript files):
|
2. **If multiple languages detected** (e.g., both Python and TypeScript files):
|
||||||
|
|
||||||
- Check which language the user's current file or question relates to
|
- Check which language the user's current file or question relates to
|
||||||
- If still ambiguous, ask: "I detected both Python and TypeScript files. Which language are you using for the Claude API integration?"
|
- If still ambiguous, ask: "I detected both Python and TypeScript files. Which language are you using for the Claude API integration?"
|
||||||
|
|
||||||
3. **If language can't be inferred** (empty project, no source files, or unsupported language):
|
3. **If language can't be inferred** (empty project, no source files, or unsupported language):
|
||||||
|
|
||||||
- Use AskUserQuestion with options: Python, TypeScript, Java, Go, Ruby, cURL/raw HTTP, C#, PHP
|
- Use AskUserQuestion with options: Python, TypeScript, Java, Go, Ruby, cURL/raw HTTP, C#, PHP
|
||||||
- If AskUserQuestion is unavailable, default to Python examples and note: "Showing Python examples. Let me know if you need a different language."
|
- If AskUserQuestion is unavailable, default to Python examples and note: "Showing Python examples. Let me know if you need a different language."
|
||||||
|
|
||||||
4. **If unsupported language detected** (Rust, Swift, C++, Elixir, etc.):
|
4. **If unsupported language detected** (Rust, Swift, C++, Elixir, etc.):
|
||||||
|
|
||||||
- Suggest cURL/raw HTTP examples from `curl/` and note that community SDKs may exist
|
- Suggest cURL/raw HTTP examples from `curl/` and note that community SDKs may exist
|
||||||
- Offer to show Python or TypeScript examples as reference implementations
|
- Offer to show Python or TypeScript examples as reference implementations
|
||||||
|
|
||||||
5. **If user needs cURL/raw HTTP examples**, read from `curl/`.
|
5. **If user needs cURL/raw HTTP examples**, read from `curl/`.
|
||||||
|
|
||||||
@@ -119,6 +121,7 @@ Every SDK language above supports both the beta Tool Runner and Managed Agents (
|
|||||||
| Persisted, versioned agent configs | Agent | **Managed Agents** | Agents are stored objects; sessions pin to a version |
|
| Persisted, versioned agent configs | Agent | **Managed Agents** | Agents are stored objects; sessions pin to a version |
|
||||||
| Long-running multi-turn agent with file mounts | Agent | **Managed Agents** | Per-session containers, SSE event stream, Skills + MCP |
|
| Long-running multi-turn agent with file mounts | Agent | **Managed Agents** | Per-session containers, SSE event stream, Skills + MCP |
|
||||||
| Agent that runs on a schedule (cron, "every night") | Agent | **Managed Agents** - scheduled deployments | Deployments fire sessions autonomously; no client-side scheduler |
|
| Agent that runs on a schedule (cron, "every night") | Agent | **Managed Agents** - scheduled deployments | Deployments fire sessions autonomously; no client-side scheduler |
|
||||||
|
| Agent work that must meet a quality bar ("until it's right") | Agent | **Managed Agents** - outcomes | A separate grader iterates the agent against your rubric until it passes |
|
||||||
|
|
||||||
> **Note:** Managed Agents is the right choice when you want Anthropic to run the agent loop *and* host the container where tools execute - file ops, bash, code execution all run in the per-session workspace. If you want to host the compute yourself or run your own custom tool runtime, Claude API + tool use is the right choice - use the tool runner for the agentic loop - its per-turn hooks still give you approval gates, logging, error interception, and conditional execution (see `shared/tool-use-concepts.md`) - or the manual loop when you want to own the entire loop yourself.
|
> **Note:** Managed Agents is the right choice when you want Anthropic to run the agent loop *and* host the container where tools execute - file ops, bash, code execution all run in the per-session workspace. If you want to host the compute yourself or run your own custom tool runtime, Claude API + tool use is the right choice - use the tool runner for the agentic loop - its per-turn hooks still give you approval gates, logging, error interception, and conditional execution (see `shared/tool-use-concepts.md`) - or the manual loop when you want to own the entire loop yourself.
|
||||||
|
|
||||||
@@ -179,6 +182,7 @@ Everything goes through `POST /v1/messages`. Tools and output constraints are fe
|
|||||||
| Claude Fable 5.1 | `claude-fable-5-1` | 1M | $10.00 | $50.00 |
|
| Claude Fable 5.1 | `claude-fable-5-1` | 1M | $10.00 | $50.00 |
|
||||||
| Claude Mythos 5.1 (Project Glasswing only) | `claude-mythos-5-1` | 1M | $10.00 | $50.00 |
|
| Claude Mythos 5.1 (Project Glasswing only) | `claude-mythos-5-1` | 1M | $10.00 | $50.00 |
|
||||||
| Claude Fable 5 | `claude-fable-5` | 1M | $10.00 | $50.00 |
|
| Claude Fable 5 | `claude-fable-5` | 1M | $10.00 | $50.00 |
|
||||||
|
| Claude Opus 5.5 (launching - use only when the user names it) | `claude-opus-5-5` | 1M | $4.00 | $20.00 |
|
||||||
| Claude Opus 5 | `claude-opus-5` | 1M | $5.00 | $25.00 |
|
| Claude Opus 5 | `claude-opus-5` | 1M | $5.00 | $25.00 |
|
||||||
| Claude Opus 4.8 | `claude-opus-4-8` | 1M | $5.00 | $25.00 |
|
| Claude Opus 4.8 | `claude-opus-4-8` | 1M | $5.00 | $25.00 |
|
||||||
| Claude Opus 4.7 | `claude-opus-4-7` | 1M | $5.00 | $25.00 |
|
| Claude Opus 4.7 | `claude-opus-4-7` | 1M | $5.00 | $25.00 |
|
||||||
@@ -189,7 +193,7 @@ Everything goes through `POST /v1/messages`. Tools and output constraints are fe
|
|||||||
|
|
||||||
**Partner pricing:** The prices above are Anthropic first-party API rates - they also apply to Claude on Microsoft Foundry, which is billed through the Microsoft Marketplace at standard API rates. Claude on Amazon Bedrock and Vertex AI is partner-operated with separate pricing - see [Bedrock](https://aws.amazon.com/bedrock/pricing/) or [Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/pricing#claude-models). For WebFetch, use the Pricing row in `shared/live-sources.md`.
|
**Partner pricing:** The prices above are Anthropic first-party API rates - they also apply to Claude on Microsoft Foundry, which is billed through the Microsoft Marketplace at standard API rates. Claude on Amazon Bedrock and Vertex AI is partner-operated with separate pricing - see [Bedrock](https://aws.amazon.com/bedrock/pricing/) or [Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/pricing#claude-models). For WebFetch, use the Pricing row in `shared/live-sources.md`.
|
||||||
|
|
||||||
**ALWAYS use `claude-opus-5` unless the user explicitly names a different model.** This is non-negotiable. Do not use `claude-sonnet-5`, `claude-sonnet-4-6`, or any other model unless the user literally says "use sonnet" or "use haiku". Never downgrade for cost - that's the user's decision, not yours. Use `claude-fable-5-1` only when the user explicitly asks for Claude Fable 5.1, "fable", or Anthropic's most capable model - it has different API behavior than the Opus family (see below) and pricing that exceeds Opus-tier. **Use only the exact model ID strings from the table - they are complete as-is; never append date suffixes** (`claude-sonnet-4-6`, never `claude-sonnet-4-6-20251114` or any other date-suffixed variant you might recall from training data). If the user requests an older model not in the table (e.g., "opus 4.5", "sonnet 3.7"), read `shared/models.md` for the exact ID - do not construct one yourself.
|
**ALWAYS use `claude-opus-5` unless the user explicitly names a different model.** This is non-negotiable. Do not use `claude-sonnet-5`, `claude-sonnet-4-6`, or any other model unless the user literally says "use sonnet" or "use haiku". Never downgrade for cost - that's the user's decision, not yours. Where a second, cheaper model is in play alongside the main one (worker or sub-agent threads, bulk extractors, LLM judges, the executor under an advisor) - because the user asked for one or a guide in this skill calls for it - or the user says "sonnet" or "haiku" without a version, that means the current generation from the table above (`claude-sonnet-5`, `claude-haiku-4-5`); previous-generation IDs such as `claude-sonnet-4-6` are only for users who name that version. Use `claude-fable-5-1` only when the user explicitly asks for Claude Fable 5.1, "fable", or Anthropic's most capable model - it has different API behavior than the Opus family (see below) and pricing that exceeds Opus-tier. **Use only the exact model ID strings from the table - they are complete as-is; never append date suffixes** (`claude-opus-5`, never `claude-opus-5-20260401` or any other date-suffixed variant you might recall from training data). If the user requests an older model not in the table (e.g., "opus 4.5", "sonnet 3.7"), read `shared/models.md` for the exact ID - do not construct one yourself.
|
||||||
|
|
||||||
### Claude Fable 5.1 (`claude-fable-5-1`) - most capable widely released model
|
### Claude Fable 5.1 (`claude-fable-5-1`) - most capable widely released model
|
||||||
|
|
||||||
@@ -202,7 +206,11 @@ Claude Fable 5.1 is Anthropic's most capable widely released model, for the most
|
|||||||
- **No assistant prefill** - same as the rest of the 4.6+ family.
|
- **No assistant prefill** - same as the rest of the 4.6+ family.
|
||||||
- **30-day data retention required** - Claude Fable 5.1 is not available under zero data retention unless expressly authorized by Anthropic; requests from an org whose retention configuration doesn't meet the requirement return `400 invalid_request_error`.
|
- **30-day data retention required** - Claude Fable 5.1 is not available under zero data retention unless expressly authorized by Anthropic; requests from an org whose retention configuration doesn't meet the requirement return `400 invalid_request_error`.
|
||||||
- **Longer turns, different prompting** - single requests on hard tasks can run many minutes (plan timeouts/streaming/progress UX); effort sweeps should include low/medium for routine work; prompts written for prior models are often too prescriptive and reduce output quality. See `shared/model-migration.md` -> Migrating to Claude Fable 5.1 -> Behavioral shifts (prompt-tunable) for the recommended prompt snippets.
|
- **Longer turns, different prompting** - single requests on hard tasks can run many minutes (plan timeouts/streaming/progress UX); effort sweeps should include low/medium for routine work; prompts written for prior models are often too prescriptive and reduce output quality. See `shared/model-migration.md` -> Migrating to Claude Fable 5.1 -> Behavioral shifts (prompt-tunable) for the recommended prompt snippets.
|
||||||
- **Successor to Claude Fable 5 (`claude-fable-5`, still served) in the same tier at the same per-token price.** Same surface as Claude Fable 5 with three breaking changes - forced tool use (`tool_choice` `any` / `tool`) returns a 400 (use `auto` + a prompt instruction, `strict: true` for schema-valid arguments, or structured outputs); thinking blocks are bound to the producing model (other models drop them, unbilled); and editing earlier turns invalidates thinking blocks ("preserved thinking"; new accounts created on/after 2026-08-31 get a 400 on edited history; later models enforce it for everyone - make every harness append-only and run the three-step check; the opt-in controls are per-platform, see `shared/platform-availability.md`) - plus per-message `effort` (beta `mid-conversation-output-config-2026-07-01`, also on Claude Opus 5), turn-scoped `clear_at: "next_user_message"` system messages (beta), `thinking.display: "updates"` progress notes (beta, all platforms), cache reads at $0.25/MTok (whether Claude Mythos 5.1 shares that rate is open at launch), and content provenance. Covered Model - ZDR orgs get `400 invalid_request_error` as on Claude Fable 5 (ZDR only if expressly authorized by Anthropic); no Priority Tier. Same tokenizer as Claude Fable 5. See `shared/model-migration.md` -> Migrating to Claude Fable 5.1 from Claude Fable 5.
|
- **Successor to Claude Fable 5 (`claude-fable-5`, still served) in the same tier at the same per-token price.** Same surface as Claude Fable 5 with three breaking changes - forced tool use (`tool_choice` `any` / `tool`) returns a 400 (use `auto` + a prompt instruction, `strict: true` for schema-valid arguments, or structured outputs); thinking blocks are bound to the producing model (other models drop them, unbilled); and editing earlier turns invalidates thinking blocks ("preserved thinking"; new accounts created on/after 2026-08-31 get a 400 on edited history on every platform, and enforcement scope is decided per model - make every harness append-only and run the three-step check; the opt-in controls are per-platform, see `shared/platform-availability.md`) - plus per-message `effort` (beta `mid-conversation-output-config-2026-07-01`, also on Claude Opus 5), turn-scoped `clear_at: "next_user_message"` system messages (beta), `thinking.display: "updates"` progress notes (beta, all platforms), cache reads at $0.25/MTok (whether Claude Mythos 5.1 shares that rate is open at launch), and content provenance. Covered Model - ZDR orgs get `400 invalid_request_error` as on Claude Fable 5 (ZDR only if expressly authorized by Anthropic); no Priority Tier. Same tokenizer as Claude Fable 5. See `shared/model-migration.md` -> Migrating to Claude Fable 5.1 from Claude Fable 5.
|
||||||
|
|
||||||
|
### Claude Opus 5.5 (`claude-opus-5-5`) - the next Opus, launching; use only when the user names it
|
||||||
|
|
||||||
|
Successor to Claude Opus 5 in the Opus line at a lower price ($4 / $20 per MTok, cache reads $0.20), same 1M context / 128K output / tokenizer / feature set. Four breaking changes for code running on Claude Opus 5: **thinking can't be disabled** (`{type: "disabled"}` and `budget_tokens` both 400 at every effort level - effort is the only control, and its **default is `medium`**, one level below Claude Opus 5's `high`, so set it explicitly); **forced `tool_choice` `any`/`tool` returns a 400** (use `auto` + `strict: true` and steer from the prompt, or structured outputs); **thinking blocks are tied to the model and the conversation** (preserved thinking: only Claude Fable 5.1 / Claude Mythos 5.1 on the Claude API read its blocks, so a fallback to Claude Opus 5 runs without them; accounts created on or after 2026-08-31 are enforced on the history-editing check); and **computer use only through `computer_toolset_20260801`** (`computer_20251124` 400s). Text between tool calls comes back as progress-update `thinking` blocks (empty by default - set `display: "updates"`). Broader safety classifiers: `bio` and `reasoning_extraction` join `cyber`. Fast mode is Claude API only, $8 / $40 per MTok (2x standard). See `shared/model-migration.md` -> Migrating to Claude Opus 5.5.
|
||||||
|
|
||||||
If any model strings above look unfamiliar, that just means they were released after your training data cutoff - they are real models.
|
If any model strings above look unfamiliar, that just means they were released after your training data cutoff - they are real models.
|
||||||
|
|
||||||
@@ -227,16 +235,17 @@ Full auth details (named profiles, scopes, the API-key-shadows-profile trap, ref
|
|||||||
|
|
||||||
## Thinking & Effort (Quick Reference)
|
## Thinking & Effort (Quick Reference)
|
||||||
|
|
||||||
Use adaptive thinking (`thinking: {type: "adaptive"}`) on every current model - Claude dynamically decides when and how much to think. Per-model rules:
|
Use adaptive thinking (`thinking: {type: "adaptive"}`) on every current model except Haiku 4.5, which still takes `budget_tokens` (table below) - Claude dynamically decides when and how much to think. Per-model rules:
|
||||||
|
|
||||||
| Model | Thinking config | Omitting `thinking` | `budget_tokens` | Sampling (`temperature`/`top_p`/`top_k`) | Effort levels |
|
| Model | Thinking config | Omitting `thinking` | `budget_tokens` | Sampling (`temperature`/`top_p`/`top_k`) | Effort levels |
|
||||||
|---|---|---|---|---|---|
|
|---|---|---|---|---|---|
|
||||||
| Fable 5 / Claude Fable 5.1 (and the Mythos counterparts) | `{type: "adaptive"}` or omit; explicit `{type: "disabled"}` returns 400 - omit the param instead (Claude Fable 5.1 / Claude Mythos 5.1 also 400 on forced `tool_choice` `any`/`tool`, and run preserved thinking's history-editing check on replayed thinking blocks) | Runs adaptive (thinking is always on) | Removed - `{type: "enabled", budget_tokens: N}` returns 400 | Removed - 400 | `low`/`medium`/`high`/`xhigh`/`max` |
|
| Fable 5 / Claude Fable 5.1 (and the Mythos counterparts) | `{type: "adaptive"}` or omit; explicit `{type: "disabled"}` returns 400 - omit the param instead (Claude Fable 5.1 / Claude Mythos 5.1 also 400 on forced `tool_choice` `any`/`tool`, and run preserved thinking's history-editing check on replayed thinking blocks) | Runs adaptive (thinking is always on) | Removed - `{type: "enabled", budget_tokens: N}` returns 400 | Removed - 400 | `low`/`medium`/`high`/`xhigh`/`max` |
|
||||||
|
| Claude Opus 5.5 | `{type: "adaptive"}` or omit; `{type: "disabled"}` and `{type: "enabled", budget_tokens}` return 400 at **every** effort level - omit the param and lower effort instead (also 400s on forced `tool_choice` `any`/`tool`, and runs preserved thinking - see `shared/model-migration.md` -> Migrating to Claude Opus 5.5) | Runs **adaptive** | Removed - 400 | Removed - 400 | `low`/`medium`/`high`/`xhigh`/`max` - **default `medium`** (not `high`); per-message effort (beta) supported |
|
||||||
| Claude Opus 5 | `{type: "adaptive"}` or omit; `{type: "disabled"}` accepted **only at effort `high` or below** - 400 at `xhigh`/`max`, and see the disabled-thinking pitfall below | Runs **adaptive** (thinking is on by default - unlike Opus 4.8/4.7) | Removed - 400 | Removed - 400 | `low`-`max` (all five) |
|
| Claude Opus 5 | `{type: "adaptive"}` or omit; `{type: "disabled"}` accepted **only at effort `high` or below** - 400 at `xhigh`/`max`, and see the disabled-thinking pitfall below | Runs **adaptive** (thinking is on by default - unlike Opus 4.8/4.7) | Removed - 400 | Removed - 400 | `low`-`max` (all five) |
|
||||||
| Opus 4.8 / 4.7 | `{type: "adaptive"}` is the only on-mode; `{type: "disabled"}` accepted | Runs **without** thinking - set `{type: "adaptive"}` explicitly | Removed - 400 | Removed - 400 | `low`/`medium`/`high`/`xhigh`/`max` |
|
| Opus 4.8 / 4.7 | `{type: "adaptive"}` is the only on-mode; `{type: "disabled"}` accepted | Runs **without** thinking - set `{type: "adaptive"}` explicitly | Removed - 400 | Removed - 400 | `low`/`medium`/`high`/`xhigh`/`max` |
|
||||||
| Sonnet 5 | `{type: "adaptive"}` is the only on-mode; `{type: "disabled"}` accepted | Runs adaptive | Removed - 400 | Removed - 400 | `low`/`medium`/`high`/`xhigh`/`max` |
|
| Sonnet 5 | `{type: "adaptive"}` is the only on-mode; `{type: "disabled"}` accepted | Runs adaptive | Removed - 400 | Removed - 400 | `low`/`medium`/`high`/`xhigh`/`max` |
|
||||||
| Opus 4.6 / Sonnet 4.6 | `{type: "adaptive"}` (recommended; auto-enables interleaved thinking, no beta header) | Set `{type: "adaptive"}` explicitly | Deprecated - do not use in new code; transitional escape hatch only (see below) | Allowed | `low`/`medium`/`high`/`max` (`xhigh` arrived with Opus 4.7) |
|
| Opus 4.6 / Sonnet 4.6 | `{type: "adaptive"}` (recommended; auto-enables interleaved thinking, no beta header) | Set `{type: "adaptive"}` explicitly | Deprecated - do not use in new code; transitional escape hatch only (see below) | Allowed | `low`/`medium`/`high`/`max` (`xhigh` arrived with Opus 4.7) |
|
||||||
| Older (Sonnet 4.5, Haiku 4.5, ...) - only if explicitly requested | `{type: "enabled", budget_tokens: N}` | No thinking | Required for thinking; must be less than `max_tokens`, minimum 1024 - errors otherwise | Allowed | `effort` works on Opus 4.5 (`low`/`medium`/`high` only - no `xhigh`/`max`); errors on Sonnet 4.5 / Haiku 4.5 |
|
| Haiku 4.5; older models (Sonnet 4.5, ...) only if explicitly requested | `{type: "enabled", budget_tokens: N}` | No thinking | Required for thinking; must be less than `max_tokens`, minimum 1024 - errors otherwise | Allowed | `effort` works on Opus 4.5 (`low`/`medium`/`high` only - no `xhigh`/`max`); errors on Sonnet 4.5 / Haiku 4.5 |
|
||||||
|
|
||||||
Opus 4.8 keeps the same request surface as 4.7 (no new breaking changes) - see `shared/model-migration.md` -> Migrating to Opus 4.8 for the behavioral re-tuning, and -> Migrating to Opus 4.7 for the full breaking-change list when coming from 4.6 or earlier. With `thinking` disabled, Opus 4.8 may write longer reasoning into the visible response - leave adaptive thinking on, or add a final-answer-only instruction (see the migration guide).
|
Opus 4.8 keeps the same request surface as 4.7 (no new breaking changes) - see `shared/model-migration.md` -> Migrating to Opus 4.8 for the behavioral re-tuning, and -> Migrating to Opus 4.7 for the full breaking-change list when coming from 4.6 or earlier. With `thinking` disabled, Opus 4.8 may write longer reasoning into the visible response - leave adaptive thinking on, or add a final-answer-only instruction (see the migration guide).
|
||||||
|
|
||||||
@@ -273,7 +282,7 @@ For placement patterns, architectural guidance, and the silent-invalidator audit
|
|||||||
|
|
||||||
## Fast Mode (Quick Reference)
|
## Fast Mode (Quick Reference)
|
||||||
|
|
||||||
**Research preview, Claude Opus 5 / Opus 4.8 only** - Claude API and Managed Agents, not Bedrock / Google Cloud / Foundry. Opus 4.7 fast mode has been removed: `speed: "fast"` on 4.7 returns an error. Fast mode on Claude Opus 5 is priced at $10 / $50 per MTok. Fast mode runs the same model at up to 2.5x higher output tokens per second, at premium pricing. Three things are required on every request: use the **beta** messages endpoint (`client.beta.messages....`), pass the beta flag `fast-mode-2026-02-01`, and set `speed: "fast"` as a top-level request parameter (not a header, not in `extra_body`).
|
**Research preview, Claude Opus 5 / Claude Opus 5.5 / Opus 4.8 only** - Claude API and Managed Agents, not Bedrock / Google Cloud / Foundry. Opus 4.7 fast mode has been removed: `speed: "fast"` on 4.7 returns an error. Fast mode on Claude Opus 5 is priced at $10 / $50 per MTok; on Claude Opus 5.5, $8 / $40 (its fast-mode docs flip after the model launch - confirm before quoting). Fast mode runs the same model at up to 2.5x higher output tokens per second, at premium pricing. Three things are required on every request: use the **beta** messages endpoint (`client.beta.messages....`), pass the beta flag `fast-mode-2026-02-01`, and set `speed: "fast"` as a top-level request parameter (not a header, not in `extra_body`).
|
||||||
|
|
||||||
```python
|
```python
|
||||||
client.beta.messages.create(
|
client.beta.messages.create(
|
||||||
@@ -301,7 +310,7 @@ client.beta.messages.create(
|
|||||||
|
|
||||||
## Task Budgets (Quick Reference)
|
## Task Budgets (Quick Reference)
|
||||||
|
|
||||||
**Beta, Claude Opus 5 / Fable 5 / Claude Fable 5.1 (confirm at launch) / Sonnet 5 / Opus 4.8 / 4.7.** A task budget gives Claude a token ceiling for an agentic loop so it paces itself and finishes gracefully instead of being cut off - distinct from `max_tokens`, which is an enforced per-response ceiling the model is not aware of. Minimum `total`: 20,000. Set `task_budget` inside `output_config` on `client.beta.messages.stream(...)` with beta flag `task-budgets-2026-03-13` - use streaming so the large `max_tokens` doesn't hit HTTP timeouts (full details: `shared/model-migration.md` -> Task Budgets):
|
**Beta, Claude Opus 5 / Claude Opus 5.5 / Fable 5 / Claude Fable 5.1 (confirm at launch) / Sonnet 5 / Opus 4.8 / 4.7.** A task budget gives Claude a token ceiling for an agentic loop so it paces itself and finishes gracefully instead of being cut off - distinct from `max_tokens`, which is an enforced per-response ceiling the model is not aware of. Minimum `total`: 20,000. Set `task_budget` inside `output_config` on `client.beta.messages.stream(...)` with beta flag `task-budgets-2026-03-13` - use streaming so the large `max_tokens` doesn't hit HTTP timeouts (full details: `shared/model-migration.md` -> Task Budgets):
|
||||||
|
|
||||||
```python
|
```python
|
||||||
with client.beta.messages.stream(
|
with client.beta.messages.stream(
|
||||||
@@ -412,11 +421,13 @@ Availability: `shared/platform-availability.md`. For agents on Bedrock / Vertex
|
|||||||
|
|
||||||
**When the user asks "how do I write the client code for X":** reach for `shared/managed-agents-client-patterns.md` - covers lossless stream reconnect, `processed_at` queued/processed gate, interrupt, `tool_confirmation` round-trip, the correct idle/terminated break gate, post-idle status race, stream-first ordering, file-mount gotchas, etc. For credentials, lead with vault `environment_variable` credentials - the first-class mechanism; secrets are substituted at egress and never enter the sandbox (`shared/managed-agents-tools.md` -> Vaults). Keeping credentials host-side via custom tools is the fallback where vault credentials don't fit (e.g. self-hosted sandboxes).
|
**When the user asks "how do I write the client code for X":** reach for `shared/managed-agents-client-patterns.md` - covers lossless stream reconnect, `processed_at` queued/processed gate, interrupt, `tool_confirmation` round-trip, the correct idle/terminated break gate, post-idle status race, stream-first ordering, file-mount gotchas, etc. For credentials, lead with vault `environment_variable` credentials - the first-class mechanism; secrets are substituted at egress and never enter the sandbox (`shared/managed-agents-tools.md` -> Vaults). Keeping credentials host-side via custom tools is the fallback where vault credentials don't fit (e.g. self-hosted sandboxes).
|
||||||
|
|
||||||
|
**When the task is a deliverable - default the kickoff to an outcome, not a plain message.** If the session's job is to produce something checkable (an artifact, a report, a PR, a dataset, a fixed set of changes), read `shared/managed-agents-outcomes.md` and kick off with `user.define_outcome` plus a starter rubric you draft from the task (5-10 concrete, independently gradeable criteria; comment it as a starter to tune). Reserve plain `user.message` for genuinely conversational sessions. Trigger on intent, not just the word: "keep working until it's right", "make sure the output is actually good", "don't stop at a first draft" all mean outcomes.
|
||||||
|
|
||||||
**When the user asks about tool approvals, permission policies, or "auto mode"** (which tool calls need a human, letting the server evaluate calls, `evaluated_permission` / `evaluation` on tool-use events): read `shared/managed-agents-tools.md` § Permission Policies - `always_allow` / `always_ask` / `auto` and the three `auto` outcomes (runs, denied as high-risk, pauses when indeterminate). For attaching a terminal to a live session (`ant beta:sessions connect`): `shared/anthropic-cli.md`.
|
**When the user asks about tool approvals, permission policies, or "auto mode"** (which tool calls need a human, letting the server evaluate calls, `evaluated_permission` / `evaluation` on tool-use events): read `shared/managed-agents-tools.md` § Permission Policies - `always_allow` / `always_ask` / `auto` and the three `auto` outcomes (runs, denied as high-risk, pauses when indeterminate). For attaching a terminal to a live session (`ant beta:sessions connect`): `shared/anthropic-cli.md`.
|
||||||
|
|
||||||
**When the user wants the agent to run on a schedule** (cron, "every night", "weekly report"): read `shared/managed-agents-scheduled-deployments.md` - deployments fire sessions autonomously on a cron cadence, with per-firing run records and lifecycle controls (pause/unpause/archive).
|
**When the user wants the agent to run on a schedule** (cron, "every night", "weekly report"): read `shared/managed-agents-scheduled-deployments.md` - deployments fire sessions autonomously on a cron cadence, with per-firing run records and lifecycle controls (pause/unpause/archive).
|
||||||
|
|
||||||
**When the agent's work fans out** (research across several sources, per-file or per-record work, "look into N things, then summarize") **or one loop would fill its context with reading:** read `shared/managed-agents-multiagent.md` and recommend a multiagent session - start with just `{"type": "self"}` in the roster so the agent can delegate to copies of itself, then move reading-heavy sub-tasks to a cheaper worker agent (e.g. Claude Haiku 4.5) referenced by ID.
|
**When the agent's work fans out** (research across several sources, per-file or per-record work, "look into N things, then summarize") **or one loop would fill its context with reading:** read `shared/managed-agents-multiagent.md` and recommend a multiagent session - start with just `{"type": "self"}` in the roster so the agent can delegate to copies of itself, then move reading-heavy sub-tasks to a cheaper worker agent (e.g. Claude Haiku 4.5, or Claude Sonnet 5 when the worker needs more judgment) referenced by ID.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -488,10 +499,20 @@ The Quick Task Reference below uses the `{lang}/claude-api/FILE.md` path notatio
|
|||||||
|
|
||||||
**Long-running conversations (may exceed context window):**
|
**Long-running conversations (may exceed context window):**
|
||||||
-> Read `{lang}/claude-api/README.md` - see Compaction section
|
-> Read `{lang}/claude-api/README.md` - see Compaction section
|
||||||
**Migrating to a newer model (Fable 5.1 / Fable 5 / Opus 5 / Opus 4.8 / Opus 4.7 / Opus 4.6 / Sonnet 5 / Sonnet 4.6), replacing a retired model, or translating `budget_tokens` / prefill patterns to the current API:**
|
**Migrating to a newer model (Opus 5.5 / Fable 5.1 / Fable 5 / Opus 5 / Opus 4.8 / Opus 4.7 / Opus 4.6 / Sonnet 5 / Sonnet 4.6), replacing a retired model, or translating `budget_tokens` / prefill patterns to the current API:**
|
||||||
-> Read `shared/model-migration.md`
|
-> Read `shared/model-migration.md`
|
||||||
**Upgrading the Anthropic SDK package itself across a major version (`anthropic` 0.x -> 1.x: `httpx2`, awaited async `.with_raw_response`, removed deprecated parameters / aliases / Text Completions, Python >= 3.10) - or writing new code against a project already on 1.x:**
|
**Upgrading the Anthropic SDK package itself across a major version (`anthropic` 0.x -> 1.x: `httpx2`, awaited async `.with_raw_response`, removed deprecated parameters / aliases / Text Completions, Python >= 3.10) - or writing new code against a project already on 1.x:**
|
||||||
-> Read `{lang}/claude-api/sdk-upgrade.md` (currently Python only; other SDKs have no bundled major-version guide yet - use that SDK's CHANGELOG via `shared/live-sources.md`)
|
-> Read `{lang}/claude-api/sdk-upgrade.md` (currently Python only; other SDKs have no bundled major-version guide yet - use that SDK's CHANGELOG via `shared/live-sources.md`)
|
||||||
|
**Building an eval set for a Claude app (or "how do I know if my change helped"):**
|
||||||
|
-> Read `shared/evals/build-eval.md` - it loads `shared/evals/eval-audit.md` (the health checklist every eval must satisfy) before Step 0.
|
||||||
|
**Checking whether an existing eval is trustworthy ("is my eval any good?"):**
|
||||||
|
-> Read `shared/evals/eval-audit.md` and run it against the eval; report per its section 6.
|
||||||
|
**Iteratively improving an app against an eval (prompt tuning, hill-climbing):**
|
||||||
|
-> Read `shared/evals/eval-hillclimb.md` - runs Step 0 -> Step 5 with a train/test split; test is scored every round and is the headline.
|
||||||
|
**Rendering an eval-hillclimb HTML report:**
|
||||||
|
-> Run `shared/evals/report/build-report.mjs` when it is on disk (EAP install), else `shared/evals/report/build-report-lite.mjs` (always extracted with this skill) - both consume the `_state.json` / `vN/` layout produced by the hillclimb guide and write the same `trajectory/scores.tsv`. Don't write a parallel one.
|
||||||
|
**Migrating to, prompting, or tuning Claude Opus 5.5 (thinking can't be disabled, effort tuning and the `medium` default, forced tool use, computer toolset, progress updates, safeguard false positives, visual inputs / design outputs):**
|
||||||
|
-> Read `shared/model-migration.md` -> Migrating to Claude Opus 5.5; the preserved-thinking mechanics it points at are under Migrating to Claude Fable 5.1 from Claude Fable 5
|
||||||
**Prompting or tuning Fable 5/5.1 (long turns, effort, verbosity, autonomous runs, sub-agents):**
|
**Prompting or tuning Fable 5/5.1 (long turns, effort, verbosity, autonomous runs, sub-agents):**
|
||||||
-> Read `shared/model-migration.md` -> Migrating to Claude Fable 5.1 -> Behavioral shifts (prompt-tunable) + Long-running agent recommendations
|
-> Read `shared/model-migration.md` -> Migrating to Claude Fable 5.1 -> Behavioral shifts (prompt-tunable) + Long-running agent recommendations
|
||||||
**Prompting or tuning Claude Fable 5.1 (progress updates, parallel tool calls, writing density / formatting, autonomy, test sprawl, whole-file rewrites) or making a harness compatible with preserved thinking's history-editing check (history edits, compaction, per-turn reminders):**
|
**Prompting or tuning Claude Fable 5.1 (progress updates, parallel tool calls, writing density / formatting, autonomy, test sprawl, whole-file rewrites) or making a harness compatible with preserved thinking's history-editing check (history edits, compaction, per-turn reminders):**
|
||||||
@@ -544,29 +565,30 @@ Live documentation URLs are in `shared/live-sources.md`.
|
|||||||
## Common Pitfalls
|
## Common Pitfalls
|
||||||
|
|
||||||
- Don't truncate inputs when passing files or content to the API. If the content is too long to fit in the context window, notify the user and discuss options (chunking, summarization, etc.) rather than silently truncating.
|
- Don't truncate inputs when passing files or content to the API. If the content is too long to fit in the context window, notify the user and discuss options (chunking, summarization, etc.) rather than silently truncating.
|
||||||
- **Prefill removed (Fable 5, Claude Fable 5.1, Opus 5, Sonnet 5, and the 4.6/4.7/4.8 family):** Assistant message prefills (last-assistant-turn prefills) return a 400 error on Fable 5, Claude Fable 5.1, Opus 5, Sonnet 5, Opus 4.6, Opus 4.7, Opus 4.8, and Sonnet 4.6. Use structured outputs (`output_config.format`) or system prompt instructions to control response format instead. (One exception: the fallback-credit prefill claim - when redeeming a credit with `fallback_has_prefill_claim: true`, the server accepts the echoed assistant message; see the migration guide's refusal section.)
|
- **Prefill removed (Fable 5, Claude Fable 5.1, Opus 5, Claude Opus 5.5, Sonnet 5, and the 4.6/4.7/4.8 family):** Assistant message prefills (last-assistant-turn prefills) return a 400 error on Fable 5, Claude Fable 5.1, Opus 5, Claude Opus 5.5, Sonnet 5, Opus 4.6, Opus 4.7, Opus 4.8, and Sonnet 4.6. Use structured outputs (`output_config.format`) or system prompt instructions to control response format instead. (One exception: the fallback-credit prefill claim - when redeeming a credit with `fallback_has_prefill_claim: true`, the server accepts the echoed assistant message; see the migration guide's refusal section.)
|
||||||
- **Confirm migration scope before editing:** When a user asks to migrate code to a newer Claude model without naming a specific file, directory, or file list, **ask which scope to apply first** - the entire working directory, a specific subdirectory, or a specific set of files. Do not start editing until the user confirms. Imperative phrasings like "migrate my codebase", "move my project to X", "upgrade to Sonnet 4.6", or bare "migrate to Opus 4.8" are **still ambiguous** - they tell you what to do but not where, so ask. Proceed without asking only when the prompt names an exact file, a specific directory, or an explicit file list ("migrate `app.py`", "migrate everything under `services/`", "update `a.py` and `b.py`"). See `shared/model-migration.md` Step 0.
|
- **Confirm migration scope before editing:** When a user asks to migrate code to a newer Claude model without naming a specific file, directory, or file list, **ask which scope to apply first** - the entire working directory, a specific subdirectory, or a specific set of files. Do not start editing until the user confirms. Imperative phrasings like "migrate my codebase", "move my project to X", "upgrade to Sonnet 4.6", or bare "migrate to Opus 4.8" are **still ambiguous** - they tell you what to do but not where, so ask. Proceed without asking only when the prompt names an exact file, a specific directory, or an explicit file list ("migrate `app.py`", "migrate everything under `services/`", "update `a.py` and `b.py`"). See `shared/model-migration.md` Step 0.
|
||||||
- **`max_tokens` defaults:** Don't lowball `max_tokens` - hitting the cap truncates output mid-thought and requires a retry. For non-streaming requests, default to `~16000` (keeps responses under SDK HTTP timeouts). For streaming requests, default to `~64000` (timeouts aren't a concern, so give the model room). Only go lower when you have a hard reason: classification (`~256`), cost caps, deliberately short outputs, or **`max_tokens: 0`** for cache pre-warming (see `shared/prompt-caching.md` -> Pre-warming).
|
- **`max_tokens` defaults:** Don't lowball `max_tokens` - hitting the cap truncates output mid-thought and requires a retry. For non-streaming requests, default to `~16000` (keeps responses under SDK HTTP timeouts). For streaming requests, default to `~64000` (timeouts aren't a concern, so give the model room). Only go lower when you have a hard reason: classification (`~256`), cost caps, deliberately short outputs, or **`max_tokens: 0`** for cache pre-warming (see `shared/prompt-caching.md` -> Pre-warming).
|
||||||
- **Disabling thinking on Claude Opus 5 has two failure modes - prefer low/medium effort instead.** Only affects code that explicitly opts out; thinking is on by default, so watch for a disabled-thinking setting carried forward from Opus 4.8. With `thinking: {type: "disabled"}`, the model occasionally writes a tool call into its **visible text** instead of a `tool_use` block: the turn succeeds, the call never runs, no error is raised, and in an agentic loop that text pollutes later turns. It can also leak `<thinking>` tags into the response. Turning thinking on and lowering `effort` fixes both and still cuts cost. If a route must stay thinking-off: **delete** any don't-think/don't-reason rule (it makes tag leakage worse), don't name thinking tags, and add the combined instruction *"When you use a tool, you may say a brief sentence first. If no tool can express what the user asked for, say so instead of guessing. Do not include internal or system XML tags in your response."* Details: `shared/model-migration.md` -> Two failure modes when thinking is disabled.
|
- **Disabling thinking on Claude Opus 5 has two failure modes - prefer low/medium effort instead.** (On Claude Opus 5.5 it can't be disabled at all - `{type: "disabled"}` is a 400 at every effort level; use `low` effort.) Only affects code that explicitly opts out; thinking is on by default, so watch for a disabled-thinking setting carried forward from Opus 4.8. With `thinking: {type: "disabled"}`, the model occasionally writes a tool call into its **visible text** instead of a `tool_use` block: the turn succeeds, the call never runs, no error is raised, and in an agentic loop that text pollutes later turns. It can also leak `<thinking>` tags into the response. Turning thinking on and lowering `effort` fixes both and still cuts cost. If a route must stay thinking-off: **delete** any don't-think/don't-reason rule (it makes tag leakage worse), don't name thinking tags, and add the combined instruction *"When you use a tool, you may say a brief sentence first. If no tool can express what the user asked for, say so instead of guessing. Do not include internal or system XML tags in your response."* Details: `shared/model-migration.md` -> Two failure modes when thinking is disabled.
|
||||||
- **128K output tokens:** Fable 5, Claude Fable 5.1, Opus 5, Opus 4.6, Opus 4.7, Opus 4.8, Sonnet 5, and Sonnet 4.6 support up to 128K `max_tokens`, but the SDKs require streaming for values that large to avoid HTTP timeouts. Use `.stream()` with `.get_final_message()` / `.finalMessage()`.
|
- **128K output tokens:** Fable 5, Claude Fable 5.1, Opus 5, Claude Opus 5.5, Opus 4.6, Opus 4.7, Opus 4.8, Sonnet 5, and Sonnet 4.6 support up to 128K `max_tokens`, but the SDKs require streaming for values that large to avoid HTTP timeouts. Use `.stream()` with `.get_final_message()` / `.finalMessage()`.
|
||||||
- **Forced tool use removed (Claude Fable 5.1 / Claude Mythos 5.1, as on Mythos Preview):** `tool_choice: {type: "any"}` and `{type: "tool", name: ...}` return a 400 (`tool_choice: type "tool" and "any" are not supported for this model.`), on `count_tokens` and Batches too. Use `{type: "auto"}` plus an explicit instruction naming the tool, `strict: true` on the tool to keep schema-valid arguments, or structured outputs (`output_config.format`) when the forced call only existed to get JSON back. `{type: "none"}` is unaffected; `disable_parallel_tool_use` still works with `auto` (at most one call).
|
- **Forced tool use removed (Claude Fable 5.1 / Claude Mythos 5.1 / Claude Opus 5.5, as on Mythos Preview):** `tool_choice: {type: "any"}` and `{type: "tool", name: ...}` return a 400 (`tool_choice: type "tool" and "any" are not supported for this model.`), on `count_tokens` and Batches too. Use `{type: "auto"}` plus an explicit instruction naming the tool, `strict: true` on the tool to keep schema-valid arguments, or structured outputs (`output_config.format`) when the forced call only existed to get JSON back. `{type: "none"}` is unaffected; `disable_parallel_tool_use` still works with `auto` (at most one call).
|
||||||
- **Tool call JSON parsing (Fable 5, Claude Fable 5.1, Opus 5, and the 4.6/4.7/4.8 family):** Fable 5, Claude Fable 5.1, Opus 5, Opus 4.6, Opus 4.7, Opus 4.8, and Sonnet 4.6 may produce different JSON string escaping in tool call `input` fields (e.g., Unicode or forward-slash escaping). Always parse tool inputs with `json.loads()` / `JSON.parse()` - never do raw string matching on the serialized input.
|
- **Tool call JSON parsing (Fable 5, Claude Fable 5.1, Opus 5, Claude Opus 5.5, and the 4.6/4.7/4.8 family):** Fable 5, Claude Fable 5.1, Opus 5, Claude Opus 5.5, Opus 4.6, Opus 4.7, Opus 4.8, and Sonnet 4.6 may produce different JSON string escaping in tool call `input` fields (e.g., Unicode or forward-slash escaping). Always parse tool inputs with `json.loads()` / `JSON.parse()` - never do raw string matching on the serialized input.
|
||||||
- **Structured outputs (all models):** Use `output_config: {format: {...}}` instead of the deprecated `output_format` parameter on `messages.create()`. This is a general API change, not 4.6-specific.
|
- **Structured outputs (all models):** Use `output_config: {format: {...}}` instead of the deprecated `output_format` parameter on `messages.create()`. This is a general API change, not 4.6-specific.
|
||||||
- **Don't reimplement SDK functionality:** The SDK provides high-level helpers - use them instead of building from scratch. Specifically: use `stream.finalMessage()` instead of wrapping `.on()` events in `new Promise()`; use typed exception classes (`Anthropic.RateLimitError`, etc.) instead of string-matching error messages; use SDK types (`Anthropic.MessageParam`, `Anthropic.Tool`, `Anthropic.Message`, etc.) instead of redefining equivalent interfaces.
|
- **Don't reimplement SDK functionality:** The SDK provides high-level helpers - use them instead of building from scratch. Specifically: use `stream.finalMessage()` instead of wrapping `.on()` events in `new Promise()`; use typed exception classes (`Anthropic.RateLimitError`, etc.) instead of string-matching error messages; use SDK types (`Anthropic.MessageParam`, `Anthropic.Tool`, `Anthropic.Message`, etc.) instead of redefining equivalent interfaces.
|
||||||
- **Error handling - catch a chain, not one broad class.** A single `except APIStatusError` / `catch (AnthropicServiceException)` / `rescue APIError` loses the distinction between retryable (429, >=500, network) and non-retryable (400/404) failures. Write a most-specific-first chain - e.g. `NotFoundError` -> `RateLimitError` -> `APIStatusError` -> `APIConnectionError` (or the Go equivalent: `errors.As` into `*anthropic.Error` then `switch apierr.StatusCode { case 404: ...; case 429: ...; default: ... }`). Per-language class names and namespaces are in `shared/error-codes.md`.
|
- **Error handling - catch a chain, not one broad class.** A single `except APIStatusError` / `catch (AnthropicServiceException)` / `rescue APIError` loses the distinction between retryable (429, >=500, network) and non-retryable (400/404) failures. Write a most-specific-first chain - e.g. `NotFoundError` -> `RateLimitError` -> `APIStatusError` -> `APIConnectionError` (or the Go equivalent: `errors.As` into `*anthropic.Error` then `switch apierr.StatusCode { case 404: ...; case 429: ...; default: ... }`). Per-language class names and namespaces are in `shared/error-codes.md`.
|
||||||
- **Don't research SDK types - write first.** If a type name isn't shown in the documentation included in this skill, write the code file from the namespace/package tables in the language-specific doc and let the compiler's error point you to the right name. Do not spend turns on WebFetch, SDK-repo clones, or compiling-and-running a separate reflection program to discover type names before writing - produce the source file first, then fix what the compiler reports. A quick `strings` / `jar tf` / `javap` against the installed SDK is acceptable for locating names (it returns in seconds), but don't escalate beyond that. A file with a wrong type name is recoverable; a session spent on discovery with no file written is not.
|
- **Don't research SDK types - write first.** If a type name isn't shown in the documentation included in this skill, write the code file from the namespace/package tables in the language-specific doc and let the compiler's error point you to the right name. Do not spend turns on WebFetch, SDK-repo clones, or compiling-and-running a separate reflection program to discover type names before writing - produce the source file first, then fix what the compiler reports. A quick `strings` / `jar tf` / `javap` against the installed SDK is acceptable for locating names (it returns in seconds), but don't escalate beyond that. A file with a wrong type name is recoverable; a session spent on discovery with no file written is not.
|
||||||
- **Bash and text editor tools are Anthropic-defined, schema-less.** Declare `{"type": "bash_20250124", "name": "bash"}` / `{"type": "text_editor_20250728", "name": "str_replace_based_edit_tool"}` - no `input_schema`. A custom tool with your own schema named `"bash"` is a different tool. Handler paths and security checks are in `shared/tool-use-concepts.md` § Client-Side Tools.
|
- **Bash and text editor tools are Anthropic-defined, schema-less.** Declare `{"type": "bash_20250124", "name": "bash"}` / `{"type": "text_editor_20250728", "name": "str_replace_based_edit_tool"}` - no `input_schema`. A custom tool with your own schema named `"bash"` is a different tool. Handler paths and security checks are in `shared/tool-use-concepts.md` § Client-Side Tools.
|
||||||
- **Advisor tool model pairing.** The advisor tool's `model` must be at least as capable as the request's top-level `model` - e.g. executor `claude-sonnet-5` -> advisor `claude-opus-4-8` or `claude-opus-4-7`. An invalid pair returns 400. Pairing table in `shared/tool-use-concepts.md` § Advisor. Availability: `shared/platform-availability.md`.
|
- **Advisor tool model pairing.** The advisor tool's `model` must be at least as capable as the request's top-level `model` - e.g. executor `claude-sonnet-5` -> advisor `claude-opus-5` or `claude-opus-4-8`. An invalid pair returns 400. Pairing table (and which advisors return plaintext vs encrypted `advisor_redacted_result` advice) in `shared/tool-use-concepts.md` § Advisor. Availability: `shared/platform-availability.md`.
|
||||||
- **Agent Skills != Managed Agents.** To have Claude generate a `.pptx`/`.xlsx`/etc. via Agent Skills, call `client.beta.messages.create` with `container={"skills": [...]}`, the `code_execution_20260521` tool, and the `code-execution-2025-08-25` beta (Skills is out of beta - no `skills-2025-10-02` header needed). Do not use `client.beta.agents` / `sessions` / `environments` here - those are the Managed Agents surface, not Agent Skills.
|
- **Agent Skills != Managed Agents.** To have Claude generate a `.pptx`/`.xlsx`/etc. via Agent Skills, call `client.beta.messages.create` with `container={"skills": [...]}`, the `code_execution_20260521` tool, and the `code-execution-2025-08-25` beta (Skills is out of beta - no `skills-2025-10-02` header needed). Do not use `client.beta.agents` / `sessions` / `environments` here - those are the Managed Agents surface, not Agent Skills.
|
||||||
- **MCP connector needs both halves.** `mcp_servers=[{type:"url", url, name}]` alone is rejected as a validation error - also add `tools=[{type:"mcp_toolset", mcp_server_name:<same name>}]` with beta `mcp-client-2025-11-20`. Availability: `shared/platform-availability.md`.
|
- **MCP connector needs both halves.** `mcp_servers=[{type:"url", url, name}]` alone is rejected as a validation error - also add `tools=[{type:"mcp_toolset", mcp_server_name:<same name>}]` with beta `mcp-client-2025-11-20`. Availability: `shared/platform-availability.md`.
|
||||||
- **`inference_geo` is a direct top-level request parameter** - `client.messages.create(..., inference_geo="us")` / `.inferenceGeo("us")`. Do not put it in `extra_body` / `putAdditionalBodyProperty`. (Messages API only - on Managed Agents, `inference_geo` instead nests inside the agent's `model` object, never top-level; see `shared/managed-agents-core.md` § Pinning inference geography.) Supported on Opus 4.6 / Sonnet 4.6 and later; availability: `shared/platform-availability.md`. `response.usage.inference_geo` reports where inference ran.
|
- **`inference_geo` is a direct top-level request parameter** - `client.messages.create(..., inference_geo="us")` / `.inferenceGeo("us")`. Do not put it in `extra_body` / `putAdditionalBodyProperty`. (Messages API only - on Managed Agents, `inference_geo` instead nests inside the agent's `model` object, never top-level; see `shared/managed-agents-core.md` § Pinning inference geography.) Supported on Opus 4.6 / Sonnet 4.6 and later; availability: `shared/platform-availability.md`. `response.usage.inference_geo` reports where inference ran.
|
||||||
- **Fine-grained tool streaming is not a beta feature.** Set `eager_input_streaming: true` on the tool definition and call the regular `client.messages.stream(...)`. There is no beta header and no `client.beta.*` path.
|
- **Fine-grained tool streaming is not a beta feature; this skill's default is to turn it on for streaming + client tools (the API itself still defaults to buffered).** Set `eager_input_streaming: true` on the tool definition and call the regular `client.messages.stream(...)`. There is no beta header and no `client.beta.*` path. Do not also send the legacy `fine-grained-tool-streaming-2025-05-14` beta header. Python's `@beta_tool(eager_input_streaming=True)` accepts it directly; TypeScript's `betaZodTool()` does not, so spread it on: `{ ...betaZodTool({...}), eager_input_streaming: true }`. With the field on, the API no longer coerces or validates the input, so the accumulated `partial_json` may be incomplete (`max_tokens`) or invalid - guard the parse (`shared/tool-use-concepts.md` -> Eager input streaming).
|
||||||
- **Cache diagnostics is beta.** Use `client.beta.messages.*` with beta `cache-diagnosis-2026-04-07`. Pass `diagnostics: {previous_message_id: null}` on the first turn and `diagnostics: {previous_message_id: <previous response id>}` on subsequent turns; the result is on `response.diagnostics`. Availability: `shared/platform-availability.md`.
|
- **Cache diagnostics is beta.** Use `client.beta.messages.*` with beta `cache-diagnosis-2026-04-07`. Pass `diagnostics: {previous_message_id: null}` on the first turn and `diagnostics: {previous_message_id: <previous response id>}` on subsequent turns; the result is on `response.diagnostics`. Availability: `shared/platform-availability.md`.
|
||||||
- **Memory tool type is `memory_20250818`.** Declare `{"type": "memory_20250818", "name": "memory"}`. Go uses the beta-namespace type `{OfMemoryTool20250818: &anthropic.BetaMemoryTool20250818Param{}}` on `client.Beta.Messages.New`; Python/TypeScript/Ruby/PHP/C# use the non-beta `client.messages.create`; Java has both a non-beta `MemoryTool20250818` and a beta tool-runner path. Python/TypeScript provide `BetaAbstractMemoryTool` / `betaMemoryTool` helpers for implementing the backend.
|
- **Memory tool type is `memory_20250818`.** Declare `{"type": "memory_20250818", "name": "memory"}`. Go uses the beta-namespace type `{OfMemoryTool20250818: &anthropic.BetaMemoryTool20250818Param{}}` on `client.Beta.Messages.New`; Python/TypeScript/Ruby/PHP/C# use the non-beta `client.messages.create`; Java has both a non-beta `MemoryTool20250818` and a beta tool-runner path. Python/TypeScript provide `BetaAbstractMemoryTool` / `betaMemoryTool` helpers for implementing the backend.
|
||||||
- **Use a model the feature actually supports.** Some features are restricted to specific model tiers - fast mode is Claude Opus 5 / Opus 4.8 only (and Claude API only), task budgets (Messages API only - Managed Agents session budgets have no model-tier restriction) are Claude Opus 5 / Fable 5 / Claude Fable 5.1 (confirm at launch) / Sonnet 5 / Opus 4.8 / 4.7 only, and the advisor tool requires a valid executor<->advisor pair. If the user's prompt names a model that the feature doesn't support, use a supported model instead and note the substitution in the output.
|
- **Use a model the feature actually supports.** Some features are restricted to specific model tiers - fast mode is Claude Opus 5 / Claude Opus 5.5 / Opus 4.8 only (and Claude API only), task budgets (Messages API only - Managed Agents session budgets have no model-tier restriction) are Claude Opus 5 / Claude Opus 5.5 / Fable 5 / Claude Fable 5.1 (confirm at launch) / Sonnet 5 / Opus 4.8 / 4.7 only, and the advisor tool requires a valid executor<->advisor pair. If the user's prompt names a model that the feature doesn't support, use a supported model instead and note the substitution in the output.
|
||||||
- **Don't define custom types for SDK data structures:** The SDK exports types for all API objects. Use `Anthropic.MessageParam` for messages, `Anthropic.Tool` for tool definitions, `Anthropic.ToolUseBlock` / `Anthropic.ToolResultBlockParam` for tool results, `Anthropic.Message` for responses. Defining your own `interface ChatMessage { role: string; content: unknown }` duplicates what the SDK already provides and loses type safety.
|
- **Don't define custom types for SDK data structures:** The SDK exports types for all API objects. Use `Anthropic.MessageParam` for messages, `Anthropic.Tool` for tool definitions, `Anthropic.ToolUseBlock` / `Anthropic.ToolResultBlockParam` for tool results, `Anthropic.Message` for responses. Defining your own `interface ChatMessage { role: string; content: unknown }` duplicates what the SDK already provides and loses type safety.
|
||||||
- **Report and document output:** For tasks that produce reports, documents, or visualizations, the code execution sandbox has `python-docx`, `python-pptx`, `matplotlib`, `pillow`, and `pypdf` pre-installed. Claude can generate formatted files (DOCX, PDF, charts) and return them via the Files API - consider this for "report" or "document" type requests instead of plain stdout text.
|
- **Report and document output:** For tasks that produce reports, documents, or visualizations, the code execution sandbox has `python-docx`, `python-pptx`, `matplotlib`, `pillow`, and `pypdf` pre-installed. Claude can generate formatted files (DOCX, PDF, charts) and return them via the Files API - consider this for "report" or "document" type requests instead of plain stdout text.
|
||||||
- **Server-tool errors don't raise.** Web search and web fetch errors return HTTP 200 with a `web_search_tool_result` / `web_fetch_tool_result` block whose `content` is a single error object (e.g. `{error_code: "max_uses_exceeded"}`) - not a raised exception. For web search, a success `content` is a *list*; an error `content` is an *object* - branch on that before indexing.
|
- **Server-tool errors don't raise.** Web search and web fetch errors return HTTP 200 with a `web_search_tool_result` / `web_fetch_tool_result` block whose `content` is a single error object (e.g. `{error_code: "max_uses_exceeded"}`) - not a raised exception. For web search, a success `content` is a *list*; an error `content` is an *object* - branch on that before indexing.
|
||||||
- **Managed Agents web tools ignore the environment's `networking`.** `web_search` / `web_fetch` run on Anthropic's servers in cloud *and* self-hosted environments, and Console org-level web settings apply to the Messages API only. Restrict them per tool with `allowed_domains` **or** `blocked_domains` (never both; 1-64 plain hostnames per list, subdomains covered; IPs, bare TLDs, single-label and `localhost`-style names rejected on both tools; a path suffix is allowed only on `web_search`) on the toolset `configs` entry - `shared/managed-agents-tools.md` § Web search & web fetch settings.
|
- **Managed Agents web tools ignore the environment's `networking`.** `web_search` / `web_fetch` run on Anthropic's servers in cloud *and* self-hosted environments, and Console org-level web settings apply to the Messages API only. Restrict them per tool with `allowed_domains` **or** `blocked_domains` (never both; 1-64 plain hostnames per list, subdomains covered; IPs, bare TLDs, single-label and `localhost`-style names rejected on both tools; a path suffix is allowed only on `web_search`) on the toolset `configs` entry - `shared/managed-agents-tools.md` § Web search & web fetch settings.
|
||||||
|
- **Eval / hillclimb work has dedicated guides:** If the user says "hillclimb", "improve my eval score", "iterate on my prompt against an eval", or "build me an eval" - load `shared/evals/eval-hillclimb.md` or `shared/evals/build-eval.md` rather than improvising. The bundled HTML report builder is `shared/evals/report/build-report.mjs` when it is on disk (EAP install), else `shared/evals/report/build-report-lite.mjs` (always extracted with this skill); don't write a parallel one.
|
||||||
- **Code execution output block type:** `code_execution_20260521` returns `bash_code_execution_tool_result` (with `.content.stdout`), **not** the legacy bare `code_execution_tool_result`. Iterate `response.content` and match on the correct type.
|
- **Code execution output block type:** `code_execution_20260521` returns `bash_code_execution_tool_result` (with `.content.stdout`), **not** the legacy bare `code_execution_tool_result`. Iterate `response.content` and match on the correct type.
|
||||||
- **Tool search: never defer everything.** The search tool itself must not have `defer_loading: true`, and at least one tool in `tools` must be non-deferred, or the API returns 400 `All tools have defer_loading set`.
|
- **Tool search: never defer everything.** The search tool itself must not have `defer_loading: true`, and at least one tool in `tools` must be non-deferred, or the API returns 400 `All tools have defer_loading set`.
|
||||||
|
|||||||
@@ -157,7 +157,7 @@ var response = await client.Messages.Create(new MessageCreateParams
|
|||||||
MaxTokens = 16000,
|
MaxTokens = 16000,
|
||||||
// ThinkingConfigParam? implicitly converts from the concrete variant classes -
|
// ThinkingConfigParam? implicitly converts from the concrete variant classes -
|
||||||
// no wrapper needed.
|
// no wrapper needed.
|
||||||
// display opt-in: default is omitted (empty thinking text) on Fable 5 / Mythos 5 / Claude Opus 5 / Opus 4.8 / 4.7
|
// display opt-in: default is omitted (empty thinking text) on Fable 5/5.1, Mythos 5/5.1, Claude Opus 5, Opus 4.8/4.7, and Claude Sonnet 5
|
||||||
Thinking = new ThinkingConfigAdaptive { Display = Display.Summarized },
|
Thinking = new ThinkingConfigAdaptive { Display = Display.Summarized },
|
||||||
Messages =
|
Messages =
|
||||||
[
|
[
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ using Anthropic.Models.Messages;
|
|||||||
|
|
||||||
var parameters = new MessageCreateParams
|
var parameters = new MessageCreateParams
|
||||||
{
|
{
|
||||||
Model = Model.ClaudeOpus4_8,
|
Model = "claude-opus-5",
|
||||||
MaxTokens = 64000,
|
MaxTokens = 64000,
|
||||||
Messages = [new() { Role = Role.User, Content = "Write a haiku" }]
|
Messages = [new() { Role = Role.User, Content = "Write a haiku" }]
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ using Anthropic.Models.Messages;
|
|||||||
|
|
||||||
var parameters = new MessageCreateParams
|
var parameters = new MessageCreateParams
|
||||||
{
|
{
|
||||||
Model = Model.ClaudeSonnet4_6,
|
Model = "claude-opus-5",
|
||||||
MaxTokens = 16000,
|
MaxTokens = 16000,
|
||||||
Tools = [
|
Tools = [
|
||||||
new Tool {
|
new Tool {
|
||||||
|
|||||||
@@ -27,11 +27,11 @@ client := anthropic.NewClient(
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Model Constants
|
## Model IDs
|
||||||
|
|
||||||
The Go SDK provides typed model constants: `anthropic.ModelClaudeFable5`, `anthropic.ModelClaudeOpus4_8`, `anthropic.ModelClaudeOpus4_7`, `anthropic.ModelClaudeSonnet4_6`, `anthropic.ModelClaudeHaiku4_5_20251001`. Default to Claude Opus 5 unless the user specifies otherwise; if they ask for Fable or the most powerful model, use `anthropic.ModelClaudeFable5` (see `shared/models.md` for the full resolution table).
|
`anthropic.Model` is an alias for `string`, so pass the model as its plain id: `Model: "claude-opus-5"`. Default to Claude Opus 5 unless the user specifies otherwise; if they ask for Fable or the most powerful model, use `"claude-fable-5-1"`; if they ask for a cheaper tier, use the current generation - `"claude-sonnet-5"` or `"claude-haiku-4-5"` (see `shared/models.md` for the full resolution table).
|
||||||
|
|
||||||
`anthropic.Model` is an alias for `string`, so a model with no typed constant yet - including Claude Opus 5 - is passed as the plain id: `Model: "claude-opus-5"`. Check the SDK release notes for a typed `Claude Opus 5` constant before assuming one exists.
|
The SDK also ships typed `anthropic.ModelClaude*` constants, but they lag model launches - a given SDK release may have constants only for previous-generation models. Do not pick a model because it has a typed constant; the string id works for every model on every SDK version. Check the SDK release notes before assuming a typed constant exists for a current model.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -69,9 +69,10 @@ Derived from `anthropic-sdk-go/message.go` (`ThinkingConfigParamUnion`, `Thinkin
|
|||||||
```go
|
```go
|
||||||
// There is no ThinkingConfigParamOfAdaptive helper - construct the union
|
// There is no ThinkingConfigParamOfAdaptive helper - construct the union
|
||||||
// struct-literal directly and take the address of the variant.
|
// struct-literal directly and take the address of the variant.
|
||||||
adaptive := anthropic.ThinkingConfigAdaptiveParam{}
|
// display opt-in: default is omitted (empty thinking text) on Fable 5/5.1, Mythos 5/5.1, Claude Opus 5, Opus 4.8/4.7, and Claude Sonnet 5
|
||||||
|
adaptive := anthropic.ThinkingConfigAdaptiveParam{Display: anthropic.ThinkingConfigAdaptiveDisplaySummarized}
|
||||||
params := anthropic.MessageNewParams{
|
params := anthropic.MessageNewParams{
|
||||||
Model: anthropic.ModelClaudeSonnet4_6,
|
Model: "claude-opus-5",
|
||||||
MaxTokens: 16000,
|
MaxTokens: 16000,
|
||||||
Thinking: anthropic.ThinkingConfigParamUnion{OfAdaptive: &adaptive},
|
Thinking: anthropic.ThinkingConfigParamUnion{OfAdaptive: &adaptive},
|
||||||
Messages: []anthropic.MessageParam{
|
Messages: []anthropic.MessageParam{
|
||||||
@@ -158,7 +159,7 @@ Use `Beta.Messages.New` with `ContextManagement` on `BetaMessageNewParams`. Ther
|
|||||||
|
|
||||||
```go
|
```go
|
||||||
params := anthropic.BetaMessageNewParams{
|
params := anthropic.BetaMessageNewParams{
|
||||||
Model: "claude-opus-5", // also supported: ModelClaudeOpus4_8, ModelClaudeSonnet4_6
|
Model: "claude-opus-5",
|
||||||
MaxTokens: 16000,
|
MaxTokens: 16000,
|
||||||
Betas: []anthropic.AnthropicBeta{"compact-2026-01-12"},
|
Betas: []anthropic.AnthropicBeta{"compact-2026-01-12"},
|
||||||
ContextManagement: anthropic.BetaContextManagementConfigParam{
|
ContextManagement: anthropic.BetaContextManagementConfigParam{
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
```go
|
```go
|
||||||
stream := client.Messages.NewStreaming(context.Background(), anthropic.MessageNewParams{
|
stream := client.Messages.NewStreaming(context.Background(), anthropic.MessageNewParams{
|
||||||
Model: anthropic.ModelClaudeOpus4_8,
|
Model: "claude-opus-5",
|
||||||
MaxTokens: 64000,
|
MaxTokens: 64000,
|
||||||
Messages: []anthropic.MessageParam{
|
Messages: []anthropic.MessageParam{
|
||||||
anthropic.NewUserMessage(anthropic.NewTextBlock("Write a haiku")),
|
anthropic.NewUserMessage(anthropic.NewTextBlock("Write a haiku")),
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ runner := client.Beta.Messages.NewToolRunner(
|
|||||||
[]anthropic.BetaTool{weatherTool},
|
[]anthropic.BetaTool{weatherTool},
|
||||||
anthropic.BetaToolRunnerParams{
|
anthropic.BetaToolRunnerParams{
|
||||||
BetaMessageNewParams: anthropic.BetaMessageNewParams{
|
BetaMessageNewParams: anthropic.BetaMessageNewParams{
|
||||||
Model: anthropic.ModelClaudeOpus4_8,
|
Model: "claude-opus-5",
|
||||||
MaxTokens: 16000,
|
MaxTokens: 16000,
|
||||||
Messages: []anthropic.BetaMessageParam{
|
Messages: []anthropic.BetaMessageParam{
|
||||||
anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("What's the weather in Paris?")),
|
anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("What's the weather in Paris?")),
|
||||||
@@ -120,7 +120,7 @@ func main() {
|
|||||||
|
|
||||||
for {
|
for {
|
||||||
resp, err := client.Messages.New(context.Background(), anthropic.MessageNewParams{
|
resp, err := client.Messages.New(context.Background(), anthropic.MessageNewParams{
|
||||||
Model: anthropic.ModelClaudeSonnet4_6,
|
Model: "claude-opus-5",
|
||||||
MaxTokens: 16000,
|
MaxTokens: 16000,
|
||||||
Messages: messages,
|
Messages: messages,
|
||||||
Tools: tools,
|
Tools: tools,
|
||||||
@@ -204,11 +204,11 @@ Server-side - no tool_result round-trip. The advisor model must be >= the execut
|
|||||||
|
|
||||||
```go
|
```go
|
||||||
response, err := client.Beta.Messages.New(ctx, anthropic.BetaMessageNewParams{
|
response, err := client.Beta.Messages.New(ctx, anthropic.BetaMessageNewParams{
|
||||||
Model: anthropic.ModelClaudeSonnet4_6,
|
Model: "claude-sonnet-5", // executor
|
||||||
MaxTokens: 4096,
|
MaxTokens: 4096,
|
||||||
Tools: []anthropic.BetaToolUnionParam{
|
Tools: []anthropic.BetaToolUnionParam{
|
||||||
{OfAdvisorTool20260301: &anthropic.BetaAdvisorTool20260301Param{
|
{OfAdvisorTool20260301: &anthropic.BetaAdvisorTool20260301Param{
|
||||||
Model: anthropic.ModelClaudeOpus4_8,
|
Model: "claude-opus-5", // advisor
|
||||||
}},
|
}},
|
||||||
},
|
},
|
||||||
Messages: []anthropic.BetaMessageParam{ /* ... */ },
|
Messages: []anthropic.BetaMessageParam{ /* ... */ },
|
||||||
|
|||||||
@@ -81,7 +81,7 @@ import com.anthropic.models.messages.MessageCreateParams;
|
|||||||
import com.anthropic.models.messages.Message;
|
import com.anthropic.models.messages.Message;
|
||||||
|
|
||||||
MessageCreateParams params = MessageCreateParams.builder()
|
MessageCreateParams params = MessageCreateParams.builder()
|
||||||
.model("claude-opus-5") // .model(String) overload - use it for ids with no typed Model constant yet
|
.model("claude-opus-5") // .model(String) overload - works for every model id; typed Model.* constants lag model launches
|
||||||
.maxTokens(16000L)
|
.maxTokens(16000L)
|
||||||
.addUserMessage("What is the capital of France?")
|
.addUserMessage("What is the capital of France?")
|
||||||
.build();
|
.build();
|
||||||
@@ -105,13 +105,13 @@ response.content().stream()
|
|||||||
```java
|
```java
|
||||||
import com.anthropic.models.messages.ContentBlock;
|
import com.anthropic.models.messages.ContentBlock;
|
||||||
import com.anthropic.models.messages.MessageCreateParams;
|
import com.anthropic.models.messages.MessageCreateParams;
|
||||||
import com.anthropic.models.messages.Model;
|
|
||||||
import com.anthropic.models.messages.ThinkingConfigAdaptive;
|
import com.anthropic.models.messages.ThinkingConfigAdaptive;
|
||||||
|
|
||||||
MessageCreateParams params = MessageCreateParams.builder()
|
MessageCreateParams params = MessageCreateParams.builder()
|
||||||
.model(Model.CLAUDE_SONNET_4_6)
|
.model("claude-opus-5")
|
||||||
.maxTokens(16000L)
|
.maxTokens(16000L)
|
||||||
.thinking(ThinkingConfigAdaptive.builder().build())
|
// display opt-in: default is omitted (empty thinking text) on Fable 5/5.1, Mythos 5/5.1, Claude Opus 5, Opus 4.8/4.7, and Claude Sonnet 5
|
||||||
|
.thinking(ThinkingConfigAdaptive.builder().display(ThinkingConfigAdaptive.Display.SUMMARIZED).build())
|
||||||
.addUserMessage("Solve this step by step: 27 * 453")
|
.addUserMessage("Solve this step by step: 27 * 453")
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
@@ -171,7 +171,7 @@ import com.anthropic.models.messages.MessageCountTokensParams;
|
|||||||
|
|
||||||
long tokens = client.messages().countTokens(
|
long tokens = client.messages().countTokens(
|
||||||
MessageCountTokensParams.builder()
|
MessageCountTokensParams.builder()
|
||||||
.model(Model.CLAUDE_SONNET_4_6)
|
.model("claude-opus-5")
|
||||||
.addUserMessage("Hello")
|
.addUserMessage("Hello")
|
||||||
.build()
|
.build()
|
||||||
).inputTokens();
|
).inputTokens();
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import com.anthropic.core.http.StreamResponse;
|
|||||||
import com.anthropic.models.messages.RawMessageStreamEvent;
|
import com.anthropic.models.messages.RawMessageStreamEvent;
|
||||||
|
|
||||||
MessageCreateParams params = MessageCreateParams.builder()
|
MessageCreateParams params = MessageCreateParams.builder()
|
||||||
.model(Model.CLAUDE_OPUS_4_8)
|
.model("claude-opus-5")
|
||||||
.maxTokens(64000L)
|
.maxTokens(64000L)
|
||||||
.addUserMessage("Write a haiku")
|
.addUserMessage("Write a haiku")
|
||||||
.build();
|
.build();
|
||||||
|
|||||||
@@ -96,7 +96,7 @@ Tool tool = Tool.builder()
|
|||||||
.build();
|
.build();
|
||||||
|
|
||||||
MessageCreateParams params = MessageCreateParams.builder()
|
MessageCreateParams params = MessageCreateParams.builder()
|
||||||
.model(Model.CLAUDE_SONNET_4_6)
|
.model("claude-opus-5")
|
||||||
.maxTokens(16000L)
|
.maxTokens(16000L)
|
||||||
.addTool(tool)
|
.addTool(tool)
|
||||||
.addUserMessage("Weather in Paris?")
|
.addUserMessage("Weather in Paris?")
|
||||||
@@ -140,7 +140,7 @@ record Book(String title, String author) {}
|
|||||||
record BookList(List<Book> books) {}
|
record BookList(List<Book> books) {}
|
||||||
|
|
||||||
StructuredMessageCreateParams<BookList> params = MessageCreateParams.builder()
|
StructuredMessageCreateParams<BookList> params = MessageCreateParams.builder()
|
||||||
.model(Model.CLAUDE_SONNET_4_6)
|
.model("claude-opus-5")
|
||||||
.maxTokens(16000L)
|
.maxTokens(16000L)
|
||||||
.outputConfig(BookList.class) // returns a typed builder
|
.outputConfig(BookList.class) // returns a typed builder
|
||||||
.addUserMessage("List 3 classic novels")
|
.addUserMessage("List 3 classic novels")
|
||||||
@@ -190,7 +190,7 @@ import com.anthropic.models.beta.messages.BetaCodeExecutionTool20260120;
|
|||||||
import com.anthropic.models.beta.messages.BetaRequestMcpServerUrlDefinition;
|
import com.anthropic.models.beta.messages.BetaRequestMcpServerUrlDefinition;
|
||||||
|
|
||||||
MessageCreateParams params = MessageCreateParams.builder()
|
MessageCreateParams params = MessageCreateParams.builder()
|
||||||
.model(Model.CLAUDE_OPUS_4_8)
|
.model("claude-opus-5")
|
||||||
.maxTokens(16000L)
|
.maxTokens(16000L)
|
||||||
.addBeta("mcp-client-2025-11-20")
|
.addBeta("mcp-client-2025-11-20")
|
||||||
.addTool(BetaToolBash20250124.builder().build())
|
.addTool(BetaToolBash20250124.builder().build())
|
||||||
|
|||||||
@@ -99,7 +99,7 @@ use Anthropic\Messages\ThinkingBlock;
|
|||||||
$message = $client->messages->create(
|
$message = $client->messages->create(
|
||||||
model: 'claude-opus-5',
|
model: 'claude-opus-5',
|
||||||
maxTokens: 16000,
|
maxTokens: 16000,
|
||||||
thinking: ['type' => 'adaptive', 'display' => 'summarized'], // display opt-in: default is omitted (empty thinking text) on Fable 5 / Mythos 5 / Claude Opus 5 / Opus 4.8 / 4.7
|
thinking: ['type' => 'adaptive', 'display' => 'summarized'], // display opt-in: default is omitted (empty thinking text) on Fable 5/5.1, Mythos 5/5.1, Claude Opus 5, Opus 4.8/4.7, and Claude Sonnet 5
|
||||||
messages: [
|
messages: [
|
||||||
['role' => 'user', 'content' => 'Solve: 27 * 453'],
|
['role' => 'user', 'content' => 'Solve: 27 * 453'],
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -258,7 +258,7 @@ If `cache_read_input_tokens` is zero across repeated identical-prefix requests,
|
|||||||
response = client.messages.create(
|
response = client.messages.create(
|
||||||
model="claude-opus-5",
|
model="claude-opus-5",
|
||||||
max_tokens=16000,
|
max_tokens=16000,
|
||||||
thinking={"type": "adaptive", "display": "summarized"}, # display opt-in: default is omitted (empty thinking text) on Fable 5 / Mythos 5 / Claude Opus 5 / Opus 4.8 / 4.7
|
thinking={"type": "adaptive", "display": "summarized"}, # display opt-in: default is omitted (empty thinking text) on Fable 5/5.1, Mythos 5/5.1, Claude Opus 5, Opus 4.8/4.7, and Claude Sonnet 5
|
||||||
output_config={"effort": "high"}, # low | medium | high | xhigh | max
|
output_config={"effort": "high"}, # low | medium | high | xhigh | max
|
||||||
messages=[{"role": "user", "content": "Solve this step by step..."}]
|
messages=[{"role": "user", "content": "Solve this step by step..."}]
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ Claude may return text, thinking blocks, or tool use. Handle each appropriately:
|
|||||||
with client.messages.stream(
|
with client.messages.stream(
|
||||||
model="claude-opus-5",
|
model="claude-opus-5",
|
||||||
max_tokens=64000,
|
max_tokens=64000,
|
||||||
thinking={"type": "adaptive", "display": "summarized"}, # display opt-in: default is omitted (empty thinking text) on Fable 5 / Mythos 5 / Claude Opus 5 / Opus 4.8 / 4.7
|
thinking={"type": "adaptive", "display": "summarized"}, # display opt-in: default is omitted (empty thinking text) on Fable 5/5.1, Mythos 5/5.1, Claude Opus 5, Opus 4.8/4.7, and Claude Sonnet 5
|
||||||
messages=[{"role": "user", "content": "Analyze this problem"}]
|
messages=[{"role": "user", "content": "Analyze this problem"}]
|
||||||
) as stream:
|
) as stream:
|
||||||
for event in stream:
|
for event in stream:
|
||||||
@@ -73,20 +73,96 @@ with client.messages.stream(
|
|||||||
|
|
||||||
## Streaming with Tool Use
|
## Streaming with Tool Use
|
||||||
|
|
||||||
The Python tool runner supports streaming: pass `stream=True` to `client.beta.messages.tool_runner(...)` and each iteration yields a stream you consume event-by-event, with `get_final_message()` for the accumulated message per turn (see `shared/tool-use-concepts.md` -> Tool Runner vs Manual Loop). Use the manual-loop pattern below only when you're not using the tool runner and need per-token streaming with tools:
|
The Python tool runner supports streaming: pass `stream=True` to `client.beta.messages.tool_runner(...)` and each iteration yields a stream you consume event-by-event, with `get_final_message()` for the accumulated message per turn (see `shared/tool-use-concepts.md` -> Tool Runner vs Manual Loop). Declare tool-runner tools with `@beta_tool(eager_input_streaming=True)` so their inputs stream as they are generated (default rule: `shared/tool-use-concepts.md` -> Eager input streaming). The runner never calls your function on unparseable input; the `ValueError` surfaces while you iterate the per-turn stream, so wrap the `for ... in runner` loop and, on failure, restart a new runner from a history you mirror while iterating, in this order for each yielded stream: take `message = stream.get_final_message()`, append it (the assistant turn), then check its `stop_reason` - on `max_tokens` with a `tool_use` present or on `refusal`, stop right there and never call `generate_tool_call_response()` for that turn (it executes the tools) - and only for a turn that continues append `runner.generate_tool_call_response()` (the matching `tool_result` user turn), exactly as `tool-use.md` does to resume `pause_turn`. The Python runner exposes no `params` read, a consumed runner cannot be iterated again, and a history missing the tool-result half of a continued turn is rejected by the API. `pause_turn` you resume yourself; a truncated text answer is simply the final message.
|
||||||
|
|
||||||
|
Use the manual-loop pattern below only when you're not using the tool runner and need per-token streaming with tools. Set `eager_input_streaming: True` on each user-defined tool. With eager streaming the server no longer validates the input: the Python SDK's tolerant parser returns a partial object for a truncated input (check `stop_reason == "max_tokens"`) and can return a silently truncated one for malformed JSON (validate the parsed input before running the tool); only JSON it cannot parse at all raises `ValueError` **from the stream iterator**, so that guard wraps the stream, not the final-message read. Schema validation is not path validation: the model-supplied `path` is untrusted output, so confine it to a project root before writing (`shared/tool-use-concepts.md` -> the text-editor security note):
|
||||||
|
|
||||||
```python
|
```python
|
||||||
with client.messages.stream(
|
import json
|
||||||
model="claude-opus-5",
|
from pathlib import Path
|
||||||
max_tokens=64000,
|
|
||||||
tools=tools,
|
|
||||||
messages=messages
|
|
||||||
) as stream:
|
|
||||||
for text in stream.text_stream:
|
|
||||||
print(text, end="", flush=True)
|
|
||||||
|
|
||||||
response = stream.get_final_message()
|
ROOT = Path.cwd().resolve()
|
||||||
# Continue with tool execution if response.stop_reason == "tool_use"
|
|
||||||
|
tools = [
|
||||||
|
{
|
||||||
|
"name": "write_file",
|
||||||
|
"description": "Write text to a file at the given path",
|
||||||
|
"eager_input_streaming": True, # stream large inputs as generated
|
||||||
|
"input_schema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"path": {"type": "string"},
|
||||||
|
"contents": {"type": "string"},
|
||||||
|
},
|
||||||
|
"required": ["path", "contents"],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
messages = [{"role": "user", "content": task}]
|
||||||
|
json_retries = 0
|
||||||
|
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
with client.messages.stream(
|
||||||
|
model="claude-opus-5",
|
||||||
|
max_tokens=64000,
|
||||||
|
tools=tools,
|
||||||
|
messages=messages,
|
||||||
|
) as stream:
|
||||||
|
for event in stream:
|
||||||
|
if event.type == "text":
|
||||||
|
print(event.text, end="", flush=True)
|
||||||
|
elif event.type == "input_json":
|
||||||
|
# Tool input fragment - arrives immediately with eager streaming
|
||||||
|
print(event.partial_json, end="", flush=True)
|
||||||
|
response = stream.get_final_message()
|
||||||
|
json_retries = 0 # the cap is on consecutive failures of one turn
|
||||||
|
except ValueError:
|
||||||
|
# JSON the SDK could not parse at all. It raised before the tool_use
|
||||||
|
# block completed, so there is no tool_use_id to answer; re-issue the
|
||||||
|
# turn (bounded). API errors are not ValueError and propagate.
|
||||||
|
json_retries += 1
|
||||||
|
if json_retries > 2:
|
||||||
|
raise
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Server-side tool hit its iteration limit: append the turn and re-send
|
||||||
|
if response.stop_reason == "pause_turn":
|
||||||
|
messages.append({"role": "assistant", "content": response.content})
|
||||||
|
continue
|
||||||
|
|
||||||
|
tool_uses = [b for b in response.content if b.type == "tool_use"]
|
||||||
|
if response.stop_reason == "refusal" or not tool_uses:
|
||||||
|
# end_turn, a text-only answer, or a refusal (which can cut a
|
||||||
|
# tool_use off mid-input): nothing to run
|
||||||
|
break
|
||||||
|
if response.stop_reason == "max_tokens":
|
||||||
|
# A truncated tool input parses as a valid partial object; don't run it.
|
||||||
|
raise RuntimeError("tool input truncated; retry with a higher max_tokens")
|
||||||
|
|
||||||
|
# The SDK's tolerant parser can return a silently truncated or mistyped
|
||||||
|
# input (for example at an unescaped inner quote), so validate first.
|
||||||
|
tool_results = []
|
||||||
|
for block in tool_uses:
|
||||||
|
args = block.input
|
||||||
|
if not (isinstance(args, dict) and isinstance(args.get("path"), str)
|
||||||
|
and isinstance(args.get("contents"), str)):
|
||||||
|
tool_results.append({"type": "tool_result", "tool_use_id": block.id, "is_error": True,
|
||||||
|
"content": json.dumps({"INVALID_JSON": json.dumps(args)})})
|
||||||
|
continue
|
||||||
|
# `path` is untrusted model output: resolve it and reject anything that
|
||||||
|
# escapes the project root (`..`, absolute paths, symlinks) before the
|
||||||
|
# write - schema validation alone does not check this.
|
||||||
|
target = (ROOT / args["path"]).resolve()
|
||||||
|
if not target.is_relative_to(ROOT):
|
||||||
|
tool_results.append({"type": "tool_result", "tool_use_id": block.id, "is_error": True,
|
||||||
|
"content": "path escapes the project root"})
|
||||||
|
continue
|
||||||
|
tool_results.append({"type": "tool_result", "tool_use_id": block.id,
|
||||||
|
"content": run_tool(block.name, {**args, "path": str(target)})})
|
||||||
|
messages.append({"role": "assistant", "content": response.content})
|
||||||
|
messages.append({"role": "user", "content": tool_results})
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -126,6 +126,34 @@ client.beta.sessions.events.send(
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Define an Outcome (default kickoff for deliverables)
|
||||||
|
|
||||||
|
When the session's job is to produce something checkable - an artifact, a report, a PR - kick off with `user.define_outcome` instead of `user.message`: the harness grades each iteration against your rubric and the agent revises until it passes. Send one or the other, never both. See [Outcomes](../../shared/managed-agents-outcomes.md) for the event reference and rubric-writing guidance.
|
||||||
|
|
||||||
|
```python
|
||||||
|
STARTER_RUBRIC = """# Report rubric - starter, tune the criteria
|
||||||
|
- Output is a single `report.md` in /mnt/session/outputs/
|
||||||
|
- Every claim cites a source URL
|
||||||
|
- Includes a summary table with one row per competitor
|
||||||
|
- Prices are current as of the run date and each row says where it was read from
|
||||||
|
- No placeholder text, TODOs, or empty sections remain
|
||||||
|
"""
|
||||||
|
|
||||||
|
client.beta.sessions.events.send(
|
||||||
|
session_id=session.id,
|
||||||
|
events=[
|
||||||
|
{
|
||||||
|
"type": "user.define_outcome",
|
||||||
|
"description": "Write a competitor-pricing report as report.md",
|
||||||
|
"rubric": {"type": "text", "content": STARTER_RUBRIC},
|
||||||
|
"max_iterations": 5, # optional; default 3, max 20
|
||||||
|
}
|
||||||
|
],
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Stream Events (SSE)
|
## Stream Events (SSE)
|
||||||
|
|
||||||
```python
|
```python
|
||||||
|
|||||||
@@ -103,7 +103,7 @@ For design and placement - the prefix-match invariant, classifying inputs by sta
|
|||||||
- **Explicit breakpoints when many independent conversations share a static prefix** (or prefix layers change at different rates). Automatic caching only amortizes within one conversation; in the cookbook's worked example, one explicit breakpoint on the static system prefix roughly halved cost per task across a queue of independent tasks. The robust shape for agent loops - one explicit breakpoint on the static prefix plus top-level automatic caching for the tail - and the cases where automatic alone is a pure surcharge are in `shared/prompt-caching.md` § Automatic vs explicit breakpoints.
|
- **Explicit breakpoints when many independent conversations share a static prefix** (or prefix layers change at different rates). Automatic caching only amortizes within one conversation; in the cookbook's worked example, one explicit breakpoint on the static system prefix roughly halved cost per task across a queue of independent tasks. The robust shape for agent loops - one explicit breakpoint on the static prefix plus top-level automatic caching for the tail - and the cases where automatic alone is a pure surcharge are in `shared/prompt-caching.md` § Automatic vs explicit breakpoints.
|
||||||
- **Use the 1-hour cache duration when the loop waits on humans between turns.** It writes at 2x instead of 1.25x and pays for itself on the first prevented miss - a miss resends the whole prefix at full price and writes it again. Decide from the start-to-start gap between requests (generation time counts against the TTL) - the table in `shared/prompt-caching.md` § Choosing the TTL.
|
- **Use the 1-hour cache duration when the loop waits on humans between turns.** It writes at 2x instead of 1.25x and pays for itself on the first prevented miss - a miss resends the whole prefix at full price and writes it again. Decide from the start-to-start gap between requests (generation time counts against the TTL) - the table in `shared/prompt-caching.md` § Choosing the TTL.
|
||||||
- **Audit for mid-task cache-breakers**: dynamic content above a breakpoint; changing `thinking` or `effort` between requests (always invalidates the messages cache, and on some models the tools+system cache too - `shared/prompt-caching.md` § Invalidation hierarchy); changing a task budget mid-task; every context-editing pass; switching models mid-conversation (caches are per-model).
|
- **Audit for mid-task cache-breakers**: dynamic content above a breakpoint; changing `thinking` or `effort` between requests (always invalidates the messages cache, and on some models the tools+system cache too - `shared/prompt-caching.md` § Invalidation hierarchy); changing a task budget mid-task; every context-editing pass; switching models mid-conversation (caches are per-model).
|
||||||
- **Verify from usage, not from code review - and re-verify after every prompt-assembly change**: on a warmed-up loop, `cache_read_input_tokens` should dominate regular `input_tokens`, and `cache_creation_input_tokens` should be roughly one turn's worth, not the whole conversation. If it isn't, hunt for a cache-breaker with the healthy-loop signature and payload-diff method in `shared/prompt-caching.md` § Verifying cache hits - unless the workload's input is mostly unique per-request payload (which can never cache), or the misses are concurrent-batch artifacts (§ 2.5); neither is a breaker, and neither has a fix.
|
- **Verify from usage, not from code review - and re-verify after every prompt-assembly change**: on a warmed-up loop, `cache_read_input_tokens` should dominate regular `input_tokens`, and `cache_creation_input_tokens` should be roughly one turn's worth, not the whole conversation. If it isn't, hunt for a cache-breaker with the healthy-loop signature in `shared/prompt-caching.md` § Verifying cache hits - unless the workload's input is mostly unique per-request payload (which can never cache), or the misses are concurrent-batch artifacts (§ 2.5); neither is a breaker, and neither has a fix. To localize the breaker, reach for cache diagnostics first on the first-party Claude API (beta; availability in `shared/platform-availability.md`): send the beta header `cache-diagnosis-2026-04-07` on every request, pass the previous response's `id` as `diagnostics.previous_message_id`, and the response's `diagnostics` object names where the two requests diverged - no payload logging needed. On other platforms, fall back to the payload-diff method in the same section.
|
||||||
- **The cache probe, when there is no usage history to read**: a scratch script for the project's own stack that sends one representative request twice, byte-identical; prints all four usage meters (`input_tokens`, `cache_creation_input_tokens`, `cache_read_input_tokens`, `output_tokens`) for both; and exits non-zero if the second request's `cache_read_input_tokens` is zero. Ship it alongside the caching diff so the user can run the before/after themselves. It spends real tokens and may execute the project's tools - run it only under the standing approval rule, and point it at a scratch environment if the request's tools mutate state.
|
- **The cache probe, when there is no usage history to read**: a scratch script for the project's own stack that sends one representative request twice, byte-identical; prints all four usage meters (`input_tokens`, `cache_creation_input_tokens`, `cache_read_input_tokens`, `output_tokens`) for both; and exits non-zero if the second request's `cache_read_input_tokens` is zero. Ship it alongside the caching diff so the user can run the before/after themselves. It spends real tokens and may execute the project's tools - run it only under the standing approval rule, and point it at a scratch environment if the request's tools mutate state.
|
||||||
|
|
||||||
### 2.2 Input tokens - progressive disclosure
|
### 2.2 Input tokens - progressive disclosure
|
||||||
@@ -167,7 +167,7 @@ From here down, every lever trades capability for cost. Sweep on the eval, one c
|
|||||||
|
|
||||||
### 2.7 Model selection - last, deliberately
|
### 2.7 Model selection - last, deliberately
|
||||||
|
|
||||||
Model choice constrains the intelligence ceiling, which is why it comes after every lever that doesn't.
|
Model choice constrains the intelligence ceiling, which is why it comes after every lever that doesn't. (The exception is when the project has an eval and you are running the hillclimb loop: there `shared/evals/cost-hillclimb.md` walks model x effort early, because an eval can detect the case where a stronger model at lower effort is the cheaper cell. Without an eval that case is invisible and a model swap stays the riskiest change - keep it last.)
|
||||||
|
|
||||||
- **Price candidates in cost per completed task on your own traffic**, including the larger model at reduced effort - per-token price lists do not predict the ranking. In Anthropic's runs, Claude Fable 5 at `low` effort beat Claude Sonnet 5 on a deep-research benchmark while costing about 10% less per task; on a coding subset both models largely saturate, Claude Opus 5 matched Claude Fable 5 (91.7% versus 91.3%) at about 60% of its cost. For most agent workloads, start with Claude Opus 5. At the other end, Claude Haiku 4.5 answered knowledge questions at about a tenth of Claude Opus 5's cost per question at 63% accuracy versus 92% - it fits high-volume work with checkable outputs, not long agentic loops.
|
- **Price candidates in cost per completed task on your own traffic**, including the larger model at reduced effort - per-token price lists do not predict the ranking. In Anthropic's runs, Claude Fable 5 at `low` effort beat Claude Sonnet 5 on a deep-research benchmark while costing about 10% less per task; on a coding subset both models largely saturate, Claude Opus 5 matched Claude Fable 5 (91.7% versus 91.3%) at about 60% of its cost. For most agent workloads, start with Claude Opus 5. At the other end, Claude Haiku 4.5 answered knowledge questions at about a tenth of Claude Opus 5's cost per question at 63% accuracy versus 92% - it fits high-volume work with checkable outputs, not long agentic loops.
|
||||||
- **Price the tail, not the median.** Compare models on the hardest tenth of the workload: on the typical task every model looks similar and the cheapest looks best, but the bill is decided by the tasks the cheap model fails - and the tail is where the money goes even when nothing fails (on one 20-problem research run, two problems carried 43% of the spend).
|
- **Price the tail, not the median.** Compare models on the hardest tenth of the workload: on the typical task every model looks similar and the cheapest looks best, but the bill is decided by the tasks the cheap model fails - and the tail is where the money goes even when nothing fails (on one 20-problem research run, two problems carried 43% of the spend).
|
||||||
|
|||||||
@@ -8,8 +8,9 @@ This file documents HTTP error codes returned by the Claude API, their common ca
|
|||||||
| ---- | ----------------------- | --------- | ------------------------------------ |
|
| ---- | ----------------------- | --------- | ------------------------------------ |
|
||||||
| 400 | `invalid_request_error` | No | Invalid request format or parameters |
|
| 400 | `invalid_request_error` | No | Invalid request format or parameters |
|
||||||
| 401 | `authentication_error` | No | Invalid or missing API key |
|
| 401 | `authentication_error` | No | Invalid or missing API key |
|
||||||
| 403 | `permission_error` | No | API key lacks permission |
|
| 402 | `billing_error` | No | Billing or payment problem |
|
||||||
| 404 | `not_found_error` | No | Invalid endpoint or model ID |
|
| 403 | `permission_error` | No | Not allowed for this credential |
|
||||||
|
| 404 | `not_found_error` | No | Unknown endpoint, or model not found or not available to your org |
|
||||||
| 413 | `request_too_large` | No | Request exceeds size limits |
|
| 413 | `request_too_large` | No | Request exceeds size limits |
|
||||||
| 429 | `rate_limit_error` | Yes | Too many requests |
|
| 429 | `rate_limit_error` | Yes | Too many requests |
|
||||||
| 500 | `api_error` | Yes | Anthropic service issue |
|
| 500 | `api_error` | Yes | Anthropic service issue |
|
||||||
@@ -26,6 +27,7 @@ This file documents HTTP error codes returned by the Claude API, their common ca
|
|||||||
- Invalid parameter types (e.g., string where integer expected)
|
- Invalid parameter types (e.g., string where integer expected)
|
||||||
- Empty messages array
|
- Empty messages array
|
||||||
- Messages not alternating user/assistant
|
- Messages not alternating user/assistant
|
||||||
|
- An `anthropic-beta` value that does not exist or is not enabled for your organization. Both cases return the same message: ``Unexpected value(s) `<value>` for the `anthropic-beta` header.``
|
||||||
|
|
||||||
**Example error:**
|
**Example error:**
|
||||||
|
|
||||||
@@ -66,11 +68,13 @@ This file documents HTTP error codes returned by the Claude API, their common ca
|
|||||||
|
|
||||||
**Causes:**
|
**Causes:**
|
||||||
|
|
||||||
- API key doesn't have access to the requested model
|
- The credential's organization or workspace is not allowed to perform this operation.
|
||||||
- Organization-level restrictions
|
- The request was blocked by an access requirement, such as a region restriction or identity verification, for a model your organization can otherwise use. The message says what to do.
|
||||||
- Attempting to access beta features without beta access
|
- Rarely, the model server denies a request that passed the API's access check. The message is `Access to this model requires an access grant your request does not have.`
|
||||||
|
|
||||||
**Fix:** Check your API key permissions in the Console. You may need a different API key or to request access to specific features.
|
A model your organization cannot use is normally a 404, not a 403 (see below). A beta header your organization is not enabled for is a 400.
|
||||||
|
|
||||||
|
**Fix:** Check your organization's access and workspace settings in the Console.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -80,9 +84,12 @@ This file documents HTTP error codes returned by the Claude API, their common ca
|
|||||||
|
|
||||||
- Typo in model ID (e.g., `claude-sonnet-4.6` instead of `claude-sonnet-4-6`)
|
- Typo in model ID (e.g., `claude-sonnet-4.6` instead of `claude-sonnet-4-6`)
|
||||||
- Using deprecated model ID
|
- Using deprecated model ID
|
||||||
|
- A model ID that exists but is not available to your organization
|
||||||
- Invalid API endpoint
|
- Invalid API endpoint
|
||||||
|
|
||||||
**Fix:** Use exact model IDs from the models documentation. You can use aliases (e.g., `claude-opus-5`).
|
A model that does not exist and a model your organization cannot use return the same response, `not_found_error` with a message that starts with `model: <id>`. The API does not reveal whether a model exists to callers who cannot use it.
|
||||||
|
|
||||||
|
**Fix:** Use exact model IDs from the models documentation. You can use aliases (e.g., `claude-opus-5`). To see which models your organization can use, call `GET /v1/models`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -114,8 +121,9 @@ Some 400 errors are specifically related to parameter validation:
|
|||||||
- **Claude Opus 5:** `thinking: {type: "disabled"}` returns 400 when `effort` is `xhigh` or `max` - it is accepted at `high` or below. Thinking is on by default, so omitting the param runs adaptive rather than disabling it.
|
- **Claude Opus 5:** `thinking: {type: "disabled"}` returns 400 when `effort` is `xhigh` or `max` - it is accepted at `high` or below. Thinking is on by default, so omitting the param runs adaptive rather than disabling it.
|
||||||
- **Fable 5/5.1 only:** an explicit `thinking: {type: "disabled"}` returns 400 at any effort (it is accepted on Opus 4.8/4.7). Omit the `thinking` param entirely instead.
|
- **Fable 5/5.1 only:** an explicit `thinking: {type: "disabled"}` returns 400 at any effort (it is accepted on Opus 4.8/4.7). Omit the `thinking` param entirely instead.
|
||||||
- **Fable 5/5.1, Mythos 5/5.1:** if the organization or workspace is set to zero data retention (ZDR) - or any retention below the required 30 days - then **all** requests to these models return `400 invalid_request_error` ("In order to access this model, your organization or workspace must have data retention enabled."), even with a perfectly valid payload; ZDR only if expressly authorized by Anthropic. Check the retention configuration before debugging the request body.
|
- **Fable 5/5.1, Mythos 5/5.1:** if the organization or workspace is set to zero data retention (ZDR) - or any retention below the required 30 days - then **all** requests to these models return `400 invalid_request_error` ("In order to access this model, your organization or workspace must have data retention enabled."), even with a perfectly valid payload; ZDR only if expressly authorized by Anthropic. Check the retention configuration before debugging the request body.
|
||||||
- **Claude Fable 5.1 / Claude Mythos 5.1 (and Mythos Preview):** `tool_choice: {type: "any"}` or `{type: "tool", name: ...}` returns 400 `tool_choice: type "tool" and "any" are not supported for this model.` - also on `count_tokens` and Batches. Use `{type: "auto"}` plus a prompt instruction (`strict: true` for schema-valid arguments), or structured outputs.
|
- **Claude Opus 5.5:** `thinking: {type: "disabled"}` or `{type: "enabled", budget_tokens: N}` returns 400 `"thinking.type.disabled" is not supported for this model. Use "thinking.type.adaptive" and "output_config.effort" to control thinking behavior.` (`"thinking.type.enabled"` for the budget form) at every effort level - omit `thinking` and lower `output_config.effort` instead. A `tools` entry of type `computer_20251124` returns 400 `'claude-opus-5-5' does not support tool types: computer_20251124.` followed by `Did you mean one of` and the accepted types - declare `{type: "computer_toolset_20260801"}` instead (no beta header, no `name` / display size). See `shared/model-migration.md` -> Migrating to Claude Opus 5.5.
|
||||||
- **Claude Fable 5.1 / Claude Mythos 5.1 - preserved thinking / history-editing check (new accounts created on/after 2026-08-31, or any request that sets `prefix_mismatch_behavior`):** ``messages.N.content.M: Invalid `signature` in `thinking` block. The block is bound to a different conversation. Remove the block, or set `thinking.block_binding.prefix_mismatch_behavior` to "drop_block".`` (plus a sentence naming the beta header when it wasn't sent, and optionally one naming the first message that changed) means the system prompt, tool list, or an earlier message changed since that thinking block was produced. Retrying the same body never clears it; `count_tokens` returns the same 400. (In the Message Batches API the *unset* default drops the failing blocks instead of failing the item - a Batches item fails as `errored` only with `prefix_mismatch_behavior: "error"` set.) Strip the named block and every thinking block after it and retry once, or resend with `thinking.block_binding.prefix_mismatch_behavior: "drop_block"` under beta `thinking-binding-controls-2026-08-01` (where the controls beta is offered - Claude API / Claude Platform on AWS at launch, per model on Bedrock and Google Cloud, not on Foundry: `shared/platform-availability.md`; elsewhere use the strip-and-retry path; without the header that field is a 400 ending `block_binding: Extra inputs are not permitted`); then fix the harness so it stops editing history (see `shared/model-migration.md` -> Migrating to Claude Fable 5.1 from Claude Fable 5). The same leading clause with *no* "bound to a different conversation" sentence is a tampered signature - always a 400, regardless of the setting.
|
- **Claude Fable 5.1 / Claude Mythos 5.1 / Claude Opus 5.5 (and Mythos Preview):** `tool_choice: {type: "any"}` or `{type: "tool", name: ...}` returns 400 `tool_choice: type "tool" and "any" are not supported for this model.` - also on `count_tokens` and Batches. Use `{type: "auto"}` plus a prompt instruction (`strict: true` for schema-valid arguments), or structured outputs.
|
||||||
|
- **Claude Fable 5.1 / Claude Mythos 5.1 / Claude Opus 5.5 - preserved thinking / history-editing check (new accounts created on/after 2026-08-31 on every platform, or any request that sets `prefix_mismatch_behavior`):** ``messages.N.content.M: Invalid `signature` in `thinking` block. The block is bound to a different conversation. Remove the block, or set `thinking.block_binding.prefix_mismatch_behavior` to "drop_block".`` (plus a sentence naming the beta header when it wasn't sent, and optionally one naming the first message that changed) means the system prompt, tool list, or an earlier message changed since that thinking block was produced. Retrying the same body never clears it; `count_tokens` returns the same 400. (In the Message Batches API the *unset* default drops the failing blocks instead of failing the item - a Batches item fails as `errored` only with `prefix_mismatch_behavior: "error"` set.) Strip the named block and every thinking block after it and retry once, or resend with `thinking.block_binding.prefix_mismatch_behavior: "drop_block"` under beta `thinking-binding-controls-2026-08-01` (where the controls beta is offered - Claude API / Claude Platform on AWS at launch, per model on Bedrock and Google Cloud, not on Foundry: `shared/platform-availability.md`; elsewhere use the strip-and-retry path; without the header that field is a 400 ending `block_binding: Extra inputs are not permitted`); then fix the harness so it stops editing history (see `shared/model-migration.md` -> Migrating to Claude Fable 5.1 from Claude Fable 5). The same leading clause with *no* "bound to a different conversation" sentence is a tampered signature - always a 400, regardless of the setting.
|
||||||
|
|
||||||
**Common mistake with extended thinking on older models (Opus 4.6 and earlier):**
|
**Common mistake with extended thinking on older models (Opus 4.6 and earlier):**
|
||||||
|
|
||||||
@@ -177,8 +185,10 @@ thinking: budget_tokens=10000, max_tokens=16000
|
|||||||
| `budget_tokens` on Claude Opus 5 / Fable 5/5.1 / Opus 4.8 / 4.7 | 400 | Use `thinking: {type: "adaptive"}` |
|
| `budget_tokens` on Claude Opus 5 / Fable 5/5.1 / Opus 4.8 / 4.7 | 400 | Use `thinking: {type: "adaptive"}` |
|
||||||
| `thinking: {type: "disabled"}` on Fable 5/5.1 | 400 | Omit the `thinking` param entirely (accepted on Opus 4.8/4.7) |
|
| `thinking: {type: "disabled"}` on Fable 5/5.1 | 400 | Omit the `thinking` param entirely (accepted on Opus 4.8/4.7) |
|
||||||
| Org set to ZDR / retention below 30 days (Fable 5/5.1, Mythos 5/5.1) | 400 on every request | Fix the org's data-retention configuration - the payload isn't the problem |
|
| Org set to ZDR / retention below 30 days (Fable 5/5.1, Mythos 5/5.1) | 400 on every request | Fix the org's data-retention configuration - the payload isn't the problem |
|
||||||
| `tool_choice` `any` / `tool` on Claude Fable 5.1 / Claude Mythos 5.1 / Mythos Preview | 400 | `{type: "auto"}` + name the tool in the prompt (`strict: true` for schema-valid args), or structured outputs |
|
| `thinking: {type: "disabled"}` or `budget_tokens` on Claude Opus 5.5 | 400 `"thinking.type.disabled" is not supported for this model` | Omit `thinking`; control depth with `output_config.effort` (default `medium`) |
|
||||||
| Edited history replayed with thinking blocks (Claude Fable 5.1 / Claude Mythos 5.1, preserved thinking) | 400 `Invalid signature in thinking block ... bound to a different conversation` | Stop editing history - keep the transcript append-only, using mid-conversation `role: "system"` / tool-change messages, turn-scoped `clear_at` reminders that are never deleted, server-side context editing, and summary-only compaction instead of edits; recover once by stripping the named block and every thinking block after it (text and tool calls stay), or `prefix_mismatch_behavior: "drop_block"` |
|
| `computer_20251124` tool on Claude Opus 5.5 | 400 `does not support tool types: computer_20251124` | `{type: "computer_toolset_20260801"}` - no beta header, no `name` / display size; update the agent loop for member tool calls |
|
||||||
|
| `tool_choice` `any` / `tool` on Claude Fable 5.1 / Claude Mythos 5.1 / Claude Opus 5.5 / Mythos Preview | 400 | `{type: "auto"}` + name the tool in the prompt (`strict: true` for schema-valid args), or structured outputs |
|
||||||
|
| Edited history replayed with thinking blocks (Claude Fable 5.1 / Claude Mythos 5.1 / Claude Opus 5.5, preserved thinking) | 400 `Invalid signature in thinking block ... bound to a different conversation` | Stop editing history - keep the transcript append-only, using mid-conversation `role: "system"` / tool-change messages, turn-scoped `clear_at` reminders that are never deleted, server-side context editing, and summary-only compaction instead of edits; recover once by stripping the named block and every thinking block after it (text and tool calls stay), or `prefix_mismatch_behavior: "drop_block"` |
|
||||||
| `thinking.block_binding` without `thinking-binding-controls-2026-08-01` | 400 `block_binding: Extra inputs are not permitted` | Send the beta header where the controls beta is offered (`shared/platform-availability.md`); elsewhere remove `block_binding` and use strip-and-retry |
|
| `thinking.block_binding` without `thinking-binding-controls-2026-08-01` | 400 `block_binding: Extra inputs are not permitted` | Send the beta header where the controls beta is offered (`shared/platform-availability.md`); elsewhere remove `block_binding` and use strip-and-retry |
|
||||||
| `budget_tokens` >= `max_tokens` (older models) | 400 | Ensure `budget_tokens` < `max_tokens` |
|
| `budget_tokens` >= `max_tokens` (older models) | 400 | Ensure `budget_tokens` < `max_tokens` |
|
||||||
| Typo in model ID | 404 | Use valid model ID like `claude-opus-5` |
|
| Typo in model ID | 404 | Use valid model ID like `claude-opus-5` |
|
||||||
@@ -251,7 +261,7 @@ if err != nil {
|
|||||||
|
|
||||||
### Error `.type` Field
|
### Error `.type` Field
|
||||||
|
|
||||||
All `APIStatusError` subclasses now expose a `.type` property (Python: `.type`, TypeScript: `.type`, Java: `.errorType()`, Go: `.Type()`, Ruby: `.type`, PHP: `.type`) that returns the API error type string (e.g., `"invalid_request_error"`, `"authentication_error"`, `"rate_limit_error"`, `"overloaded_error"`). Use this for programmatic error classification when you need finer granularity than the HTTP status code - for example, distinguishing `"billing_error"` from `"permission_error"` (both map to 403).
|
All `APIStatusError` subclasses now expose a `.type` property (Python: `.type`, TypeScript: `.type`, Java: `.errorType()`, Go: `.Type()`, Ruby: `.type`, PHP: `.type`) that returns the API error type string (e.g., `"invalid_request_error"`, `"authentication_error"`, `"rate_limit_error"`, `"overloaded_error"`). Use this to classify errors by type name instead of by status code. `"billing_error"` is a 402 and `"permission_error"` is a 403.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
except anthropic.APIStatusError as e:
|
except anthropic.APIStatusError as e:
|
||||||
|
|||||||
235
skills/claude-api/shared/evals/build-eval.md
Normal file
235
skills/claude-api/shared/evals/build-eval.md
Normal file
@@ -0,0 +1,235 @@
|
|||||||
|
# Building an Eval for a Claude-Powered Application
|
||||||
|
|
||||||
|
> **If you arrived via `/claude-api build-eval`:** this is the right file. If the user passed an argument, treat it as their answer to the first question below - what they want to measure. Run the interview - don't summarize it back to the user, ask the questions and work through the sign-offs. The goal is a runnable eval the user trusts, not a document about evals.
|
||||||
|
|
||||||
|
This guide is for when a user wants to measure whether their Claude app is working - typically because they're about to change something (migrate to a new model, rewrite a prompt, add a tool) and need to know whether the change helped. Your job is to build an eval that could be used to make deploy decisions.
|
||||||
|
|
||||||
|
An eval, for this purpose, is three things: **a set of input examples**, **a way to run the app against each input**, and **a way to grade each output**. The runner is usually a plain Python script; it could be a CLI, a pytest suite, or whatever fits their stack. The exact shape matters much less than whether the user looks at the inputs and says "yes, those are the cases I care about" and looks at the grades and says "yes, that's measuring the right thing." Do not impose a framework. Read how their codebase is already structured and fit the eval into it.
|
||||||
|
|
||||||
|
Stay recommendation-forward throughout: every decision goes through `AskUserQuestion` with your pick listed first and labelled "(Recommended)", so a user who trusts your defaults clicks through in seconds and one who doesn't can override at the exact point they care about. It is much easier to react to "here's what I'd do - OK?" than to answer an open question from scratch.
|
||||||
|
|
||||||
|
> **Talking to the user.** These steps are your execution plan, not a script to narrate. Keep user-facing messages short and outcome-focused: what you built, the number it produced, what you need them to look at, a path or link to open. Don't walk the user through which step you're on, which files you're writing, or internal bookkeeping unless they ask. One concise update per step is enough; instead of listing individual cases, prompts, or per-case scores in the chat, prefer to give the `report.html` path and a one-line headline - call out one or two specific cases in chat only when there's a reason the user should look at those first. When you need a decision - grader type, where inputs come from, what "good" means, which guardrails matter - use the `AskUserQuestion` tool rather than free-text prose: batch up to four related questions into one call, give each two to four concrete options with your recommendation listed first and labelled "(Recommended)", and don't add your own "Other" option - the tool appends a free-text one automatically. If `AskUserQuestion` isn't available (headless runs), fall back to one short question at a time.
|
||||||
|
|
||||||
|
There are two sign-offs you always need - the inputs and the grading method. Each is a literal pause: state what you're proposing, ask for approval, and **wait for a clear yes** - not silence, and not your own judgment that it's fine. If getting to a yes took several rounds of back-and-forth, restate the final version in one message and confirm it once more before you build on it; it's easy for both sides to lose track of what was actually agreed after five refinements. They're the only places you wait for prose, not a click. Everything else is guidance; adapt freely to the user's situation.
|
||||||
|
|
||||||
|
**Read `shared/evals/eval-audit.md` now, before Step 0, and keep it in view throughout.** It is the health checklist every eval must satisfy - task design, harness design, metrics hygiene, grader design, and whether the eval can detect the change the user is after. While you build, treat each item as a construction requirement the runner, grader, and case set meet by default; when the user brings an existing eval, it is the verification you run on it; and before the first full paid pass you run it once more against what you built and report per its §6.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 0: Understand what's being evaluated
|
||||||
|
|
||||||
|
For a complete worked example of this flow end to end - cases, labeling policy, runner, and a five-round hillclimb - see `shared/evals/examples/clawd-triggering/` (in the EAP package and the source repo; the CLI does not extract it, so skip it if the directory is absent).
|
||||||
|
|
||||||
|
Start by asking what the user actually wants to measure:
|
||||||
|
|
||||||
|
> What exactly are you trying to evaluate - which use-case or feature? If this app does several things, which one do you need a number for first?
|
||||||
|
|
||||||
|
One app can easily have ten things worth evaluating - a classifier here, a summarizer there, an agent loop elsewhere - and they need different inputs and different grading. Pin down one. One flow per eval; don't try to build a grand unified benchmark. If the user invoked `/claude-api build-eval` with an argument, take that as their answer and confirm it rather than asking from scratch.
|
||||||
|
|
||||||
|
Then make sure you and the user agree on what "the app" is for that flow. Find the entry point: the function, endpoint, or script that takes a user input and produces the output that matters. Read enough of it to know the model, **which provider it's calling** (first-party Anthropic API, Claude Platform on AWS, Amazon Bedrock, Vertex AI, Foundry), the system prompt, the tools, and what the output looks like (text, JSON, a tool trajectory, a file). If the entry point is a streaming proxy or wrapper that doesn't surface `model`, `usage`, or `stop_reason`, propose a small additive change to its final event so the runner can record them per case - without those the report can't derive cost or flag truncation. Any code the runner writes - judge calls included - must use the same provider's client class and model-ID format; see `SKILL.md` and its referenced `shared/` docs for the per-provider details.
|
||||||
|
|
||||||
|
If the flow depends on live external state - a database, a search index, a customer's private documents - note that now. You'll need fixtures or a test instance to make the eval reproducible, and whether those exist will shape everything downstream. Prefer measuring real *outcomes* through the real entry point whenever possible. Only when that can't be run safely or reproducibly - because tools have real-world side effects (send emails, write to databases, delete files) or depend on live external state that's since changed - stub those tools (optionally replaying canned tool results) and grade the model's tool calls and response text instead of the downstream effect.
|
||||||
|
|
||||||
|
Also ask what the system needs per example besides the user message:
|
||||||
|
|
||||||
|
> What does one request into this flow carry besides the text - attached files or images? User metadata or profile? Summarized memory of prior conversations? A container image or workspace for an agent to run in?
|
||||||
|
|
||||||
|
The answer shapes what an eval "input" is. Often it's just a prompt string; sometimes it's a prompt plus a PDF, a user profile, a conversation prefix, or a path to a docker image for an agentic environment. Don't force a schema - just find out what the app actually consumes so each eval case carries everything the entry point needs. If the input is a multi-turn conversation, also pin down what gets graded: the final response only, each assistant turn independently, or the trajectory as a whole. A turn can look fine on its own but be downstream of an earlier wrong turn - grading per-turn will call that "good" when the conversation isn't. Default to grading the conversation outcome unless the user explicitly wants per-turn.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 1: Find or build the input set
|
||||||
|
|
||||||
|
Ask the user:
|
||||||
|
|
||||||
|
> Do you already have any of the pieces - a set of test cases (even an informal spreadsheet), a grader or scoring function, or a harness/script that runs the app over inputs?
|
||||||
|
|
||||||
|
**Whatever exists, use it; build only what's missing.** An existing grader gets wrapped, not rewritten; an existing harness gets a thin adapter that emits `results.jsonl`/`traces/` in the Step 3 shape (that shape is the only contract the report needs - `report/SCHEMA.md`), not replaced by the scaffold. Say which pieces you're reusing and which you're adding before you write anything. **If there are cases:** read them, then run `eval-audit.md` against them - cases, runner, and grader - and report what you find per its §6 before deciding how much to reuse. Two questions to ask the user directly rather than infer: whether the inputs are still representative of real traffic, and **where the expected outputs came from** - human-written, human-verified, or a model's outputs (which model). Gold derived from a model under comparison - the incumbent in a migration, especially - makes reference-match scoring reward imitation of that model; say so and prefer a rubric or pairwise judge, or human-verify a sample first. If the audit and the user both trust it, use it as the starting point and reuse the grading. If only partly ("the inputs are fine but the grading is vibes"), keep the inputs and rebuild the grading. If not, treat it as one source among several.
|
||||||
|
|
||||||
|
**Either way,** ask where realistic inputs could come from. Work down this list and use the first source that's available and that the user is comfortable using:
|
||||||
|
|
||||||
|
1. **Production transcripts or logs.** The highest-fidelity source. Ask where they live (Datadog, a database, S3, a logging endpoint) and whether you can pull a sample. Before you pull anything, confirm the source is **usable in practice**, not just available right now: *Is there a retention policy that will force you to delete this data? Does it contain PII that can't sit in a repo?* An eval built on data the user can't keep is an eval they can't re-run next quarter - that's worse than a synthetic one they can. If either answer is yes, three options: store only the **identifiers** in the repo and have the runner fetch the real inputs at eval time (nothing sensitive ever lands on disk); have the user pull and anonymize a sample themselves; or rewrite each real input into a synthetic one that preserves the shape and difficulty but replaces the identifying content (show the user the rewrites before using them).
|
||||||
|
2. **Bug reports, support tickets, or "this went wrong" examples.** Often the most valuable inputs are the ones someone complained about. Ask if there's a channel or tracker where these collect.
|
||||||
|
3. **Hand-written by the user.** Ask them for five to ten examples off the top of their head. These are usually skewed toward what's salient to them rather than what's frequent, so treat them as a seed, not the whole set.
|
||||||
|
4. **Synthesized by you from the codebase.** Read the system prompt, the tool descriptions, and any docs or tests, and generate candidate inputs that exercise the flow. This is the lowest-fidelity option - make that clear to the user, and don't do it cold: first get three to five real examples from them (source 3) plus a sentence on what makes a case *hard* in this domain, then synthesize variations of those rather than inventing from the prompt alone. Evals synthesized with nothing real to anchor on come out simplistic, and steering them afterwards costs the user more than writing cases would have.
|
||||||
|
|
||||||
|
Aim for somewhere between fifteen and a hundred inputs for a first eval. Fewer than fifteen and a single flaky case swings the score; well past a hundred and the user won't actually review them all, which defeats the point of the sign-off - for a big set, have them read a stratified sample and lean on `eval-audit.md` §1's programmatic checks for the rest. You can always grow the set later. One caveat: if the user already knows they'll want to **hill-climb** on this eval afterwards, size the set against the change they hope to detect, not just against reviewability - `eval-audit.md` §5 has the arithmetic (noise floor ~ `1/sqrt(n·reps)` for a pass-rate; 25 cases × 2 reps is about ±14 points). Show them that number next to the improvement they'd act on, and budget cases and reps together now: fifty-plus inputs with a random held-out slice, or fewer inputs with more reps, are two routes to the same resolution. Finding out after several paid rounds that the eval couldn't have seen the win is the expensive way.
|
||||||
|
|
||||||
|
### Get the inputs approved
|
||||||
|
|
||||||
|
Show the user the actual inputs - all of them, not a summary. Any observation you offer about the set should be quantitative - counts, named cases, measured scores - not "looks reasonable." Default to rendering them as a simple formatted HTML page (one case per section, with any attached files or metadata shown inline), but **prefer whatever the user already uses to look at prompts and transcripts** - if they have an existing viewer, a notebook they like, or a markdown convention, put the inputs there instead. Match their workflow; the point is that they actually read them. Ask:
|
||||||
|
|
||||||
|
> Here are the N inputs I'm proposing to use. Please skim them. Are these representative of what your app actually sees? Are there obvious cases missing, or cases in here that don't matter?
|
||||||
|
|
||||||
|
If you need the user to label or classify a specific case, quote the relevant lines of that case directly in your question - don't send them hunting for "case 17."
|
||||||
|
|
||||||
|
Do not proceed until the user has looked and said yes. If they say "mostly, but...", fix the "but" and show them again. If you sourced inputs from production data, this is also the point to confirm they're comfortable with this exact set living in their repo. **The user's sign-off here is the thing that makes them trust the final number** - skipping it produces an eval that is technically runnable and practically ignored.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 2: Decide how to grade
|
||||||
|
|
||||||
|
Start by proactively offering a menu of side-channel metrics the runner can log on every case, and ask the user which ones matter for their product:
|
||||||
|
|
||||||
|
> Besides output quality, here's what I can record per case - output length (words/tokens), tool-call count, whether the model refused, whether it hit `max_tokens`, format adherence (if output is structured), cost, latency. Which of these matter for this flow? Anything with a hard product ceiling (e.g., "must answer in under 10 s")?
|
||||||
|
|
||||||
|
The picked metrics become `perf_fields` in `_state.json` and show as columns in the report (full viewer) and in hillclimb's status table; unpicked ones don't. This choice is only about what to *display* - the runner records `model` + `usage` regardless, so `cost_usd` can be added later if they change their mind. It says nothing about whether the user wants a spend estimate for the eval itself; don't volunteer one unless they ask.
|
||||||
|
|
||||||
|
If the dataset has labeled positive and negative cases - and per Step 1 it should - don't collapse grading to a single pass-rate. The natural metric family for a classification task is the confusion matrix: report precision and recall on the positives, specificity on the negatives, and the false-positive rate as separate metrics alongside overall accuracy. A variant that "wins" on accuracy may have quietly traded recall for precision or shifted the false-positive rate, and a single number hides that. Putting each cell in its own column makes the tradeoff visible in the report so the user can decide which side of it they care about.
|
||||||
|
|
||||||
|
Then, for each input, the eval needs to turn the app's output into a score or a pass/fail. Propose the grading method that *matches the output's shape* - pick the cheapest one that genuinely measures what the user cares about, but don't let cost push you toward a programmatic check for a property that actually needs judgment. The list below is roughly cheapest-first; the right choice depends on whether the output space is constrained or open-ended:
|
||||||
|
|
||||||
|
1. **Programmatic check.** Exact match, contains-substring, JSON validates against schema, classification label from a fixed set, code compiles, test passes. Deterministic and free. Use this when the output space is constrained - a number, a label from a closed set, structured data, a pass/fail - so the check is measuring the answer, not the phrasing. **When the app is an agent that acts on an environment** (writes code, edits files, calls APIs with side effects), this is the primary grader and it should read the *end state*, not the transcript: run each case in a disposable workspace, then check what was left behind - tests pass, the diff applies, expected files or values exist, nothing off-limits was touched, steps within budget - and reserve a judge for the taste dimensions a check can't see (readability, minimality, the PR description). If the output is free-form prose with many valid phrasings, a programmatic check will be brittle; use a judge instead. For a **coding or tool-using agent**, the programmatic check is on the *end state*, not the transcript: run each case in a throwaway checkout/container and score what's left behind - the hidden tests pass, the diff applies cleanly and touches only the intended files, the linter/typechecker is clean, the expected file/row/API side-effect exists - plus a no-op detector (agent claimed success, workspace unchanged). Transcript-graded "did it say the right things" is the weakest signal for agents; use it only for process guardrails (asked before deleting, didn't leak the secret).
|
||||||
|
2. **Pairwise blind comparison.** A judge reads the input and two candidate outputs - typically the current system's and a baseline's - and picks the better one, optionally against a short rubric. When the quality criteria are fuzzy, pairwise tends to be more accurate than scoring each side on its own and subtracting: judges are better at "which of these two is better" than at placing a single output on an absolute scale. It's the natural fit when the question is inherently comparative (a migration, v1 vs v2). Three defaults: randomize which candidate is A and which is B on every case; let the judge answer `tie` or `both_bad` rather than forcing a winner; and have the judge's system prompt treat both candidates as untrusted data, not instructions. **If you'll hillclimb on this eval, fix the reference now:** save the baseline's outputs to disk once (e.g., `baseline/ref/<id>.html`) and judge every later variant's fresh output against those frozen artifacts - never regenerate the reference, or "win rate" silently changes meaning between rounds. On the **baseline rows themselves**, write the comparative metric as its neutral value (e.g., `win = 0.5`) - a primary metric that's missing on the reference variant breaks the report. When a variant later saturates near 100% against that reference and the metric stops discriminating, freeze that variant's outputs as a *second* reference and carry both win-rate columns forward - don't replace the original. And note that a per-case pairwise judge structurally cannot see a cross-case mode collapse (every output converging to one style can each score "better than baseline"); if that's a risk for this app, pair the judge with a programmatic or set-level diversity metric.
|
||||||
|
3. **Model-graded pointwise rubric.** A second Claude call that reads the input, a single output, and a rubric, and returns a score with reasoning. Reach for this when there's no baseline to compare against, or when the user wants an absolute per-case number rather than a win rate - open-ended outputs (summaries, explanations, drafted emails) where there's no single correct answer but there are clear quality criteria. Let the user pick the judge model - `claude-haiku-4-5` is cheap and fast enough to run on every PR, `claude-sonnet-5` is a balanced middle, `claude-opus-5` is worth the cost when the quality criteria are nuanced enough that a weaker judge would miss the point (the same choice applies to a pairwise judge). Ask which they prefer; don't assume. Whichever they pick, avoid using the exact model-under-test as its own judge. For the judge call itself, prefer **structured outputs** (`output_config.format` with a JSON schema) over "respond with only JSON" prose - free-text JSON fails on unescaped quotes in reasoning often enough to matter; a schema makes the parse deterministic. Write the rubric - whether it's used pointwise or handed to a pairwise judge - as concrete, checkable claims ("the response cites at least one source from the context"; "the response does not fabricate API parameters") rather than vague scales ("rate helpfulness 1-5").
|
||||||
|
4. **Human spot-check.** For outputs where even a rubric is hard to write ("does this legal brief demonstrate sound reasoning?"), the honest answer may be that a handful of human-graded examples is worth more than a hundred model-graded ones. Propose a small curated subset for the user to grade by hand, and be explicit that this limits how often the eval can run.
|
||||||
|
|
||||||
|
Most cases carry an `expected` field alongside the input, but what it holds depends on the grading method - it isn't always a ground-truth answer. For a programmatic check it's the literal target; for pairwise it's the baseline response to compare against; for a pointwise rubric it might be the per-case rubric text the judge reads. Let the shape follow from the grader, not the other way around.
|
||||||
|
|
||||||
|
When you propose the rubric or criteria, show your work: list the criteria you're including *and* the ones you considered and left out, with a line on why, so the user can pull something back in rather than wonder whether you thought of it. When the set has both positives and negatives, propose the confusion-matrix metrics - precision, recall, specificity - rather than accuracy alone. Generalize each criterion to the principle behind it - if the user says "it shouldn't cite Wikipedia," write "cites credible sources" rather than hard-coding one domain - and check that two criteria aren't scoring the same underlying thing twice. Where the user is really expressing a tradeoff ("shorter is better, but not at the cost of completeness"), prefer a continuous measure the eval can report over a hard pass/fail cutoff; a threshold can always be applied later, but a binary grade throws away the shape of the tradeoff. And if any criterion asserts a checkable fact ("the API returns field X"), offer to verify it against docs or code before baking it in - rubrics are as prone to hallucination as any other generated text.
|
||||||
|
|
||||||
|
Whatever grades quality, record the side-channel metrics the user picked from the menu above on every case. **Report them as absolute numbers first** ("19.8 s/turn, $0.031/call, 480 output tokens") and only then as relative changes ("33% faster than baseline"); the absolute value is what the user will feel in production, and a percentage without it hides whether you're talking about 2 s or 20 s. Keep them as separate columns alongside the quality score rather than folding them into it.
|
||||||
|
|
||||||
|
Run the grader on a handful of cases and show the grades alongside the outputs. A rubric that looks sensible in the abstract can turn out to reward the wrong thing; the only way to catch that is to look at what it actually does.
|
||||||
|
|
||||||
|
### Get the grading method approved
|
||||||
|
|
||||||
|
Write the pilot cases into `.claude/hillclimb/<flow>/baseline/` in the same shape Step 3 describes (`results.jsonl` rows + `traces/<id>_rep0.json`), run the report builder (§Report builder in Step 3) on the flow directory, and give the user the resulting `report.html` - that's how they review the pilot, not a chat summary. With the full viewer, point them at the Transcripts tab and ask them to click into each case: they should see the full exchange (system prompt, every tool call and result, the model's response) alongside the grade and the judge's reasoning. With the lite report, each per-case row links to its trace file - ask them to open two or three and read the exchange there. **If the cases carry artifacts** - input PDFs/images, generated HTML/SVG/plots, files the model wrote - make sure the user can see those too: with the full viewer, fill the `attachments` slots per §Make artifacts visible below so they render in the Transcripts tab; with the lite report, name the artifact paths in the handover message. Do this before asking for sign-off. The user can't sign off on grading whose raw material they haven't read. Ask directly:
|
||||||
|
|
||||||
|
> Here are five graded examples in `report.html` - open each one. **Would you have scored any of these differently?** Is there something you care about that this isn't measuring - or something it's penalizing that you don't actually mind?
|
||||||
|
|
||||||
|
If the answer to "would you have scored differently" is yes for even one case, the rubric isn't ready - iterate on it and show a fresh batch until the user's judgment and the grader's line up, then get an explicit yes on the final version.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 3: Make it runnable
|
||||||
|
|
||||||
|
Write a script (or test file, or whatever fits their repo) that: loads the inputs, runs the app against each one, grades each output, writes per-case results to disk, and prints a summary line with the headline score and a confidence interval so the user can tell signal from noise. Run the cases concurrently - bound in-flight requests with something like an `asyncio.Semaphore` set near the account's rate limit - so a full pass finishes in minutes rather than hours; fast eval turnaround is what makes iterating on the result practical. Keep it simple and keep it in their codebase's idiom - if they have a `scripts/` directory full of Click CLIs, make it one of those; if everything is pytest, make it a pytest.
|
||||||
|
|
||||||
|
Have the runner write its output into `.claude/hillclimb/<flow>/baseline/` (the hillclimb loop, if they run it later, will add `v1/`, `v2/`, ... siblings under the same parent). If the user already has a results layout they like, keep it - what matters is that each case carries the full transcript, `usage`, cost, and grade from the same model call - but this layout is the default when starting fresh. **Write each row as the case completes**, not in one batch at the end - a crash mid-run shouldn't cost the cases that already finished - and make resume idempotent at the **(case, rep)** key, so restarting after a crash skips exactly what's already written and never produces a duplicate-rep row whose score and transcript came from different calls. Four more properties a trustworthy runner needs - cheap to add up front, expensive to discover missing mid-run:
|
||||||
|
|
||||||
|
- **A hard per-case wall-clock ceiling, independent of stream liveness.** A hung streaming connection can emit keepalives indefinitely, defeating any inactivity-based timer; only a ceiling on total case time reliably reclaims the slot. Fail the case when it fires and record it as a timeout, not a zero - and note the timed-out call itself may keep running in the background: the ceiling reclaims the slot and stops further retries, it can't abort the underlying request.
|
||||||
|
- **Jittered backoff on 429/overloaded, with retries visible.** A zero-delay retry loop multiplies cost invisibly under rate limits and can turn one transient 429 into a torn-down batch. Back off with jitter, cap attempts, and record the retry count with the attempt - attempts run vs. attempts scored should be visible in the data, not just the bill.
|
||||||
|
- **Explicit case-retry semantics.** If the runner can re-run a failed case, decide which attempt's grade, transcript, and usage land in the results. Default to scoring strict per attempt - a case that passed only on retry is a fail unless the user decides otherwise - and count every attempt in cost.
|
||||||
|
- **A failure class on every failed attempt** - refusal / harness-or-serving error / timeout / genuine failure - recorded with the attempt (in `grade` or the row's `meta` for graded outcomes like refusals; an errors sidecar is fine for harness failures, which must not occupy the `(case, rep)` slot in `results.jsonl` or resume will never re-run them). The sidecar is append-only across resumes - a `(case, rep)` appears once per failed attempt, and a later success in `results.jsonl` supersedes its error rows. Carry the attempt's `model` and `usage` on the error row when the call completed, and count that usage in any spend accounting - billed-but-failed spend is still spend. Zeros with different causes need different handling and are indistinguishable in the score column.
|
||||||
|
|
||||||
|
Two files per run, plus an **`errors.jsonl`** sidecar for attempts that failed before producing a scorable output (API error after retries, tool exception, wall-clock ceiling, grader crash, served-model mismatch) - one line per failed attempt with its failure class, retry count, and `model`/`usage` if the call completed. Those never go in `results.jsonl`: a row at the `(case, rep)` key would make resume skip it forever and would score plumbing as a model failure. The report shows the error count per variant next to the case count.
|
||||||
|
|
||||||
|
- **`results.jsonl`** - one JSON object per case, with `prompt_id`, `prompt` (the full text), an ordered `tags` list, `stop_reason` and a `status` (`ok`, or `truncated` when the response hit `max_tokens` - the report counts truncated rows and leaves them out of the means rather than scoring a clipped answer as wrong), `grade`, and the side-channel metrics the user picked in Step 2. `tags[0]` is the primary grouping key (topic, task type, difficulty bucket - whichever cut the user cares about most) and becomes the section header in the eval table; **further `tags` entries render as chips next to the prompt** in both the eval and transcript views, so put there any short label the user needs at a glance to make sense of a case's score - difficulty, source, user segment, language. Decide deliberately what's chip-worthy: if it matters for reading the result, it's a tag; if it's just sidecar data (provenance IDs, raw annotator notes), put it in `meta` instead, which is carried through but never rendered. `grade` is a bool, a number, or a `{metric_id: number}` dict, with an optional `explanation: {metric_id: str}` sibling for judge rubrics. When you're tracking more than one quality metric - the precision/recall/specificity family from Step 2, for instance - `grade` must be the dict form keyed by metric id, e.g. `{"precision": 1.0, "recall": 1.0, "specificity": 0.0}`. The adapter reads per-case scores from `grade` and nowhere else, so a bare bool or number alongside multiple declared metrics renders as dashes in every metric column. Declare the metric ids (and their labels) in `.claude/hillclimb/<flow>/_state.json` under `metrics` - see `eval-hillclimb.md` for the full `_state.json` shape - so the report knows what columns to draw, then have the runner populate every id on every case's `grade`. **Order matters:** the report's headline metric (the one the Summary tab, the lite report, the trajectory file, and `--verify` track) is the first `kind: "binary"` entry, else the first entry - so list the metric you actually care about first, not a constant format-check. Keep each metric's `label` to <=14 characters - the full viewer's legend has limited width and truncates with an ellipsis; put qualifiers, units, and definitions in `metrics.md` instead of packing them into the label. The side-channel perf keys are read by exact name - `latency_s`, `tool_calls`, `web_searches`, `usage: {input_tokens, output_tokens, cache_read_input_tokens, cache_creation_input_tokens}` - and those are the default perf columns the full viewer renders; if the runner didn't track some of them, or this flow's meaningful per-case fields are different, declare your own via a `perf_fields` list in the same `_state.json` so the table shows what you measured instead of zeros. Also record `model` on each row, taken from the response rather than your config - `cost_usd` is **derived** from each row's `model` × `usage` plus, when present, `judge_model` × `judge_usage` (so model-graded evals show the judge spend too; otherwise up to half the real cost is invisible): by the full viewer when it is on disk, otherwise by you when you report, with the recipe under "If the user asks what this will cost" in § Before the first paid call below (Current Models prices in `SKILL.md`; cache writes at 1.25× input, cache reads at 0.1× input). Either way the runner doesn't compute cost; a model swap can't carry a stale rate; a swap that didn't take is visible. Go one step further and **assert** it: fail the attempt loudly when a response's `model` differs from the requested one beyond documented alias->snapshot resolution - a silently substituted model (a provider fallback, a capacity reroute) invalidates the comparison. Silent fallback may not appear in response fields at all, so where the provider exposes usage or billing records, cross-check the aggregate against them. For models not in the full viewer's built-in price table, add a `prices: {model_id: {in, out}}` map to `_state.json`.
|
||||||
|
- **`traces/<id>_rep<k>.json`** - the full conversation for that case, as a JSON list of `{role, content, thinking?, name?, attachments?}` turns where `role` is one of `system | user | assistant | tool_call | tool_result`. Each tool call is its own `{role: "tool_call", name, content}` entry (content = args, pretty-printed), each tool result a `{role: "tool_result", content}`, and assistant extended-thinking goes in the optional `thinking` field on the assistant or tool_call turn it preceded. Example:
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{"role": "system", "content": "You are a helpful trading assistant."},
|
||||||
|
{"role": "user", "content": "What's AAPL trading at?"},
|
||||||
|
{"role": "tool_call", "name": "get_quote",
|
||||||
|
"content": "{\n \"symbol\": \"AAPL\"\n}",
|
||||||
|
"thinking": "Need the current price."},
|
||||||
|
{"role": "tool_result", "content": "{\"price\": 187.42}"},
|
||||||
|
{"role": "assistant", "content": "AAPL is trading at $187.42."}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
If the flow involves images, screenshots, or generated files, save them as sidecar files and reference them via the structured `attachments` slot (on the row for inputs, on the trace turn for outputs) so the report can show them inline - see the **Make artifacts visible** note below.
|
||||||
|
|
||||||
|
Those two are the runner's job. The full per-variant contract the report builder reads - including files that only matter once a second variant exists - is:
|
||||||
|
|
||||||
|
| file | scope | purpose | if missing |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `results.jsonl` | every variant | per-case scores, perf, tags | no data |
|
||||||
|
| `traces/<id>_rep<k>.json` | every variant | per-case transcript | no click-through; can't audit behaviour |
|
||||||
|
| `change.md` | non-baseline | what changed and why; first non-heading line becomes the variant's one-line description | Harness Changes panel has no rationale - the user sees a metric moved but not what caused it |
|
||||||
|
| `change.patch` | non-baseline | unified diff of the harness files you edited, cut against the user's real source paths | no diff view in Harness Changes |
|
||||||
|
| `<name>.before.<ext>` + `<name>.<ext>` | non-baseline | before/after snapshot pair per edited file, dropped in the variant dir | no cumulative vs-baseline diff |
|
||||||
|
| `summary.json` | optional | `{"description", "label", "target": "system_prompt"\|"skill"\|"tools"\|"code", "suspicious"}` | falls back to first line of `change.md` |
|
||||||
|
|
||||||
|
Variant directories must be named exactly `baseline` or `v<N>` (`v1`, `v2`, ...) - the report builder silently ignores `v1-better-prompt`, `variant_a`, or anything else that doesn't match, so put the descriptive name in `change.md`'s first line instead. For the baseline-only eval you're building here, `results.jsonl` + `traces/` is the whole job; the non-baseline rows matter the moment you - or `/claude-api hillclimb` - add a `v1/`, and missing them doesn't error, it produces a report whose Harness Changes panel is quietly empty.
|
||||||
|
|
||||||
|
If there's no existing runner to adapt, **start from `shared/evals/report/runner-scaffold.mjs`** - copy it into the user's repo and fill in `loadCases` / `runCase` / `gradeCase`. The scaffold's CLI surface (`--variant` / `--model` / `--reps` / `--timeout-s`), rep-aware filenames + resume, frozen-pairwise-reference handling, read-only `_state.json`, jittered backoff, per-case wall-clock ceiling, served-model assertion, harness-integrity gate, and failure sidecar are already hillclimb-shaped, so adding `v2` later is one flag, not a refactor. The gate means the first run exits 2 until the user runs it once with `--approve-harness` (it records a sha of the runner plus `_state.json.harness_paths`); that flag is the user's to pass, not yours. If there *is* an existing runner, keep it - but check it has those same properties before the loop starts. Run the scaffold with `node` or `bun`, whichever is on PATH. If neither is installed (common in Python-only projects), don't ask the user to install one: write the runner in the project's language against the contract above (`results.jsonl` rows, `traces/<id>_rep<k>.json`, `errors.jsonl`, `baseline` / `v<N>` directories) and the field reference in `shared/evals/report/SCHEMA.md`, keeping the scaffold's properties - `--variant` / `--model` / `--reps` flags, rep-aware filenames with resume, backoff, a per-case wall-clock ceiling, a failure sidecar, and the harness-integrity gate (a sha over the runner file plus `_state.json.harness_paths`, refusing to run on mismatch until the user re-approves - that approval is theirs to give, never yours, exactly as with the scaffold's `--approve-harness`).
|
||||||
|
|
||||||
|
**Report builder.** Do **not** hand-roll an HTML index. Two builders in `shared/evals/report/` read the same flow directory and write the same `trajectory/scores.tsv`; the report is the deliverable, and which builder you run depends on what is on disk:
|
||||||
|
|
||||||
|
- `build-report.mjs` - the full viewer: sortable per-case table with every metric's score and side-channel columns, click-through transcripts with rendered tool calls and attachments, per-round diffs and trend charts. It is present only when the skill was installed from the EAP package; `/claude-api` in the CLI does not extract it (or its `lib/`).
|
||||||
|
- `build-report-lite.mjs` - always extracted with this skill: a single static `report.html` with the per-variant summary, a sortable per-case table (primary metric per variant, split, tags, prompt), and a link to each trace file. No transcripts inlined, no charts.
|
||||||
|
|
||||||
|
Pick the full builder if `shared/evals/report/build-report.mjs` exists next to the lite one, else the lite one; run it with `node` or `bun`, whichever is on PATH. The script paths are relative to this skill's base directory while `.claude/hillclimb/<flow>/` is relative to the user's project, so spell out the base directory rather than `cd`-ing into it:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
R="<base directory>/shared/evals/report" # the "Base directory for this skill" shown when the skill loaded
|
||||||
|
B="$R/build-report.mjs"; [ -f "$B" ] || B="$R/build-report-lite.mjs"
|
||||||
|
node "$B" .claude/hillclimb/<flow>/
|
||||||
|
```
|
||||||
|
|
||||||
|
Show the user `report.html`, never the raw JSON. If neither `node` nor `bun` is installed, the deliverable is a markdown table (case, split, per-variant mean of the primary metric over status-ok reps - the same numbers `trajectory/scores.tsv` would hold) computed from `results.jsonl`, plus the trace file paths; still no hand-rolled HTML. If your results land in a different shape, `shared/evals/report/SCHEMA.md` is the field reference; writing a custom adapter is a full-viewer feature.
|
||||||
|
|
||||||
|
**Make artifacts visible.** If the cases consume or produce artifacts - input PDFs/images, computer-use screenshots, generated HTML/SVG/plots, files the model wrote - the full viewer has prebuilt rendering for them; the runner just fills the slot (the lite report renders none of this - it links the trace file and the user opens the `ref`'d paths directly - so keep every `ref` relative to the flow root either way). **One slot per artifact**: put the output in `Turn.attachments` once and let the viewer render it - don't also screenshot it into a separate file or rely on a fenced block in the response text; the viewer suppresses its inline-render toggle on any turn that already has attachments, so the structured slot is the single source. **Input artifacts** go on the `results.jsonl` row as `"attachments": [{"kind":"pdf","ref":"baseline/inputs/case_3.pdf","alt":"source doc"}]` and render above the first user turn. **Output artifacts** go on the trace turn that produced them: `{"role":"assistant","content":"...","attachments":[{"kind":"html","ref":"baseline/out/case_3.html"}]}` - write the file under the variant dir and `ref` it relative to the flow root. Fenced ` ```html `, ` ```svg `, ` ```json ` blocks inside an assistant turn's `content` get a "> Render" toggle automatically. The full viewer handles `image`/`svg` inline, `html` in a sandboxed scrollable iframe, `pdf` via the browser's native viewer, `json`/`text` in a `<pre>`, anything else (`file`: docx, pptx, ...) as a download chip - each with a Hide/Show toggle. Paths under ~2 MB are inlined into `report.html`; larger ones stay as download links.
|
||||||
|
|
||||||
|
How the runner invokes the app matters more than it sounds. Do not reconstruct the Claude API call yourself from the system prompt and model string you found - the eval needs to exercise the user's retry logic, tool wiring, context assembly, and whatever else sits between "input arrives" and "Claude is called." Pick whichever of these is closest to production while still safe to run N times in a row:
|
||||||
|
|
||||||
|
- call the **real entry point** from Step 0 directly;
|
||||||
|
- hit the **real prod API or endpoint** with test or mock user IDs - real code path, but attributed to a test account so it's isolated and easy to clean up;
|
||||||
|
- call a **thin test-mode wrapper** around the entry point that mocks only the prod-touching dependencies (DB writes, outbound emails, external side effects) and leaves everything else real - this is the stubbing fallback flagged in Step 0.
|
||||||
|
|
||||||
|
Then **run it once** - on the full set if it's cheap, or on a handful of inputs if it isn't. Before computing anything, **read the row the runner wrote, not just the number it printed**: every field reporting needs - `model`, `usage`, the trace file, plus whichever guardrail fields the user picked - should be present and non-trivial on the pilot row. Whatever's missing or zero now will be missing or zero on all N cases, and after the full run it usually can't be reconstructed. Fix the runner until one row is complete.
|
||||||
|
|
||||||
|
### Before the first paid call
|
||||||
|
|
||||||
|
Run `eval-audit.md` against what you just built - it takes minutes and catches most wiring bugs before they cost a full pass. At minimum: push an **oracle** (the reference answers, or an input that must pass) and a **null** (empty output, a constant answer) through the whole runner-plus-grader and confirm ~100% and ~0%; feed the judge, if there is one, an empty string, "I don't know," and a confident answer to the wrong question and confirm it fails all three; confirm an induced API error lands as `status: error`, not `grade: 0`; and put the pilot's noise floor next to the change the user hopes to see (§5). Report anything else the checklist turns up per its §6 - briefly, severity first, with an offer to fix.
|
||||||
|
|
||||||
|
Then tell the user what you're about to run - *"N cases × R reps on `<model>`, ~Z minutes"* (where Z is the pilot's wall-clock × N/M, not an intuition) - and proceed on a yes. That's the consent gate.
|
||||||
|
|
||||||
|
**If the user asks what this will cost or gives you a budget**, replace that one-liner with a real estimate derived **from the pilot's actual `usage`, and only from that** - historical-log surveys and dataset medians are routinely 2-4× off because they don't reflect the mode flags, cache state, agentic turn count, or retries the eval actually runs. Compute, from the pilot rows:
|
||||||
|
|
||||||
|
- **Tokens per case** (input + output, plus judge input + output if model-graded), measured. Report the spread, not just the mean - `min / median / max` per case.
|
||||||
|
- **Dollars per full run**: tokens × the per-token prices for the user's provider - the **Current Models table in `SKILL.md`** is first-party pricing; if the app is on Bedrock, Vertex, or another provider, ask the user for their rate card. Price every `usage` field: base input and output at the table rate, cache writes at **1.25× input**, cache reads at **0.1× input**.
|
||||||
|
- **Wall-clock per full run**: time the pilot run end-to-end and scale - `(pilot wall-clock) × (N cases / M pilot cases)`. Never estimate from intuition.
|
||||||
|
|
||||||
|
Then **show the math** - the formula is what makes the assumption inspectable:
|
||||||
|
|
||||||
|
> Pilot: M cases, median ~Xin / ~Xout tokens (range Xlo-Xhi). At <model> prices ($A/MTok in, $B/MTok out, cache-read 0.1×): ~ $C/case (range $Clo-$Chi). Full run = N cases × R reps × $C ~ **$Y** (range $Ylo-$Yhi), ~Z minutes.
|
||||||
|
|
||||||
|
Ask whether that's acceptable. If it isn't, offer the levers: switch the judge to a cheaper model, cache more aggressively, or **trim to the discriminating cases** - from the pilot, rank cases by signal (cross-rep score variance, distance from median, judge disagreement) and keep the top K; cases that always pass or always fail tell you nothing round-to-round. If you trim, the loop runs on those K every round and you run the **full** set once on baseline and once on the winner at the end to confirm - those are two different populations, so don't mix them in the same comparison. **The case count and rep count in the formula you got approved are what you run** - re-present if either changes. After the full run completes, replace the projected cost with the measured one wherever you wrote it down.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 4: Hand it over
|
||||||
|
|
||||||
|
Once the sign-offs are cleared, the user has: an input set they've reviewed, a grading method they've validated, a runnable script, and a baseline number. **Proactively - don't wait to be asked** - do a full baseline run against the model the user cares about (if the Step 3 pilot already covered the whole set, reuse that; otherwise run the full set now), then build and open the report:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
R="<base directory>/shared/evals/report" # the "Base directory for this skill" shown when the skill loaded
|
||||||
|
B="$R/build-report.mjs"; [ -f "$B" ] || B="$R/build-report-lite.mjs"
|
||||||
|
node "$B" .claude/hillclimb/<flow>/
|
||||||
|
```
|
||||||
|
|
||||||
|
**Verify the report before handing it over.** Open `report.html` yourself first. With the lite report the checks are the header's variant and case counts and that every per-variant column shows numbers rather than blanks (a blank column means `grade` isn't the `{metric_id: number}` dict form, or every rep had a non-ok `status`); the rest of this paragraph is the full viewer. The header should show the variant count you expect - if you ran baseline plus one variant and it says "1 variant", a directory was named something other than `baseline` / `v<N>` and got silently skipped (rename it and rebuild). On the Summary chart, the y-axis ticks should be short readable numbers - a tick like `6.838607594936709` means a formatter is missing - and any lower-is-better metric (latency, cost, error rate) should read as such; if the chart or colour scale implies higher-is-better for a metric where lower is, the viewer's first impression will be backwards. If there's more than one variant, click each non-baseline row in the Summary table to open its diff drawer: every one should show a diff and a rationale; an empty drawer means that variant's `change.md` / `change.patch` are missing. In the Transcripts tab, click into at least two examples: you should see the system prompt as a collapsible card, distinct user and assistant turn bubbles, and any tool calls and results rendered as their own cards - not as raw JSON inside a text bubble; one giant blob, missing turns, or `{"type": "tool_use", ...}` rendered literally means the runner's trace writer is emitting the wrong format (fix it per §Step 3 and rebuild; `build-report.mjs <flow> --check` runs the trace lint without rendering). In the Eval table, click into a passing case and a failing case: every declared metric column should show a number, not a dash - dashes mean `grade` isn't the `{metric_id: number}` dict form. Every perf column should carry a non-trivial value - a column full of `$0.000` or `0` means the runner didn't emit that field. The metric panel above the table should read cleanly without explanation - a cryptic metric id needs a `label`. Fix any of these in `_state.json` / the runner's `grade` output per §Step 3 and rebuild.
|
||||||
|
|
||||||
|
Once it looks right, hand over `.claude/hillclimb/<flow>/report.html` as **the** deliverable. The handover message is: the file path (or open the file for them), plus a one-line headline ("baseline scores X on N cases - every row links to its transcript"). Prefer that over enumerating cases or scores in the chat - the viewer is where per-case detail lives, and a wall of plaintext makes the user less likely to open it; call out one or two specific cases only when there's something you want them to look at first. The Step 4 verification you just did is for *you* to catch render bugs, not to narrate to the user. With only a single baseline variant on disk the report renders as a pure eval viewer - per-case table plus click-through transcripts (trace-file links, with the lite report). Point at `report.html`, not at `results.jsonl`; the raw JSON is an implementation detail.
|
||||||
|
|
||||||
|
Summarize where each artifact lives and what the baseline score was. If the reason they wanted an eval was to hill-climb on it, point them at `/claude-api hillclimb`.
|
||||||
|
|
||||||
|
### Make it durable
|
||||||
|
|
||||||
|
The eval is only useful if the user can rerun it - on the next model, on next quarter's traffic, after the next prompt rewrite. Count files and bytes under `.claude/hillclimb/<flow>/` (with and without `traces/`) plus the runner and input files wherever they live, then ask via `AskUserQuestion`:
|
||||||
|
|
||||||
|
- **Commit the eval (Recommended)** - runner, inputs, grader, and `.claude/hillclimb/<flow>/` minus `traces/`. Quote the actual count: "N files, ~X MB". Add `**/traces/`, `report.html`, `state.json`, and `trajectory/` to `.gitignore` so derived and bulk output stays out.
|
||||||
|
- **Commit the eval and transcripts** - same plus `traces/`. Quote "M files, ~Y MB". Only worth it if the transcripts themselves are evidence the user wants in the repo.
|
||||||
|
- **Don't commit** - this was a one-off; they don't plan to rerun it.
|
||||||
|
|
||||||
|
Whichever they pick, do it - stage, write the `.gitignore` lines, commit with a message that names the flow and the baseline score. The lite report builder ships with this skill, not the user's repo - a teammate regenerates `report.html` by running any `/claude-api` command (which extracts `shared/evals/report/build-report-lite.mjs` with the guides) and then the builder command above; the full viewer regenerates the same way on an EAP install. If the user wants the eval fully self-contained, copy `shared/evals/report/build-report-lite.mjs` (15 KB, no dependencies) into the committed eval directory; offer the full viewer's `{build-report.mjs,lib/}` (~1 MB) only when it is on disk.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Failure modes to avoid
|
||||||
|
|
||||||
|
These are the ways eval-building tends to go wrong. You have latitude in how you run the process above; you do not have latitude to fall into these.
|
||||||
|
|
||||||
|
- **Skipping the sign-offs.** Generating forty plausible-looking inputs and a sensible-looking rubric without showing the user produces an eval that nobody trusts. The sign-offs are the product.
|
||||||
|
- **Running before the user says go.** Kicking off even a small pilot while a design question is still open, or quietly moving from "let's refine the rubric" to "I ran it," costs trust faster than it costs tokens. Get an explicit OK before the first paid call.
|
||||||
|
- **Mandating a format.** Do not tell the user they need to adopt an eval framework, restructure their repo, or express inputs in a particular schema. Fit the eval to their codebase, not the other way around.
|
||||||
|
- **Reimplementing the app.** The runner must call the user's actual entry point. Rebuilding the Claude call from scratch in the eval script silently diverges from what production does and measures the wrong thing.
|
||||||
|
- **Guessing at cost** - when the user asks what it'll cost, ground the estimate in at least one measured run; token guesses are routinely off by 3-10×. Run it, read `usage`, then multiply - from the **pilot**, not from a survey of historical logs.
|
||||||
|
- **Trusting a zero.** Before you present any number - in chat, in `metrics.md`, in `report.html` - sanity-check it. Every metric on every row should be **present and plausible**: a `cost_usd` of `$0.00`, a `latency_s` of `0.0`, an empty `usage`, or a metric that's a flat constant across all cases is almost never a real measurement - it's a field-name mismatch, a silent lookup failure, or a default that papered over an exception. Treat a zero in a column that should never be zero as a runner bug, not a result. Make the runner fail loud (raise, don't write the row) when a required field is missing on a successful case; make yourself fail loud (stop, don't present) when you spot one in output you're about to show.
|
||||||
|
- **Ignoring data handling.** If inputs come from production traffic, the retention and PII questions are not optional. Ask them before pulling data, not after the file is committed.
|
||||||
|
- **Over-trusting a model judge.** LLM graders are convenient and usually reasonable, but they can be gamed and they can fixate on surface features. Always show the user graded examples before locking in a rubric, and prefer a programmatic check wherever one exists.
|
||||||
|
- **Building the grand unified eval.** One flow, one eval. If the user has six flows, that's six evals - build the one they asked about and stop.
|
||||||
441
skills/claude-api/shared/evals/cost-hillclimb.md
Normal file
441
skills/claude-api/shared/evals/cost-hillclimb.md
Normal file
@@ -0,0 +1,441 @@
|
|||||||
|
# Cost-reduction search: how to structure it
|
||||||
|
|
||||||
|
Guidance for running an eval-driven search whose central goal is **reducing cost** (at
|
||||||
|
equal-or-better quality) for a Claude-powered app - typically during a migration from an
|
||||||
|
older model and prompt to a current one. This is the procedure the hillclimb loop
|
||||||
|
(`eval-hillclimb.md`) follows when the user's Step 1 goal is cost; it assumes there is an
|
||||||
|
eval to measure quality against. Without one, use `shared/cost-optimization.md` instead -
|
||||||
|
the no-eval checklist (caching -> input trim -> agent-loop hygiene -> output -> batch -> effort ->
|
||||||
|
model last). The lever order differs on purpose: with an eval you can *detect* that a
|
||||||
|
stronger model at lower effort is the cheaper cell, so the model × effort walk comes early
|
||||||
|
here; without one, a model swap is the riskiest change and belongs last. Where this file states a number, it
|
||||||
|
reflects measured behavior on representative benchmark evals except where a
|
||||||
|
practitioner report is noted as such, stated so you can anticipate the shape of
|
||||||
|
results; always re-measure on the user's own eval.
|
||||||
|
|
||||||
|
## The search order
|
||||||
|
|
||||||
|
Work the levers in this order. Each position exists because running it later corrupts
|
||||||
|
or wastes the steps in between.
|
||||||
|
|
||||||
|
**Step 0 - Caching health: check first, re-verify after every lever change.**
|
||||||
|
Caching is configuration, not a search lever - its health gates the accuracy of every
|
||||||
|
cost measurement below, and its dominant failure mode is silent invalidation. Quick
|
||||||
|
health check: cache breakpoints are set; the cached prefix contains no dynamic content;
|
||||||
|
`cache_read_input_tokens` is nonzero in responses. Do not restate or re-derive caching
|
||||||
|
design here - follow the skill's prompt-caching guidance (shared/prompt-caching.md
|
||||||
|
in the shipped package; its load-bearing practices: re-verify cache health after
|
||||||
|
every change, not just at setup; know what a healthy cache loop looks like in the
|
||||||
|
usage fields; and when reads drop, hunt down the specific invalidator) - but
|
||||||
|
re-run this health check after EVERY model or effort decision below. Two scoping facts matter for every
|
||||||
|
step below: the cache is per-model, and effort participates in the prompt-cache key on
|
||||||
|
the Messages API - a mid-conversation effort switch costs one full prefix rewrite
|
||||||
|
(probe-measured on a current top-tier model against the raw API: 3/3 effort switches
|
||||||
|
re-billed the full prefix; 0/9 same-effort continuations did). Reports from first-party
|
||||||
|
product surfaces that effort can be switched without losing the cache do not transfer
|
||||||
|
to API customers - the serving path differs; trust an API-side probe. The upshot: a
|
||||||
|
lever change silently converts a healthy cache into a cost regression that looks like
|
||||||
|
model behavior, so re-verify cache health after every step of the model×effort walk
|
||||||
|
(Step 2), not only at setup.
|
||||||
|
|
||||||
|
**Step 1 - Audit the existing prompt and request config.**
|
||||||
|
Dated prompt content and legacy request parameters corrupt every later comparison: in
|
||||||
|
the harder arm of a measured migration (a heavily dated, extended prompt), the model
|
||||||
|
upgrade alone moved accuracy barely at all while auditing the same prompt recovered
|
||||||
|
more than ten times the gap; the milder arm of the same migration (lightly planted
|
||||||
|
cruft) measured a ~2× gap, so the multiple scales with how dated the prompt is. A
|
||||||
|
planted legacy thinking configuration (a dated budget-tokens shape) turned out to be
|
||||||
|
rejected outright - field-level, on every current model, probe-verified - and had to
|
||||||
|
be re-authored before any comparison could run at all; the period-correct form that
|
||||||
|
does run everywhere inflates cost instead of crashing, which is worse, because nothing
|
||||||
|
forces you to notice it. Newer models follow
|
||||||
|
legacy scaffolding MORE literally, so a model swap judged under a dated prompt can
|
||||||
|
mis-rank models - and can even *add* cost. The audit is cheap, runs once, and de-noises
|
||||||
|
everything after it. Run `prompt-audit` (the procedure ships as
|
||||||
|
shared/prompt-audit.md), and check request parameters against the current API
|
||||||
|
surface (see the model-migration guide), before any measurement you intend to keep.
|
||||||
|
|
||||||
|
**Step 2 - Model × effort: walk the staircase, don't sweep the grid.**
|
||||||
|
The cheapest configuration is frequently a *stronger* model at *lower* effort: the
|
||||||
|
stronger model tends to spend fewer tokens on the same task (a measured direction,
|
||||||
|
not a fixed magnitude), so it can win on cost as well as score. That
|
||||||
|
configuration is invisible to any procedure that fixes the model at default effort and
|
||||||
|
then tunes effort - and a full factorial grid finds it only by paying for every cell,
|
||||||
|
most of them in the expensive corner. Treat model × effort as one surface and search
|
||||||
|
it with a *staircase walk*: lay the cells out with model tier on one axis and effort
|
||||||
|
on the other. Cost rises with effort within each row - across tiers the measured
|
||||||
|
cost bands can overlap (see the bottom-up exception below) - and quality rises
|
||||||
|
(weakly) along both axes, so the cells that clear a pre-registered quality floor
|
||||||
|
form an upper-right region, the cheapest acceptable cell sits near that region's
|
||||||
|
lower-left boundary, and a monotone
|
||||||
|
walk from the top-left corner traces that boundary in roughly (tiers + effort notches)
|
||||||
|
cells instead of (tiers × effort notches) - and the cells it skips are the expensive
|
||||||
|
corner. (On cheap evals the walk buys pre-registrable discipline more than dollars:
|
||||||
|
one measured program's full grid cost ~$20 all-in.) Scope note: the "stronger model at lower effort" pattern is measured at list
|
||||||
|
prices on ordinary-sized tasks and is benchmark-dependent - the walk verifies it on
|
||||||
|
the user's own eval rather than assuming it.
|
||||||
|
|
||||||
|
*Set up the grid.* Rows are model tiers ordered by capability; columns are effort
|
||||||
|
notches (low -> high). Two regularities make the walk work, and one of them is the
|
||||||
|
load-bearing assumption to name in the plan: within a row, cost rises with effort
|
||||||
|
(measured in every row of both programs behind this guide); and at fixed effort,
|
||||||
|
quality rises with tier (held in every measured pair - where it bends, the walk
|
||||||
|
mis-prunes, which is part of what the registered confirm exists to catch). Quality
|
||||||
|
along the *effort* axis is only weakly monotone - in one measured family the high
|
||||||
|
notch drew below low on single-run screens (a tie within the measured ~±6 noise
|
||||||
|
band, while costing 1.7× the tokens) - so the walk never leans on it. The frontier tier above the
|
||||||
|
default top row, where one exists, sits *outside* the grid as an extension: it has
|
||||||
|
repeatedly priced above the top row's medium cell (~7× the eventual winner in one
|
||||||
|
measured migration), so treat it as a quality probe, not a cost candidate - the
|
||||||
|
cost-plausibility screen below is the test that decides this per workload.
|
||||||
|
|
||||||
|
*Round-0 diagnostic (before the grid spends anything).* From the baseline repeats
|
||||||
|
already run for the noise bar, read two signals out of the transcripts: output-token
|
||||||
|
share and turns per task. The third signal - effort sensitivity - costs one or two
|
||||||
|
cheap cells on the *old* model at a different effort. Output-heavy, multi-turn, and
|
||||||
|
effort-sensitive -> expect the winner near the top rows' low cells and budget repeats
|
||||||
|
there. Input-heavy, single-shot, effort-flat -> the exception class, where per-token
|
||||||
|
price dominates; the entry cell is the same, but expect to step down quickly and
|
||||||
|
budget repeats for the bottom rows. The diagnostic sets where repeats get spent,
|
||||||
|
never where the walk enters.
|
||||||
|
|
||||||
|
*Cost-plausibility screen (what "cost-plausible" means).* Project each candidate
|
||||||
|
tier's low cell from billing texture at matched effort - the tier's token prices
|
||||||
|
times a low-effort texture, which the round-0 diagnostic already bought on the old
|
||||||
|
model; if only the baseline's own-effort texture exists, discount it by the measured
|
||||||
|
round-0 effort ratio before applying the bar. (This is rule 4's effort-matching
|
||||||
|
requirement applied at screen time: a profile at a different effort overstates a low
|
||||||
|
cell by roughly the effort ratio, and at the screen the overstatement lands on the
|
||||||
|
silent-exclusion side.) A tier moves out to the above-grid extension only when the
|
||||||
|
evidence is overdetermined: no projection within the documented error band brings
|
||||||
|
its low cell in under the next tier down's medium cell - a bare point estimate
|
||||||
|
cannot establish "can't"; measured projection errors have run ~2× optimistic and
|
||||||
|
2.8× pessimistic - AND no measured or reported token-economy evidence suggests the
|
||||||
|
tier closes that gap in this workload's regime (smarter tiers spend fewer tokens per task, but how much is regime- and
|
||||||
|
pair-dependent, and the measured economies so far are single-draw readings - treat
|
||||||
|
them as direction, not magnitude). The screen is one-sided by design: when in doubt the tier stays in
|
||||||
|
the grid, because the walk makes inclusion errors cheap (the entry probe is that
|
||||||
|
tier's cheapest cell, and a fail prunes a whole column) while exclusion errors are
|
||||||
|
silent (only the on-fail extension trigger can catch one). Record the screen's
|
||||||
|
verdict and its basis in the pre-registration.
|
||||||
|
|
||||||
|
*Enter at the highest cost-plausible new-generation tier at low effort.* Three
|
||||||
|
reasons. Only the top-left corner gives an unambiguous walk - a pass prunes in one
|
||||||
|
direction and a fail prunes in the other, while from the bottom-left corner a fail
|
||||||
|
leaves two uphill directions and no way to choose without probing both. The entry
|
||||||
|
probe is the top tier's cheapest cell, so it is budget-bounded. And it doubles as the
|
||||||
|
regime test: if the whole top row fails the floor, the eval sits at or above the
|
||||||
|
models' capability frontier - upgrading is a quality story, not a cost story; stop
|
||||||
|
searching for savings and say so. (One honest cost: the top row *before the first
|
||||||
|
pass* has no incumbent, so its rightward walk is cost-unbounded by construction.
|
||||||
|
That is the regime probe's price.)
|
||||||
|
|
||||||
|
*The walk.*
|
||||||
|
|
||||||
|
- **Pass at (tier k, effort e):** record the cell as the incumbent with cost c*, drop
|
||||||
|
the rest of row k, and step *down* a tier - from here on, only into cells projected
|
||||||
|
under c*. The row-drop needs no quality assumption at all: every cell rightward of
|
||||||
|
a pass costs more than the pass, so it cannot beat the incumbent whether or not it
|
||||||
|
clears the floor. That makes the rule robust to effort non-monotonicity.
|
||||||
|
- **Fail at (tier k, effort e):** presume every lower tier at effort e also fails
|
||||||
|
(the tier-monotonicity assumption above) and step *right*. Once an incumbent
|
||||||
|
exists, step only into cells projected under c*, and cap the rightward walk at one
|
||||||
|
or two notches - quality in effort is too weakly monotone to chase further.
|
||||||
|
- **Overlap probes:** after a fail-then-pass on tier k, cells of tier k-1 projected
|
||||||
|
under c* may still be probed. This overlap - the smaller model working hard against
|
||||||
|
the smarter model barely trying - is the only place the walk branches.
|
||||||
|
- **Extension trigger (the one upward move):** if the top row's low cell fails and
|
||||||
|
the row's passing cells price near the above-grid extension tier, probe the
|
||||||
|
extension's low cell before stopping. This is also the only recovery path for a
|
||||||
|
tier the screen wrongly excluded - project it effort-matched (rule 4).
|
||||||
|
- **Stop** when no unprobed cell projects under c* and the extension trigger is
|
||||||
|
quiet. The incumbent is the answer.
|
||||||
|
|
||||||
|
In one sentence: enter at the highest cost-plausible new-generation tier at low
|
||||||
|
effort; step down on pass, right on fail; prune by incumbent cost; the frontier
|
||||||
|
tier's low cell is the on-fail extension above the grid, and the old model at low is
|
||||||
|
the round-0 diagnostic below it.
|
||||||
|
|
||||||
|
*Decision machinery the walk cannot run without.*
|
||||||
|
|
||||||
|
1. **The floor is pre-registered before round 1** - for example the baseline's best
|
||||||
|
repeat, with the rationale stated - never the baseline mean read after the fact.
|
||||||
|
In one measured migration the registered floor was set above the baseline mean
|
||||||
|
precisely because a one-repeat score at or just under that mean is as likely
|
||||||
|
below baseline as at it - such a read is not admissible evidence of parity.
|
||||||
|
2. **Promotion needs n >= 2 near the floor.** Any cell about to become the incumbent
|
||||||
|
whose margin over the floor is inside the noise bar gets a second run before c*
|
||||||
|
moves. The errors are asymmetric and the expensive one is the false *pass*: a
|
||||||
|
lucky pass sets c* and prunes the true winner, a lower tier failing says nothing
|
||||||
|
about whether the pass above it was real, and the final confirm catches the error
|
||||||
|
only after the pruned cells are gone. (Measured: a winner that passed at 11 of 20
|
||||||
|
at one repeat drew 6 of 20 later on the identical configuration.) A false fail
|
||||||
|
just sends the walk one cell right - cheaper, and the next rule covers it.
|
||||||
|
3. **Fails inside the noise bar of the floor get re-tested** before the walk steps
|
||||||
|
right on their account.
|
||||||
|
4. **Pruning is calibrated deferral, not deletion.** Project a cell's cost from
|
||||||
|
billing texture - the tier's token prices times a measured token profile MATCHED
|
||||||
|
TO THE CANDIDATE'S EFFORT (a low-effort candidate projects from a low-effort
|
||||||
|
cell's banked texture; the incumbent's profile at a different effort overstates
|
||||||
|
the candidate by roughly the effort ratio - a measured case read 2.8× too high on
|
||||||
|
an incumbent-at-higher-effort basis, and the effort-matched projection reversed
|
||||||
|
the verdict to cheaper-than-incumbent) - and never from priors alone: early
|
||||||
|
projections in one measured program ran ~2× optimistic, and optimistic
|
||||||
|
projections *under*-prune. A pruned cell is deferred; re-admit it if the
|
||||||
|
projections recalibrate.
|
||||||
|
|
||||||
|
*What the walk looks like on real evals.* Replaying the two measured migrations
|
||||||
|
behind this guide: on the ordinary-workload eval the walk reaches the eventual winner
|
||||||
|
in two cells - the entry cell passes at low, and the tier below passes at low once
|
||||||
|
the prompt is clean (under the surviving cruft it failed there, and was rescued by
|
||||||
|
the Step 4 re-probe - see that step's caveat) - and then asks the one question the
|
||||||
|
actual program never did, the next tier further down; the frontier-tier cell that
|
||||||
|
program did run plays the declared quality-probe role below. On the frontier-hard eval the entry cell fails the floor, and the same
|
||||||
|
tier's medium cell passes - one point over the floor, inside the noise bar, which is
|
||||||
|
exactly the case rule 2 above exists for: it gets a second run before it promotes to
|
||||||
|
incumbent. (The confirm's later 11, 6, 11 spread on that identical configuration is
|
||||||
|
the demonstration - a one-point margin at one repeat can be a 6.) The walk then steps down to the
|
||||||
|
mid tier's low cell - a probe the actual program never fired (projected cheaper than
|
||||||
|
the cells it did) - and on a fail would step right into the mid tier's medium cell,
|
||||||
|
which the program did fire: it came in under the incumbent's cost and failed badly.
|
||||||
|
There the walk stops, pruning without running it the mid tier's high cell, which the
|
||||||
|
actual program paid real money to learn was priced above the incumbent. (That program's winner read -46% vs the same model's high setting and -43% vs the
|
||||||
|
old-model baseline on fresh-run means, where the single cheapest selection pass read
|
||||||
|
-50%/-48% on the same comparisons: report the fresh-run means, never the favorable
|
||||||
|
end of a spread. Both arms billed on an internal page-counted route; on public
|
||||||
|
breakpoint billing the reductions run a few points smaller - ~-40% on the baseline
|
||||||
|
comparison - and the arms compare like-for-like either way.) The frontier-hard case is also the cautionary half: the winner's
|
||||||
|
pre-registered confirm FAILED its stability clause - the identical configuration drew
|
||||||
|
11 of 20 on the selection pass and then 11, 6, and 11 across the three fresh confirm
|
||||||
|
runs - so the honest verdict was "cost cut firm,
|
||||||
|
mean quality comparable within noise, NOISIER than baseline", and the headline had to
|
||||||
|
be the confirm's number, not the selection round's. Which regime you are in decides
|
||||||
|
whether upgrading is a cost lever or a quality lever; the entry cell is what tells
|
||||||
|
you, in one bounded probe.
|
||||||
|
|
||||||
|
*Per-cell honesty rules (they apply to every probe in the walk):*
|
||||||
|
|
||||||
|
- **Single-run reads are pass/fail evidence, not rankings.** A single eval pass can
|
||||||
|
swing several points on sampling alone (a recorded small-set example: ~8 points,
|
||||||
|
±6 across repeats). The honest single-run signals are *telemetry* - realized
|
||||||
|
thinking tokens, output tokens, and tool rounds per case - not small score deltas.
|
||||||
|
Measure the noise bar BEFORE the walk (repeat runs of the incumbent config, or
|
||||||
|
pass@k over existing results files), so the floor margin and the promotion rule
|
||||||
|
have a number to work with.
|
||||||
|
- **Confirm the effort dial is alive before crediting a rightward step.** Effort
|
||||||
|
curves are per-model-family and not always monotonic: measured cases include a
|
||||||
|
family where medium beat high, and a score curve with a knee that endpoint
|
||||||
|
sampling cannot see. If a step right does not change realized thinking tokens, the
|
||||||
|
dial is dead for that family - further rightward cells are the same cell at a
|
||||||
|
higher price, so treat the row as exhausted.
|
||||||
|
- **Walk cost readings are cache-cold.** Cells never share cache - the cache is
|
||||||
|
per-model and effort participates in the cache key (Step 0) - so production cost
|
||||||
|
will be cheaper than walk cost by the cache rate; either warm each cell or
|
||||||
|
annotate the readings. Keep effort fixed within any session whose cost is being
|
||||||
|
measured, or cache invalidation noise lands in the effort arm's numbers.
|
||||||
|
- **State the billing basis per cell.** Eval-harness billing routes can differ from
|
||||||
|
what an API customer pays - some internal routes count cache in fixed-size pages
|
||||||
|
where the public API bills exact tokens from breakpoints - and the same run can
|
||||||
|
differ materially in reported cost across routes. Check which route the ledger
|
||||||
|
rides before quoting absolute costs; ratios between cells on the same route are
|
||||||
|
more robust than absolutes.
|
||||||
|
|
||||||
|
*Declare a quality probe, or the ceiling goes unmeasured.* By construction the walk
|
||||||
|
never fires the expensive corner, so a migration that passes early never learns what
|
||||||
|
the top tier at high effort would have bought. If that number is wanted - it usually
|
||||||
|
is, once - run the top-right cell, or the above-grid frontier tier at low, as ONE
|
||||||
|
declared quality-reference cell outside the cost walk, marked as such in the plan.
|
||||||
|
Skippable on tight budgets.
|
||||||
|
|
||||||
|
*When entering from the bottom is defensible.* Two cases. (1) Steady-state tuning -
|
||||||
|
already on a current-generation model with a tuned prompt, just trimming: sweep
|
||||||
|
effort downward from where you are, but ALWAYS add the single next-tier-up-at-low
|
||||||
|
probe. The blind spot it closes: a bottom-up sweep that finds quality fine and cost
|
||||||
|
high at a lower tier never escalates, so the cheaper-better cell one tier up at low
|
||||||
|
is never tested. The measured billing overlap is why this is unsafe to skip: in one
|
||||||
|
program the top tier's low cell drew per-run costs both below and above the mid
|
||||||
|
tier's medium cell across two draws (~0.8× and ~1.5× its cost, the mid cell itself
|
||||||
|
a single draw) while solving more cases in both - adjacent tiers' measured cost
|
||||||
|
bands overlap, so tier order cannot be trusted to give cost order
|
||||||
|
(overlap evidence for the hazard, not an observed firing of the blind spot itself:
|
||||||
|
in that program the mid tier's cell also failed the floor, so even a bottom-up sweep
|
||||||
|
would have escalated). (2) A total budget of a cell or two plus a round-0 diagnostic
|
||||||
|
reading "exception class": go straight to the same-tier successor at low and accept
|
||||||
|
the risk of missing the inversion.
|
||||||
|
|
||||||
|
(For what the effort knob is and when the top of the range earns its cost, see the
|
||||||
|
skill's effort-level guidance - a pending skill update, not yet in the shipped
|
||||||
|
package; this section is about how to SEARCH it.)
|
||||||
|
|
||||||
|
**Step 3 - Prompt-hillclimb on the frozen model.**
|
||||||
|
Prompt wins do not transfer across models - measured gains of +30 and +15 points on two
|
||||||
|
model families were each model-specific, and one newer model's failure mode was not
|
||||||
|
prompt-addressable at all. Hillclimbing the prompt before the model is frozen wastes
|
||||||
|
the climb. Run the loop per the hillclimb guide, with the cost-specific rules below.
|
||||||
|
|
||||||
|
Do not assume the prompt is where the cost lives. The Step 1 audit tells you what is
|
||||||
|
*wrong* with a prompt; only measurement tells you what the wrongness *costs*. In one
|
||||||
|
measured case a dated opener full of turn-inflating ritual (forced plan files,
|
||||||
|
re-read-after-every-edit, full test suite after every change) audited as an obvious
|
||||||
|
cost win - and the cleaned opener failed to save anything: both cleanup cells landed
|
||||||
|
above the CEILINGS of their pre-registered 80% cost intervals (the cleaned cell's
|
||||||
|
point prediction was a ~32% cut), and inside the incumbent's own identical-config cost
|
||||||
|
spread measured later (so "cost more" is within noise; "missed its pre-registered
|
||||||
|
cost interval entirely" is the solid finding). The engagement census (below) showed the
|
||||||
|
forced-reasoning ritual was fully ignored while a plan-file instruction was genuinely
|
||||||
|
obeyed in 17 of 20 runs - and deleting all of it saved nothing, because per-run cost
|
||||||
|
was bound by turn count and context growth, not by opener text. That is sharper than
|
||||||
|
"models ignore dead text": even the obeyed scaffolding was not where the cost lived.
|
||||||
|
Pre-register the falsifier before the cleanup round - "if the cleaned prompt does not
|
||||||
|
come in under a named cost bar, the prompt lever is exhausted here, say so" - so a
|
||||||
|
no-win closes the lever with a recorded finding instead of inviting another round of
|
||||||
|
edits at the same dead wall.
|
||||||
|
|
||||||
|
**Step 4 - After the prompt climb, re-probe one cell down-left.**
|
||||||
|
One effort notch lower, or one tier lower at the effort that just passed. Cleanup can
|
||||||
|
make a previously failing cheaper cell viable, so the walk's verdict on those cells
|
||||||
|
expires when the prompt changes: in one measured migration the mid tier's low cell
|
||||||
|
went from 0.64 under the dated prompt to 0.98 after the transcript-driven cleanup on
|
||||||
|
the frozen model. Honest caveat: that rescue came
|
||||||
|
from the round-3 transcript-driven cleanup; whether the lighter pre-grid mechanical
|
||||||
|
audit (Step 1) alone recovers such cells is untested - the earlier program's arc
|
||||||
|
suggests it recovers much of the gap (audited cells scored far above swap-only cells
|
||||||
|
on the same eval), but treat that as suggestive, not measured, for this specific
|
||||||
|
re-probe. One cell, not a re-opened search: if it passes under the incumbent's cost,
|
||||||
|
it becomes the configuration the confirm tests; if not, the incumbent stands.
|
||||||
|
|
||||||
|
**Step 5 - Final effort re-sample = the registered joint confirm.**
|
||||||
|
After the prompt climb (and the Step 4 re-probe, if it promoted a cheaper cell),
|
||||||
|
re-sample effort around the chosen point at n>=3 and make that
|
||||||
|
run the pre-registered confirm of the full (model, prompt, effort) configuration - the
|
||||||
|
three adoption gates below, registered before it fires, on held-out cases if any exist.
|
||||||
|
This is the number to report. (The prompt winner was selected at the earlier effort
|
||||||
|
point; the direct prompt×effort interaction is unmeasured, so a prompt tuned under rich
|
||||||
|
thinking may not hold at lower effort - the joint confirm is the insurance.)
|
||||||
|
|
||||||
|
**Step 6 - Multi-model topologies only behind a task-shape preflight - usually never.**
|
||||||
|
Across every measured comparison, one strong model at the right effort beat every team
|
||||||
|
shape on the cost-score plane: cheap tokens pay by *substitution* (the cheap model does
|
||||||
|
the work instead), never by *addition* (a helper alongside a strong lead) - a strong
|
||||||
|
lead pays roughly an order of magnitude in its own tokens to consume cheap help. The
|
||||||
|
bar for any topology candidate is the model×effort frontier from Step 2 ("does this
|
||||||
|
beat what the effort dial gives for free?"). Documented exceptions worth a preflight:
|
||||||
|
the executor is constrained to be cheap or non-Claude (then one up-front plan call by
|
||||||
|
the strong model, with zero mid-run interaction, can pay); the executor is genuinely
|
||||||
|
weak (advisors pay below the lead's tier, with a floor); or the task has a visible,
|
||||||
|
checkable artifact (verification transfers; capability does not).
|
||||||
|
|
||||||
|
## Adoption gates - register before round 1
|
||||||
|
|
||||||
|
A candidate change (prompt edit, effort cut, model swap) is adopted only if ALL three
|
||||||
|
pre-registered gates pass:
|
||||||
|
|
||||||
|
1. **Quality band** - held-out score within a named band of the incumbent (state the
|
||||||
|
band before running).
|
||||||
|
2. **Cost margin** - strictly cheaper beyond a registered margin, measured at the
|
||||||
|
stated pricing basis.
|
||||||
|
3. **Mechanism** - the *predicted* mechanism appears in the measurements (e.g. "this
|
||||||
|
edit removes duplicate lookups" must show up as fewer tool calls, not just a lower
|
||||||
|
bill). A cost tie with the right mechanism and a cost win with the wrong mechanism
|
||||||
|
are both rejections: the first is an edit that didn't bite, the second is an
|
||||||
|
unexplained confound that will not survive contact with production.
|
||||||
|
|
||||||
|
The final joint confirm (Step 5 of the search order) reports against these same gates;
|
||||||
|
three sequential selections, each made on the data that chose it, overstate the
|
||||||
|
combined win, so the confirm's number - not the per-round selection scores - is the
|
||||||
|
headline.
|
||||||
|
|
||||||
|
## Measurement discipline
|
||||||
|
|
||||||
|
- **Noise bar first.** Before round 1, answer "how big must a delta be to be believed?"
|
||||||
|
with a number, from repeat runs of the unchanged config. The same baseline repeats
|
||||||
|
feed the round-0 diagnostic of the model×effort walk (Step 2): read output-token
|
||||||
|
share and turns per task out of their transcripts while measuring the bar. If the tuned artifact is
|
||||||
|
itself a stochastic generation (e.g. a built index or wiki, not a fixed prompt),
|
||||||
|
measure *build* variance with a no-change rebuild control before judging any edit.
|
||||||
|
- **Selection set != holdout.** The split whose score picks winners each round is a
|
||||||
|
selection set, even if the guide calls it "test". Pre-register confirm runs for the
|
||||||
|
headline and expect train->holdout shrinkage.
|
||||||
|
- **Pricing basis discipline.** Lock and state the pricing basis up front (which price
|
||||||
|
sheet, whether cache-adjusted, promo vs standard). The same run's reported cost can
|
||||||
|
diverge severalfold across bases - cached input bills at a tenth of the fresh-input
|
||||||
|
price, so cache-adjusted and flat accountings of one run separate fast at high
|
||||||
|
cache rates. Do paper arithmetic with the rate card before spending:
|
||||||
|
it can exclude whole configurations with zero eval runs.
|
||||||
|
- **Register cost in the objective.** An optimizer optimizes exactly what is
|
||||||
|
registered: a quality-only climb raised cost per deliverable by 75% in one measured
|
||||||
|
search. If the goal is cost-subject-to-quality, the gates above ARE the objective -
|
||||||
|
write them into the plan sign-off.
|
||||||
|
- **One lever per round, frozen arm.** Move exactly one axis per round so wins and
|
||||||
|
regressions are attributable.
|
||||||
|
- **Make the optimizer predict before it measures.** Require, in each round's
|
||||||
|
proposal, a point estimate and an 80% interval for every cell - on score AND cost -
|
||||||
|
plus named falsifiers ("if X happens, the lever is dead; say so"). Compare outcomes
|
||||||
|
to intervals after each round, and shift and widen the next round's intervals after
|
||||||
|
misses. This turns every round into a correction of the optimizer's own predictions: in
|
||||||
|
one measured search the optimizer's round-2 cells both landed just below its solved
|
||||||
|
intervals; it said so, re-centered, and the falsifier it registered for round 3 is
|
||||||
|
what caught the prompt-lever no-win cleanly.
|
||||||
|
- **Verify serving identity and wiring before believing any arm.** Record the model id
|
||||||
|
from the *response*, not the config; confirm usage fields are present per case; run
|
||||||
|
on an eval surface that reports them; disable any auto-retry scoring that passes on
|
||||||
|
either attempt. A result without wiring receipts is not evidence.
|
||||||
|
- **Audit graders before believing persistent failures.** Re-grading has shrunk a
|
||||||
|
claimed +9-point win to +3 in a measured case. When a case fails every round, suspect
|
||||||
|
the grader before grinding prompt content at it.
|
||||||
|
- **Routers price only on the full traffic frame.** A difficulty-router evaluated on a
|
||||||
|
hard subset self-defeats (everything routes to the big model and you pay the routing
|
||||||
|
overhead for nothing); its savings exist only on the full distribution, and are
|
||||||
|
paper-only until the predictor is tested.
|
||||||
|
|
||||||
|
## What drives prompt cost (measured mechanics)
|
||||||
|
|
||||||
|
- **Cost scales with extra actions triggered, not prompt length.** In one measured
|
||||||
|
decomposition, a single extra tool round added roughly a third of the per-case
|
||||||
|
cost, while longer-but-inert prompt text was nearly free - *when cached*.
|
||||||
|
- **Census engagement before trimming.** Before editing scaffold instructions, count
|
||||||
|
in existing transcripts the artifacts each instruction demands (plan-file writes,
|
||||||
|
forced reasoning blocks, capped or repeated reads, per-edit suite runs, narration
|
||||||
|
phrases) - and subtract the prompt's own occurrences of each marker, or static text
|
||||||
|
masquerades as engagement. Near-zero corrected counts mean the model is ignoring
|
||||||
|
that text: dead weight, nearly free while cached, and deleting it will not cut cost.
|
||||||
|
Expect mixed pictures - in the measured case the forced-reasoning ritual counted
|
||||||
|
zero everywhere while a plan-file instruction was engaged in 17 of 20 runs. A
|
||||||
|
two-cell ablation (cleaned opener vs cleaned-plus-ritual) is cheap and settles
|
||||||
|
whether a suspect block is load-bearing: here the two cells landed within 2% on cost
|
||||||
|
and tied exactly on the held quality gate (the partial-credit diagnostic moved, a
|
||||||
|
reminder that "tied" is metric-relative) - the ritual was dead weight at the scale
|
||||||
|
the test could detect.
|
||||||
|
- **The expensive patterns are action-triggering instructions.** "Verify twice"
|
||||||
|
(+48% per-case cost via duplicate lookups and re-deliberation) and "be maximally
|
||||||
|
thorough" (+39% via unneeded tool calls) together cost roughly twice as much as all
|
||||||
|
other measured cost-adding patterns combined. Audit for instructions that trigger
|
||||||
|
redundant actions before trimming words.
|
||||||
|
- **Charge a prompt edit its own token mass at the real cache-adjusted price.** A
|
||||||
|
standing directive that rides every request must net positive against its own mass:
|
||||||
|
one measured 650-character directive produced exactly the predicted behavior change
|
||||||
|
and still only tied on cost, because its per-request mass canceled the saving.
|
||||||
|
- **Brevity caps save money through shorter replies** - a reply-quality tradeoff to
|
||||||
|
surface to the user, not a free win. Flag the median reply-length change alongside
|
||||||
|
the cost saving.
|
||||||
|
- **Output tokens are the latency lever too.** In latency-bound products, output-token
|
||||||
|
prompting rises in priority: one customer self-reported ~11% output-token cuts with
|
||||||
|
quality flat-or-up (a practitioner report, not a benchmark measurement), and streamed
|
||||||
|
tokens are directly perceived latency.
|
||||||
|
|
||||||
|
## Stopping rules
|
||||||
|
|
||||||
|
- **Prompt rounds:** wins come in rounds 1-2; stop when two consecutive variants fail
|
||||||
|
to beat the incumbent beyond the noise band; cap at ~3-4 rounds per model.
|
||||||
|
- **Effort:** savings saturate stepwise (each step down saves less while variance
|
||||||
|
grows). Stop inside the noise band. Remember lowered effort doesn't fail fixed cases -
|
||||||
|
failures MOVE between runs ("shallower thinking fails wherever the margin is thin"),
|
||||||
|
so effort-cut decisions need aggregate non-inferiority over multiple runs, never
|
||||||
|
per-case reads.
|
||||||
|
- **The model×effort walk:** stops itself - when no unprobed cell projects under the
|
||||||
|
incumbent's cost and the extension trigger is quiet, the incumbent is the answer.
|
||||||
|
Do not keep probing "to be sure";
|
||||||
|
the declared quality-reference cell is the sanctioned way to buy information
|
||||||
|
outside the walk.
|
||||||
|
- **Overall:** when the joint confirm passes its gates, ship; when it fails, report the
|
||||||
|
best gated configuration honestly rather than re-searching on the confirm data.
|
||||||
204
skills/claude-api/shared/evals/eval-audit.md
Normal file
204
skills/claude-api/shared/evals/eval-audit.md
Normal file
@@ -0,0 +1,204 @@
|
|||||||
|
# Eval health checklist
|
||||||
|
|
||||||
|
This file is loaded whenever an eval is being **built** (`build-eval.md`) or **climbed on** (`eval-hillclimb.md`). It has two jobs. When you are writing the eval, every item below is a construction requirement - the runner, grader, and case set you produce should satisfy it by default, not after someone flags it. When the user brings an existing eval, it is the verification pass you run before building anything on top of it. Either way, run it once more before the first full paid pass and before round 1 of a hillclimb.
|
||||||
|
|
||||||
|
Before trusting an eval to tell you which model, prompt, or configuration is better, check that the eval itself is sound. A broken eval produces confident-looking numbers that point in the wrong direction, and a hillclimb over a broken eval just multiplies the misdirection: you will "improve" an artifact and ship nothing. In practice the most surprising eval results usually turn out to be bugs in the eval rather than facts about the model, so an hour of auditing up front routinely saves days of chasing phantom differences.
|
||||||
|
|
||||||
|
The checks are grouped into **task design** (are the cases right?), **harness design** (is the scaffolding right?), **metrics hygiene** (are cost and latency measured correctly?), **grader design** (is the scoring right?), and **can it detect the change you're after** (is there enough signal for the decision?). They are written as direct instructions: for each, look at the eval's actual code, config, and data, not its README. The final section, **Reporting findings to the user**, covers how to communicate what you find; the checks are declarative, but the report to the human is observations and suggestions, since the eval's author almost always has context that justifies choices an outsider would flag.
|
||||||
|
|
||||||
|
Before auditing further, run the eval once end-to-end on a handful of cases, or find a recent results file. A surprising number of eval-quality discussions turn out to be about code that does not currently run.
|
||||||
|
|
||||||
|
## 1. Task design
|
||||||
|
|
||||||
|
These checks concern the cases themselves: what is being asked, what counts as correct, and whether the set as a whole can distinguish between the systems being compared.
|
||||||
|
|
||||||
|
### Auditing case sets at scale
|
||||||
|
|
||||||
|
The harness and grader are code you can read end to end; the case set may be hundreds of items you cannot. Do not try to read every case inline. Work in three tiers:
|
||||||
|
|
||||||
|
**Tier 1: programmatic checks over the full set.** Write a short script that loads every case and reports: exact- and near-duplicate rate; label or category balance; prompt-length and expected-answer-length distributions; schema validity and missing-field counts; obviously malformed rows. Cheap, exhaustive, and catches skew, duplicates, truncation, and broken rows regardless of set size.
|
||||||
|
|
||||||
|
**Tier 2: stratified sample for a close read.** Draw twenty to fifty cases, stratified across `tags[0]` if it exists, otherwise uniformly at random, and apply the per-case checks below to those. Recommend the user read a handful themselves as well - a second pair of human eyes on raw cases catches things no checklist does. (This is what the build-eval inputs sign-off is for; the report's per-case table is the surface.)
|
||||||
|
|
||||||
|
**Tier 3: per-case LLM auditor.** For sets beyond a few hundred items, run one isolated model call per case with a tight audit prompt, collect a structured verdict, and aggregate. Ask before running it - the cost is roughly N cheap-model calls - and offer it explicitly: "I can run a per-case auditor over all N cases, ~$X. Want me to?"
|
||||||
|
|
||||||
|
A per-case auditor prompt that works well (adapt field names to the eval's schema):
|
||||||
|
|
||||||
|
```
|
||||||
|
You are auditing a single case from an evaluation suite. Given the prompt, the reference answer, and a description of how the grader decides pass/fail, flag any of the following. Be conservative - only flag when reasonably confident.
|
||||||
|
|
||||||
|
PROMPT:
|
||||||
|
{prompt}
|
||||||
|
|
||||||
|
REFERENCE ANSWER:
|
||||||
|
{gold}
|
||||||
|
|
||||||
|
GRADER BEHAVIOUR:
|
||||||
|
{grader_description}
|
||||||
|
|
||||||
|
For each issue answer yes/no with a one-line reason if yes:
|
||||||
|
- ambiguous: could two careful experts reasonably disagree on the correct answer?
|
||||||
|
- gold_suspect: does the reference answer look wrong, incomplete, or arguable?
|
||||||
|
- answerable_from_memory: could a well-read model answer this without doing the intended work?
|
||||||
|
- grader_too_strict: are there clearly correct answers the grader as described would reject?
|
||||||
|
- grader_too_lenient: are there clearly wrong answers the grader as described would accept?
|
||||||
|
- trivially_cheatable: is there a shortcut that satisfies the grader without solving the task?
|
||||||
|
- other: anything else that would make this case's result misleading.
|
||||||
|
|
||||||
|
Return JSON: {"case_id": "...", "flags": {"ambiguous": {"flagged": bool, "reason": "..."}, ...}, "overall": "ok" | "review" | "broken"}
|
||||||
|
```
|
||||||
|
|
||||||
|
Cluster by flag type, surface the top issues with example case IDs, and feed them into the report (§6).
|
||||||
|
|
||||||
|
The per-case checks (apply to the tier-2 sample):
|
||||||
|
|
||||||
|
- **Unambiguous success criteria.** Would two independent domain experts, shown the same output, agree on pass vs fail? If the criteria admit reasonable disagreement ("write a *good* summary"), scores reflect grader opinion as much as model capability. Note the dual failure: under-specified (a required output, filename, format left unstated) or over-specified (the prompt is a step-by-step recipe, leaving nothing for the model to decide).
|
||||||
|
|
||||||
|
- **Reference solution exists and passes.** Does each case ship with at least one gold answer that actually passes the grader? A 0% pass rate across all variants is more often a broken case than a hard one. Spot-check by running the reference through the grader.
|
||||||
|
|
||||||
|
- **Ground-truth labels are correct.** Sample ten cases and independently re-derive the expected answers. Widely used benchmarks routinely carry meaningful label error; wrong labels cap measurable accuracy for reasons that have nothing to do with the model.
|
||||||
|
|
||||||
|
- **Where did the ground truth come from?** Ask, and record the answer as a tag: human-written, human-verified, or **a model's outputs - and which model**. If the expected outputs are a model's outputs, reference-match scoring rewards *imitating that model*, not being right; this is worst in a migration, where gold derived from the incumbent makes the incumbent look best by construction and penalises a successor for every stylistic difference. Prefer a rubric or pairwise judge over reference similarity in that case, or have a human verify a sample of the references first. Never use model A's outputs as gold when the question is A vs B.
|
||||||
|
|
||||||
|
- **No annotation artifacts.** Could a trivial baseline score well from surface patterns - question length, keywords, option order - without solving the task? If a no-op or majority-class baseline scores well above chance, the eval is partly measuring the artifact.
|
||||||
|
|
||||||
|
- **Label leakage in the prompt.** Does the expected answer, or a near-paraphrase, appear anywhere the model can see - the prompt, few-shot examples, system message, a tool description, a file the agent can read? Common in few-shot setups assembled by copy-pasting from the golden set.
|
||||||
|
|
||||||
|
- **Answerable from memory.** For cases about real, named entities, can the model answer from parametric memory even though the intent is to test retrieval or tool use? If the goal is whether the model can *do the work*, subjects need to be obscure or synthetic enough that recall alone doesn't carry it.
|
||||||
|
|
||||||
|
- **Difficulty comes from the problem, not the prompt.** Are hard-looking cases just worded obscurely? Then the score measures prompt-deciphering. Suggest stating the problem plainly and letting the problem itself be hard.
|
||||||
|
|
||||||
|
- **Agentic cases: symptom, not investigation.** For cases that ask an agent to diagnose or fix something, how much of the investigation is handed over in the prompt? If it already includes the log line, the failing test name, or the file, the eval measures whether the model can read a hint, not find one. Give the agent what a user would plausibly report and let it fetch the rest.
|
||||||
|
|
||||||
|
- **Realistic distribution and interaction shape.** Compare a handful of cases to production traffic. Also check the *shape*: a single-turn eval won't capture effects that only appear in long multi-turn or agentic settings, and vice versa. Name any obvious divergence up front so readers can calibrate how far results transfer.
|
||||||
|
|
||||||
|
- **Difficulty headroom.** If results exist, look at the spread. If the baseline already scores ~95%+, the eval cannot discriminate at the top and a hillclimb will mostly move cost or latency - useful, but say so in advance. If everything scores ~0%, there is more often a case or grader bug than a genuinely impossible task.
|
||||||
|
|
||||||
|
- **Saturated evals and what they end up measuring.** Near the ceiling, remaining variance is dominated by format quirks, grader tie-breaking, or mild reward-hacking rather than capability. Flag that the last few points may no longer measure what the eval was built for; suggest harder items.
|
||||||
|
|
||||||
|
- **Class balance.** For classification-style evals, check the label distribution; report the majority-class baseline alongside model scores. When both positives and negatives exist, prefer precision/recall/specificity to accuracy alone.
|
||||||
|
|
||||||
|
- **Both-directions coverage.** An eval for "does the agent search when it should" also needs "does the agent *not* search when it shouldn't"; otherwise always-search scores perfectly and one-sided evals produce one-sided optimisation. Same for refusals, tool use, escalation.
|
||||||
|
|
||||||
|
- **One capability per case (when diagnosis matters).** A case that needs retrieval *and* reasoning *and* formatting shows 0 whenever any one breaks. Fine for a headline number; flag it when the user wants to know *why* variants differ.
|
||||||
|
|
||||||
|
- **Inverted items as a smoke test.** Where a clearly weaker variant outscores a clearly stronger one on an item, it is far more often a case or grader bug than a real inversion - a good place to look closely.
|
||||||
|
|
||||||
|
- **Staleness.** If cases reference live facts (prices, dates, API responses, library versions), when were the gold answers last verified? A currently-correct answer gets marked wrong against a stale key.
|
||||||
|
|
||||||
|
- **For generated cases: fix the generator, not the filter.** When cases come from a pipeline, problems in the output are symptoms of something upstream; patching individual items leaves siblings of the same bug. Adjust the generator and regenerate.
|
||||||
|
|
||||||
|
## 2. Harness design
|
||||||
|
|
||||||
|
These checks concern the code around the model call. The central failure mode is **conflation**: any time a non-model artifact - an infra error, a truncated response, a broken tool, a retry delay - lands in the same column as a genuine model result, the eval attributes to the model something that belongs to the plumbing.
|
||||||
|
|
||||||
|
- **Infra failures distinguished from model failures.** How does the runner handle a timeout, an API or rate-limit error after retries, an unparseable output, a response cut off at `max_tokens`, a tool that threw, a grader that itself failed? If any of these are silently scored as 0 (or as pass) and mixed in with real answers, the headline is contaminated. Attempts that never produced a scorable output go to an `errors.jsonl` sidecar with a failure class (harness/serving error, timeout, served-model mismatch) - never into `results.jsonl`, where they'd occupy the `(case, rep)` slot, block resume, and score plumbing as a model failure. Rows that did produce output carry `stop_reason` and `status: truncated` when the response hit `max_tokens`, so a clipped answer is counted and shown but not averaged in as wrong. Refusals are a graded outcome, not an error - record them as their own metric so refusal-zeros and capability-zeros aren't summed.
|
||||||
|
|
||||||
|
- **"No answer" is not "negative answer."** Does the grader distinguish the model *asserting a negative* ("no vulnerabilities found") from the model *failing to produce an answer* (empty, crashed, truncated, unparseable)? If both land on the same label, a runner that errors on every input scores identically to one that carefully found nothing. Look for this in detection, classification, and retrieval evals where "none" is a valid answer.
|
||||||
|
|
||||||
|
- **Clean, isolated state per trial.** Does each (case, rep) start from a fresh environment - no files, rows, git history, env vars, or cached results left from a previous trial? Shared state leaks one case's side effects into another's score, lets an agent read hints from an earlier run, and makes results order-dependent.
|
||||||
|
|
||||||
|
- **Environment complete and functional.** Does the environment actually have what the task requires - dependencies, fixtures, reachable services? A case that fails for every variant because a package is missing measures the environment. Distinguish from deliberate obstacles.
|
||||||
|
|
||||||
|
- **Deterministic setup.** Unseeded randomness, unordered iteration that reaches the model or grader, timestamp-dependent paths, stochastic simulators without a fixed seed - these add run-to-run variance unrelated to the system under test. Pin seeds, sort anything whose order matters, and use the sampling parameters you intend for production.
|
||||||
|
|
||||||
|
- **Scaffold limitations separated from model limitations.** A missing tool, a tight step budget, an early-give-up retry policy, or a template that drops context all look like capability gaps from outside. Where practical, vary the scaffold holding the model fixed (or vice versa) to attribute results to the right layer.
|
||||||
|
|
||||||
|
- **Token and context limits won't clip any case.** Compare the longest prompt and longest plausible correct answer against the configured context window and `max_tokens`. Truncation is easy to misread as the model choosing to stop; it must surface as `status: truncated`, not as a wrong answer.
|
||||||
|
|
||||||
|
- **Transient errors retried with jittered backoff, and retries recorded.** Unretried 429/529s show up as spurious failures and can make one variant or one time of day look worse; a zero-delay retry loop is worse - it multiplies cost invisibly and can turn one 429 into a torn-down batch. Back off with jitter, cap attempts, and record the attempt count per row so retries can be excluded from latency and "attempts run vs attempts scored" is visible in the data, not just the bill. If the runner re-runs whole failed *cases*, decide which attempt's grade lands - default strict (passed-only-on-retry is a fail) - and count every attempt's usage.
|
||||||
|
|
||||||
|
- **A hard per-case wall-clock ceiling, independent of stream liveness.** A hung streaming connection can emit keepalives indefinitely, defeating inactivity timers; only a ceiling on total case time reclaims the worker slot. When it fires the attempt goes to `errors.jsonl` as a timeout, never a zero.
|
||||||
|
|
||||||
|
- **The model that served the request is the model you asked for.** Read `model` from the *response* on a smoke case, then assert it on every call - beyond documented alias->snapshot resolution, a mismatch (a provider fallback, a capacity reroute) fails the attempt loudly. A score served by the wrong model measures nothing, and silent substitution may not surface anywhere else; where the provider exposes usage or billing records, cross-check the aggregate once.
|
||||||
|
|
||||||
|
- **Eval config matches production config.** Diff the system prompt, tool definitions, model version, sampling parameters, and scaffolding in the eval against what actually ships. The runner must call the app's real entry point; a re-implemented call silently measures a different setup.
|
||||||
|
|
||||||
|
- **Full per-case trajectories saved.** Every message, tool call and result, and error, per (case, rep) - plus the grader's own inputs and outputs - so a surprising score can be traced to a fact about the model or a bug in the eval without re-running. This is the single highest-leverage habit for a debuggable eval, and it is what the report's Transcripts tab renders (full viewer) or its per-case rows link to (lite).
|
||||||
|
|
||||||
|
- **Multiple trials with variance reported.** A single rep is a point estimate with no error bar; differences smaller than the run-to-run spread are not meaningful. The runner must support reps and reported numbers must carry intervals.
|
||||||
|
|
||||||
|
- **Reproducible over time.** Dependencies pinned, case set and grader versioned together, environment specified. Scores from before and after a grader change are not comparable.
|
||||||
|
|
||||||
|
- **Harness tested on known-good and known-bad.** Before the first full pass, run (a) an oracle - the reference answers, or a variant that *should* score near 100% - and (b) a null baseline - empty output, a constant answer, or the majority class - through the whole pipeline. If the oracle doesn't pass, the harness or grader is broken; if the null doesn't fail, the grader is too lenient. Two runs, minutes, and it catches most wiring bugs before they cost a full pass.
|
||||||
|
|
||||||
|
## 3. Metrics hygiene
|
||||||
|
|
||||||
|
Pass rate alone rarely answers the user's real question, which is some form of "what quality can I get for what cost and latency?" Check that each perf metric reflects the model under test rather than the rig around it.
|
||||||
|
|
||||||
|
- **Token accounting from the API, not estimated.** Input, output, cache-read and cache-write tokens per row from the response's `usage` block. String-length estimates are off by enough to reverse a cost comparison.
|
||||||
|
|
||||||
|
- **Cost derived from recorded tokens and the row's actual model** - including cache rates - never a flat assumed rate; and the judge's cost recorded separately (`judge_model`, `judge_usage`) so it neither hides nor dampens differences between variants.
|
||||||
|
|
||||||
|
- **Cache hit rate comparable across variants.** If one variant runs warm-cache and another cold, cost and latency differences are partly an artifact of run order. Flag comparisons where cache-read share differs materially.
|
||||||
|
|
||||||
|
- **Latency measured against the right boundaries.** Time the final successful request only; keep client-side retries, backoff sleeps, local queueing behind a semaphore, and post-processing out of the model-latency column (record total wall-clock separately if useful). Otherwise whichever variant hit more transient errors looks slower.
|
||||||
|
|
||||||
|
- **Per-call breakdown for agentic evals.** Record tokens, cost, and timing per model call and per tool call, not just per episode, or a slow tool is indistinguishable from a slow model.
|
||||||
|
|
||||||
|
- **Perf reported alongside quality**, per variant, as absolute numbers first - so quality-vs-cost and quality-vs-latency trade-offs are visible rather than implied.
|
||||||
|
|
||||||
|
## 4. Grader design
|
||||||
|
|
||||||
|
These checks concern the function that turns an output into a score - exact match, unit test, end-state check, or LLM judge.
|
||||||
|
|
||||||
|
- **Prompt-grader agreement.** Does the grader reward what the prompt asks for? Common drift: prompt says "at least X", grader passes only on strictly more; prompt asks for an explanation, grader checks only the number. This penalises models that follow instructions.
|
||||||
|
|
||||||
|
- **Grades outcomes, not paths.** Does the grader reward reaching the right answer or taking a particular route? Requiring an exact tool-call sequence, phrasing, or intermediate step fails a model that solved it a different valid way. Check the answer is correct and appropriately grounded without dictating the trajectory.
|
||||||
|
|
||||||
|
- **For agents that act on an environment, grade the end state, not the transcript.** Run the task in a disposable workspace, then score what it left behind programmatically - tests pass, the diff applies cleanly, expected files/rows/values are present, nothing off-limits was touched, step and tool-call counts within budget - and layer a rubric or pairwise judge only for the taste dimensions a check can't see (readability, minimality of the diff, quality of the PR description). A judge reading a coding transcript is grading the narration; the environment is the answer.
|
||||||
|
|
||||||
|
- **Not overly rigid.** For exact/substring graders: whitespace, casing, `4` vs `4.0`, markdown fences, units, thousands separators, a sentence wrapped around the answer. Normalise both sides or accept a small set of equivalent forms.
|
||||||
|
|
||||||
|
- **Not too lenient.** For test-based graders: are the tests thorough enough to catch wrong answers? Write a deliberately wrong-but-plausible answer and confirm it fails.
|
||||||
|
|
||||||
|
- **Cheat-resistant.** How could a model satisfy the grader without solving the task - hard-coding the expected output, reading the answer key, special-casing on test names, an empty string a lenient regex accepts, a degenerate policy that technically optimises the metric, injecting instructions into the judge's input? Models under optimisation pressure find these. Close them off.
|
||||||
|
|
||||||
|
- **Ground truth not reachable by the model under test.** Not in a file in the sandbox, a checked-out repo, leftover commit history, a grader prompt it can see, or the open web if it has search. This has to be structural; "don't look" in a prompt is not a defence.
|
||||||
|
|
||||||
|
- **Spot-check the failures.** Read a handful of outputs the grader marked wrong. If more than roughly one in ten look like grader errors, fix the grader before any full pass - otherwise you are partly measuring which variant matches the grader's blind spots.
|
||||||
|
|
||||||
|
- **Deterministic, or with measured variance.** Run the grader on the same output twice. If the result changes, there is grader variance on top of model variance; measure and report it.
|
||||||
|
|
||||||
|
- **Atomic checks over holistic scores.** Score independent properties as separate metrics (`{correct, formatted, concise}`) rather than one blended number - more reproducible, easier to calibrate, and diagnostic. Prefer a separate judge call per property.
|
||||||
|
|
||||||
|
- **Aggregation matches the question.** Mean is right for typical-case quality; for rare high-stakes behaviours (data deletion, irreversible actions), fail-on-any or worst-case reflects what matters better than a mean diluted by easy cases.
|
||||||
|
|
||||||
|
- **Partial credit and penalties don't make a degenerate policy optimal.** If penalties for trying and stumbling outweigh the reward for succeeding, "do nothing" wins.
|
||||||
|
|
||||||
|
- **Handles large outputs.** The grader must not truncate, time out, or crash on the longest output a model might produce; a grader crash is `status: error`, not a model failure.
|
||||||
|
|
||||||
|
### When the grader is an LLM judge
|
||||||
|
|
||||||
|
- **Position bias.** In pairwise comparison, randomise A/B per case (or score both orders and average).
|
||||||
|
- **Verbosity bias.** Tell the judge not to reward length for its own sake, or judges reliably prefer longer answers.
|
||||||
|
- **Self-preference.** A judge from the same family as a model under test tends to prefer outputs that resemble its own; avoid the exact model under test as its own judge, and consider a different family or a small jury for close calls.
|
||||||
|
- **Label deference.** Don't tell the judge which response is the "reference", "baseline", or "human" one.
|
||||||
|
- **Concrete rubric, not vibes.** Specific checkable properties, not "which is better?"; treat candidate text as untrusted data, not instructions; use structured output so the parse is deterministic.
|
||||||
|
- **Calibrated against human labels.** Validate the judge on a few dozen cases a human labelled independently and report agreement. Well below ~90% on clear-cut cases means the judge prompt needs another iteration before its scores can steer changes - and this number is what lets a cautious owner trust a judge-graded taste metric at all.
|
||||||
|
- **Tested on known negatives.** Feed the judge an empty string, "I don't know", and a confident answer to the wrong question; confirm it fails all three.
|
||||||
|
|
||||||
|
## 5. Can it detect the change you're after?
|
||||||
|
|
||||||
|
An eval can be correct on every item above and still be useless for the decision at hand because it lacks the resolution to see the effect. Check this *before* the first full pass and again before round 1 of a hillclimb - discovering it after several paid rounds is the expensive way.
|
||||||
|
|
||||||
|
- **Noise floor vs headroom vs the smallest change worth acting on.** From the baseline run at its actual rep count, compute the noise floor on the target metric - the half-width of the paired-difference 95% CI at the current n × R (for a pass-rate, roughly `1/sqrt(n·R)`: 25 cases × 2 reps ~ ±14 points, 100 × 2 ~ ±7). Put it next to the **headroom** (ceiling minus baseline) and the **smallest improvement the user would actually ship on**. If the noise floor exceeds either, say so plainly now, with the numbers, and offer the levers in order of cost: more reps (cheapest, and paired designs make them go further), more cases, a pairwise or continuous metric instead of a binary one, or trimming to discriminating cases for iteration with a full-set confirm at the end. Cases and reps are two knobs on the same dial; budget them together when the set is sized, not after.
|
||||||
|
|
||||||
|
- **Train and test are the same population.** If the eval will be hillclimbed with a split, the split must be drawn at random (stratified by `tags[0]`), never by baseline score. A train slice hand-picked from the worst-scoring cases guarantees two things: the analyzer only ever sees pathological cases, so its fixes target the tail rather than the population; and selecting on low baseline scores buys regression to the mean - those cases "improve" on re-run by chance alone. The symptom is a healthy train gain with a flat held-out set. Check at baseline that train and test means agree within noise; if they don't, re-draw before round 1. The analyzer can still *focus* on failures within train.
|
||||||
|
|
||||||
|
- **The mechanism is wired.** Whatever the score is supposed to depend on - a tool, a memory store, an instruction file - disable it and confirm the score drops; enable it and confirm it engages in the transcripts. If the score barely moves either way, the eval isn't measuring the lever you plan to pull.
|
||||||
|
|
||||||
|
- **The headline recomputes from raw rows.** Recompute the number you will report from per-case `grade` values yourself; don't trust an aggregate field. Mean-vs-sum and per-rep-vs-per-case mixups produce phantom breakthroughs.
|
||||||
|
|
||||||
|
## 6. Reporting findings to the user
|
||||||
|
|
||||||
|
The checks above are directives to you; the report you hand the human should not read as one. The person who built the eval almost always has context you lack - a constraint, a deadline, a deliberate trade-off - and the purpose is to surface things worth a second look, not to grade their work.
|
||||||
|
|
||||||
|
- **Frame findings as observations and suggestions.** "Something worth looking at is...", "you might consider...", "one thing that can cause trouble here is..." over "this is wrong." State what you observed, why it might matter, and one concrete change, then let the user decide.
|
||||||
|
- **Distinguish severity.** Lead with things likely to make the numbers actively misleading - infra errors scored as failures, "no answer" conflated with "negative", reachable ground truth, gold derived from a model under comparison, a split selected by score, a noise floor larger than the effect sought, a non-deterministic judge - then things that add noise or limit generality without flipping conclusions.
|
||||||
|
- **Be specific and cite evidence.** The file, function, case ID, or transcript line. "Case 14's expected answer looks stale - the library changed its default in v3" is actionable; "some labels may be stale" is not.
|
||||||
|
- **Say when things are fine.** An audit that finds nothing wrong is a valid result. Don't manufacture concerns.
|
||||||
|
- **Don't be preachy or exhaustive.** Report the handful of things that matter for the decision the user is making; listing every deviation from an ideal buries them.
|
||||||
|
- **Offer to fix, not just flag.** Where a finding is a small change - add a `status` field, pin a seed, normalise before comparing, randomise A/B, re-draw the split - make it.
|
||||||
|
|
||||||
|
Two practices worth suggesting regardless of what the audit finds: treat the eval as a living suite (new production failure modes become cases, saturated items are hardened, the judge is re-calibrated when it drifts); and periodically have a strong model read the cases, rubric, and a few graded transcripts and ask where a reasonable person would disagree with the label - the tier-3 auditor is the scaled-up version of that.
|
||||||
335
skills/claude-api/shared/evals/eval-hillclimb.md
Normal file
335
skills/claude-api/shared/evals/eval-hillclimb.md
Normal file
@@ -0,0 +1,335 @@
|
|||||||
|
# Hill-Climbing on an Eval
|
||||||
|
|
||||||
|
> **If you arrived via `/claude-api hillclimb`:** this is the right file. Work through the steps in order - Steps 0 and 0.5 are hard prerequisites; Steps 1-2 feed the plan sign-off you need before the loop starts. Don't summarize this guide; execute it.
|
||||||
|
|
||||||
|
This guide is for iteratively improving a Claude-powered app against a fixed eval: run the eval, read the failures, change something in the codebase, run again, and repeat until the score stops moving or the budget runs out. It picks up where eval-building leaves off - the user has a way to measure; now they want to move a number: usually the quality score up, but just as often cost or latency down while quality holds.
|
||||||
|
|
||||||
|
The loop itself is simple. What makes it work or not is discipline: reading the actual transcripts rather than pattern-matching on summary stats, knowing which change produced which effect, keeping a clean record of what was tried, and not fooling yourself by tuning on the same cases you score on. **The number that matters at the end is the test-set delta versus the starting point** - improvement on the cases you read while iterating is not the result, it's the process. Those are the things this guide is opinionated about. Everything else - what to change, how many rounds to run, when to stop - is the user's call, and you should ask rather than assume.
|
||||||
|
|
||||||
|
Stay recommendation-forward - propose a concrete default with every question so the user can just say "yes" - and treat the plan sign-off at the end of Step 2 as the minimum approval you need before the loop starts. How often to check in during the loop is one of the Step 2 questions; don't ask it separately here.
|
||||||
|
|
||||||
|
> **Talking to the user.** These steps are your execution plan, not a script to narrate. Keep user-facing messages short and outcome-focused: what you ran, the score, what you'll try next, a path or link to open. Don't walk the user through which step you're on, which files you're writing, or internal bookkeeping unless they ask. One concise update per round is enough; put detail in `report.html` and `narrative.md`, not the chat. When you need a decision - what's in scope to change, which change to try next, whether to spend another round - use the `AskUserQuestion` tool rather than free-text prose: batch up to four related questions into one call, give each two to four concrete options with your recommendation listed first and labelled "(Recommended)", and don't add your own "Other" option - the tool appends a free-text one automatically. If `AskUserQuestion` isn't available (headless runs), fall back to one short question at a time.
|
||||||
|
|
||||||
|
> **Run the eval command in the background; keep the conversation free.** An eval run can take minutes to hours - don't make the user sit through it, but don't wrap it in a subagent either. Each round, do the quick parts yourself in the main session - apply the change, write `vN/change.*` - then launch the runner as **one `Bash` call with `run_in_background: true`** (the eval command itself, not an `Agent`). You'll get a completion notification when it exits; meanwhile stay available for the user's questions and, when useful, spawn the analyzer subagent (Step 4) - the only subagent this loop uses. When the runner finishes, **verify on disk before trusting the notification**: `vN/results.jsonl` should have N×R rows and `vN/summary.json` should exist; if rows are short, re-launch the same command (resume is idempotent at (case, rep), so it picks up where it stopped). Then regenerate `report.html` via the report builder (full or lite, per build-eval.md), tell the user the score and the path, and pick the next change - via `AskUserQuestion` if the Step 2 cadence has you checking in now, otherwise just state it and proceed. Before the first unattended round, show the user the exact runner command and ask them to allow it for the session, so a permission prompt can't stall a round nobody is watching. That approval covers the harness as it stands: the scaffold runner hashes itself plus `_state.json.harness_paths` and exits 2 when the hash differs from the one last recorded with `--approve-harness` - so a round that edits any harness path stops the next run until the user has seen the diff and said OK. Never pass `--approve-harness` from an unattended round; it is the user's to run. If you're running headless (`-p` / SDK) there's no conversation to keep free - run the eval in the foreground instead. When the user asks how a run is going, answer from the runner's own progress line (the scaffold prints `k/N done ... ~Ns left` every 30 s and mirrors it to `vN/progress.txt`) - one line, not a narration.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 0: Confirm there's a runnable eval
|
||||||
|
|
||||||
|
Ask the user:
|
||||||
|
|
||||||
|
> Do you have an eval script for this flow - something I can run from the command line that exercises the app against a fixed set of prompts and prints a score?
|
||||||
|
|
||||||
|
If yes, ask for the command and where it writes its per-case results. Also ask whether the runner retries failed cases - and if so, which attempt's grade, transcript, and usage land in the results; score strict per attempt (a case that passed only on retry is a fail unless the user decides otherwise) and make sure retry attempts show up in cost accounting rather than being silently absorbed. Make sure the eval measures the outcome you're trying to improve, not just a behavior you assume correlates with it. If you're using a behavioral proxy because the real outcome is too expensive to measure every round, say so up front and run the winner on the real eval once at the end. **Each eval run must capture, per case: the full transcript, `model`, `usage` (input/output/cache token counts), and the grade dict** - not just an aggregate score. The transcript and the score for a case must come from the *same* model call; don't re-run the model separately to collect a transcript and then grade a different sample. Search the user's codebase for an existing runner or wrapper for this eval that already persists those fields before building anything new. Run it once to confirm it works and see the output shape (or work from a recent results file if one's handy). Then **read `shared/evals/eval-audit.md` and run it against the eval** - cases, runner, grader - reporting per its §6; an eval that wasn't built by `build-eval` hasn't had these checks, and Step 0.5 below is the must-pass subset, not the whole list.
|
||||||
|
|
||||||
|
If no, **stop here**. Hill-climbing without an eval is just editing and hoping. Route the user to `/claude-api build-eval` (read `shared/evals/build-eval.md` and run that flow), and come back when there's a script and a baseline number.
|
||||||
|
|
||||||
|
If the reason for hill-climbing is a model migration - the user wants to move to a newer Claude model and tune their prompts for it - read `shared/model-migration.md` alongside this guide so your proposed changes account for the new model's breaking changes and behavioral shifts.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 0.5: Prove the eval can be climbed
|
||||||
|
|
||||||
|
A runnable eval (Step 0) is not yet a *trustworthy* one. Before you spend a round, rule out the possibility that the harness is lying to you - a hill-climb on a broken measurement is worse than none, because you'll "improve" an artifact, declare victory, and ship nothing. `eval-audit.md` (loaded in Step 0, or by `build-eval` if that's how the eval was made) is the full checklist; the checks below are the ones that must pass before round 1, each of which has silently wrecked a run:
|
||||||
|
|
||||||
|
- **Prove the eval can detect the win you're after.** From the baseline at its actual rep count, put three numbers in front of the user: the **noise floor** on the Step 1 target (paired-difference CI half-width at the current n × R - `eval-audit.md` §5 has the arithmetic), the **headroom** (ceiling minus baseline), and the **smallest improvement they'd act on**. If the noise floor is bigger than either, the loop cannot show a real in-scope win no matter how good the changes are - say so now, not after five rounds, and offer more reps, more cases, or a finer-grained metric before starting.
|
||||||
|
- **Prove the mechanism is actually wired.** Whatever the score depends on - a memory store the agent writes to, a tool it should call, a file it should read - run a one-off probe that it takes effect end-to-end before you trust any score: write a value and read it back through the same path the eval uses, or confirm the tool actually shows up in the agent's tool list. If the eval comes back as though the mechanism does nothing, check the wiring before concluding "the model can't do this."
|
||||||
|
- **Recompute the headline number from raw per-case results.** Don't trust an aggregate field in a manifest - recompute the number you'll report from the per-instance values in `results.jsonl` yourself. Mean-vs-sum and similar aggregation mixups produce spectacular phantom results that look exactly like a breakthrough until you hand-check them. A too-good-to-be-true number is a measurement bug until a manual cross-check says otherwise; make the cross-check a step, not a lucky catch.
|
||||||
|
- **Spot-check the grading on the baseline failures.** For a handful of the lowest-scoring baseline cases, read the model's actual output, the judge's reasoning, and the expected value: did the judge grade fairly, and is the ground truth correct? A wrong rubric or wrong expected value will send every round chasing a harness fix for a measurement error. If you find one, fix the rubric/GT and re-grade the baseline in place (re-run the judge on the stored transcripts - no model re-run needed) before round 1. While you're there, triage *every* zero-scoring baseline case: classify each as harness error vs. grader verdict (read the per-case error field or errors sidecar, wherever the runner records failures), and exclude the harness-error cases from the scored denominator before round 1. Spot-check the graders your gates depend on: confirm each reads the artifact the agent actually writes, and that nothing outside the fixture can flip it (host repo state, pre-seeded files, wall clock) - a grader that escapes its fixture measures the environment, not the agent.
|
||||||
|
- **Verify what served the requests and how the runner retries.** Run one smoke case and read `model` from the *response*, not your config - silent server-side substitution invalidates every comparison - and confirm request retries back off with jitter and are counted, not absorbed. `runner-scaffold.mjs` asserts both by default; a user-supplied runner needs the check (`eval-audit.md` §2-3).
|
||||||
|
|
||||||
|
- **If the artifact you score is generated from the artifact you tune, measure its build variance first.** Some flows put a stochastic generation step between the lever and the score: the prompt you're iterating on *builds* something - a memory store, a retrieval index, a synthesized corpus - and the eval then scores reads against the built thing. When that build runs once per variant and every rep reads the same build, reps and their CIs measure only the noise of scoring a fixed build; the build's own run-to-run variance is sampled once per variant, invisible to every gate, and can be the larger term. Before round 1, rebuild the baseline artifact two or three times with the prompt *unchanged* and score each build the same way: the spread across those no-change rebuilds is the floor a one-edit effect has to clear. In one climb, three builds of the same prompt spanned ~7 points against rescore noise near ±1.4 on the train mean - every edit had been compared against a single baseline build, and the loop could not tell any of them from the default. If the build spread exceeds a plausible one-edit effect, build K times per variant and compare build-pooled means, or move the lever closer to the score; adding reps over one build can't see it.
|
||||||
|
|
||||||
|
If the flow spawns subagents, also confirm the parameters you're iterating on - model, effort, prompt - actually reach every subagent and that traces capture their turns; a knob that silently doesn't propagate makes every round on it a no-op.
|
||||||
|
|
||||||
|
If you have a choice of which eval or slice to climb on, **pick the one with the most signal per token**:
|
||||||
|
|
||||||
|
- **The mechanism must actually drive the score** - disable it and re-run; if the score barely drops, the eval isn't measuring what you're tuning, and no amount of tuning will show up.
|
||||||
|
- **Low run-to-run variance at small rep counts** - if the baseline's per-rep scores swing widely, a "win" is indistinguishable from variance. Raise reps or pick a calmer slice rather than chasing noise.
|
||||||
|
- **An inspectable mechanism** - prefer an eval where you can *see why* a variant won (an artifact it wrote and reused, a tool-call trace) over a black-box delta you can't attribute and that may not generalize.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 1: Agree on the goal, what to change, and how it's wired in
|
||||||
|
|
||||||
|
**First, the goal.** "Make the number go up" is only one of the things a hillclimb is for, and the loop behaves differently for each - so always ask before anything else, via `AskUserQuestion`, listing the metrics and perf fields the eval actually records:
|
||||||
|
|
||||||
|
> What should this hillclimb optimize?
|
||||||
|
> - **Raise `<headline metric>`** (Recommended when the eval is new and the score has obvious room)
|
||||||
|
> - **Cut cost per request** - hold `<headline metric>` within noise of baseline
|
||||||
|
> - **Cut latency** - hold `<headline metric>` within noise of baseline
|
||||||
|
> - **Move to `<other model>`** and recover `<headline metric>` on it
|
||||||
|
|
||||||
|
The answer sets three things for the rest of the loop: the **primary target** the analyzer is pointed at each round (Step 4), the metric the **stopping condition** is phrased against (Step 2), and the **guardrails** - every other recorded metric becomes a must-not-regress-outside-noise constraint rather than something to improve. If the goal is cost or latency, make sure `cost_usd` / `latency_s` is in `_state.json`'s `perf_fields` whether or not it was picked as a display column in build-eval - the goal forces the column. Record the goal in `_state.json` (e.g. `"approve_each_round": false,
|
||||||
|
"goal": {"target": "cost_usd", "direction": "lower", "hold": ["accuracy"]}`) so a resumed session doesn't silently revert to climbing the score.
|
||||||
|
|
||||||
|
Then ask which part of the app is on the table:
|
||||||
|
|
||||||
|
> What do you want me to iterate on? For example:
|
||||||
|
> - The system prompt
|
||||||
|
> - A specific skill or instruction file the agent reads
|
||||||
|
> - Tool descriptions
|
||||||
|
> - Model choice or API parameters (`effort`, `thinking`, `max_tokens`)
|
||||||
|
> - The agent loop / harness code itself
|
||||||
|
> - All of the above - whatever moves the target
|
||||||
|
>
|
||||||
|
> And is there anything that's off-limits - parts of the prompt or code I should leave alone even if I think changing them would help?
|
||||||
|
|
||||||
|
Record the answer. This defines what you'll be editing each round; the off-limits list is a hard constraint. Also have the user name the **harness paths** - the runner script, grader, and any file the eval command executes - and record them in `_state.json.harness_paths` (repo-relative); the runner refuses to start when any of them changed since the user last ran it with `--approve-harness`, which is what keeps a harness edit from executing unreviewed in an unattended round. If the user says "whatever moves it," that's fine - but still ask about off-limits, because there's almost always something (a compliance disclaimer, a tone requirement, a tool that's contractually required). For a cost or latency goal, model choice and API parameters (`effort`, `max_tokens`, caching) are usually the biggest levers - make sure they're explicitly in or out.
|
||||||
|
|
||||||
|
If the target is a skill or instruction file, confirm **how it reaches the model during the eval**: is it appended directly into the system prompt (which isolates "is the content good?"), or loaded through the app's real skill-discovery path (which also tests "does the model find and use it?")? Both are valid and they measure different things - ask which one the user wants, and make sure the eval runner matches.
|
||||||
|
|
||||||
|
Two things you can choose freely unless the user objects: the model that *reads transcripts and proposes changes* doesn't have to be the model under test - using a stronger model for diagnosis is often worth it - and the proposed changes don't have to be prose. If a concrete helper script, a code snippet, or a worked example would guide the model better than another paragraph of instructions, write that instead.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 2: Agree on a stopping condition (and a budget, if cost matters)
|
||||||
|
|
||||||
|
Ask via `AskUserQuestion` how many rounds to run before checking back in:
|
||||||
|
|
||||||
|
> One pass over the full set is N cases × R reps on `<model>`, roughly ~Y minutes. How many rounds before I check back in?
|
||||||
|
> - **Until plateau (Recommended):** keep going until the Step 1 target improves by less than delta for K consecutive rounds (K >= 3 - two flat rounds is too few to call a plateau), or a guardrail metric regresses outside noise, then report.
|
||||||
|
> - **One round at a time:** propose, run, report, ask again. Pick this to steer each change.
|
||||||
|
> - **N rounds:** run N, report, ask whether to continue. (User types N.)
|
||||||
|
|
||||||
|
This is both the stopping condition and the check-in cadence - the loop runs autonomously between check-ins.
|
||||||
|
|
||||||
|
Set delta above the noise floor from Step 0.5 - a stopping threshold finer than the eval can resolve never fires honestly.
|
||||||
|
|
||||||
|
**If reducing cost is itself the Step 1 goal** - not just a ceiling on this loop - read `shared/evals/cost-hillclimb.md` before planning rounds: it narrows this guide's loop to the cost objective, with a lever search order (caching health -> prompt audit -> a model × effort staircase walk -> prompt climb on the frozen model -> a down-left re-probe -> a registered joint confirm), pre-registered adoption gates, and cost-specific stopping rules. (`shared/cost-optimization.md` is the no-eval checklist for the same goal; inside this loop, follow `cost-hillclimb.md`.)
|
||||||
|
|
||||||
|
**If the user asks what the loop will cost or gives you a budget**, also present the **total loop cost** - baseline plus every planned round - and get a ceiling. Estimate it from real numbers, don't guess:
|
||||||
|
|
||||||
|
1. From a recent results file (or a small sample run if none exists), sum the `usage` fields across all cases, including judge calls if model-graded.
|
||||||
|
2. Multiply by the per-token prices for the user's provider - the Current Models table in `SKILL.md` is first-party; ask or look up if they're on Bedrock/Vertex/etc. Cached reads are ~10× cheaper than base input. This gives the cost of one pass at one rep.
|
||||||
|
3. Measure wall-clock for that pass - time a real run end-to-end and scale; don't estimate.
|
||||||
|
4. Add a rough allowance for the per-round analysis turns - typically small relative to the eval itself.
|
||||||
|
|
||||||
|
Present `(N + 1) × R × $X` and ask what total spend they're comfortable with. If they hesitate, offer the levers: fewer rounds, fewer reps, a cheaper judge model, or trim to the discriminating cases (rank by cross-rep variance from the baseline run, keep the top K, then run the full set on baseline + winner at the end to confirm). Whatever they pick, the default inside the loop is still to run the **same** set every round; never silently subset it to fit. **The N, R, and case count you present must be what you actually run** - if reps/split later push the total above the approved ceiling, mention it before proceeding.
|
||||||
|
|
||||||
|
When the goal is cost and the candidate change is prompt text, price the instruction itself first - its per-request input tokens × requests per case, against the predicted saving; some candidates disqualify on paper before you spend a round.
|
||||||
|
|
||||||
|
### Get the plan approved
|
||||||
|
|
||||||
|
Before you touch any files, confirm the plan with the user and get a clear yes. Two pieces:
|
||||||
|
|
||||||
|
- **A scope table** - two columns, "will change" and "won't touch," populated from Step 1. The user should be able to glance at it and know exactly which files and knobs are in play.
|
||||||
|
- **Who applies changes** - by default you apply each round's change and the user reviews the result; offer the alternative of **showing each round's diff for a yes/no before it runs** (recommend it when the artifact is customer-facing copy, legal/medical/regulated content, or anything the user said a human must own). Record the choice as `_state.json.approve_each_round`.
|
||||||
|
- **A short approach paragraph** - how you intend to run the loop. For example: *"Each round I'll have a fresh analyzer read the train traces and propose one change; I'll apply it, rerun the full set, and post a status table. Early rounds I'll steer toward different levers (tool descriptions, system-prompt wording, `effort`) to find where the headroom is. Running 8 rounds max."*
|
||||||
|
|
||||||
|
Don't make the user ask for this; produce it by default. It's what lets them trust the loop enough to let it run without checking in every twenty minutes.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 3: Set up state, split the data, and take a baseline
|
||||||
|
|
||||||
|
The loop will run for multiple rounds, possibly across multiple sessions. Keep state on disk so it survives interruption and so the user can see the history. If the user already has a results directory and file layout from a prior eval, **keep theirs** - what matters is that each run produces the per-case data from Step 0 (full transcript, `model`, `usage`, grade dict, all from the same model call); the layout below is the default when starting fresh. Otherwise, create a working directory - `.claude/hillclimb/<flow-name>/` is a reasonable default, but put it wherever fits their repo - with this layout. **The report generator reads this tree directly**, so the file names and field names below are an exact contract, not a suggestion:
|
||||||
|
|
||||||
|
```
|
||||||
|
.claude/hillclimb/<flow>/
|
||||||
|
_state.json # loop state + report config - shape below
|
||||||
|
metrics.md # free-text rubric (markdown) - what each metric means; the full viewer renders it
|
||||||
|
narrative.md # model-authored running exec summary - rewritten after every round; final version in Step 5
|
||||||
|
trajectory/
|
||||||
|
scores.tsv # derived by the report builder (full or lite): per-case mean of the primary metric, one column per round
|
||||||
|
baseline/
|
||||||
|
results.jsonl # one JSON object per (case, rep) - shape below
|
||||||
|
summary.json # per-variant header - shape below
|
||||||
|
traces/
|
||||||
|
<id>_rep<k>.json # full transcript, one file per rep (train split only)
|
||||||
|
v1/
|
||||||
|
change.md # what changed this round and why (from the analyzer)
|
||||||
|
change.patch # the actual diff applied to the codebase
|
||||||
|
results.jsonl summary.json traces/<id>_rep<k>.json
|
||||||
|
v2/
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
**`_state.json`** - everything here is optional except the split ids; `metrics` and `perf_fields` let you override what the report infers from the data. `best.round` is 0-indexed (0 = baseline). If the eval has multiple metrics, **the first `binary`-kind metric (else `metrics[0]`) is the report's headline** - order the list accordingly. `goal` records the Step 1 answer - the metric or perf field the loop is optimizing, its direction, and the metrics it must hold - so `best` is picked against the goal, not blindly against the headline:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "current_round": 2, "reps": 2,
|
||||||
|
"goal": {"target": "pass", "direction": "higher", "hold": ["cost_usd"]},
|
||||||
|
"approve_each_round": false,
|
||||||
|
"best": {"round": 1, "test_score": 0.70},
|
||||||
|
"train_ids": ["case_01", ...], "test_ids": [...],
|
||||||
|
"harness_paths": ["eval/run-eval.mjs", "eval/grade.mjs"],
|
||||||
|
"harness_sha": "...written by the runner on --approve-harness; never edit by hand...",
|
||||||
|
"metrics": [
|
||||||
|
{"id": "pass", "kind": "binary", "label": "Pass"},
|
||||||
|
{"id": "quality", "kind": "judge"},
|
||||||
|
{"id": "verbosity", "kind": "float", "better": "lower"}
|
||||||
|
],
|
||||||
|
"perf_fields": [
|
||||||
|
{"id": "cost_usd", "label": "Cost", "unit": "$"},
|
||||||
|
{"id": "latency_s", "label": "Latency", "unit": "s"}
|
||||||
|
],
|
||||||
|
"prices": { "my-custom-model": {"in": 2.0, "out": 8.0} } }
|
||||||
|
```
|
||||||
|
|
||||||
|
**`results.jsonl`** - one line per case per rep, **appended as each case completes** so a crash doesn't lose finished work. `grade` can be a bool, a number, or a `{metric_id: number}` dict; `explanation` is an optional `{metric_id: "judge reasoning"}` sibling for judge-kind metrics. Put the full prompt text in `prompt` (the report shows it). `tags` is ordered - `tags[0]` is the primary grouping key. Record `model` from the response, not from config - `cost_usd` is derived from each row's `model` × `usage` (plus `judge_model` × `judge_usage` when present), so a model swap can't carry a stale rate and the runner doesn't compute cost at all. The full viewer does that derivation when it is on disk; otherwise compute `cost_usd` per row yourself when you report, with the recipe in build-eval.md § Before the first paid call (the "If the user asks what this will cost" bullets: Current Models prices in `SKILL.md`; cache writes at 1.25× input, cache reads at 0.1× input) - that is where the status table's `$/run` and `spend` come from. The adapter is forgiving on input: `prompt_id` may also be spelled `id` or `case_id`, and if `_state.json` omits `metrics` they're inferred from the union of grade keys. Perf keys are read by exact name:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "prompt_id": "case_17", "rep": 0, "prompt": "...full prompt text...",
|
||||||
|
"tags": ["topic-a", "hard"],
|
||||||
|
"grade": {"pass": 1, "quality": 7.2, "verbosity": 3.0},
|
||||||
|
"explanation": {"quality": "Cites two sources; balanced."},
|
||||||
|
"model": "claude-opus-5",
|
||||||
|
"latency_s": 12.4,
|
||||||
|
"tool_calls": 2, "web_searches": 1,
|
||||||
|
"usage": {"input_tokens": 1200, "output_tokens": 480} }
|
||||||
|
```
|
||||||
|
|
||||||
|
Two more optional per-row keys the report understands: `attachments` (a list of `{kind: "image"|"file"|"url", ref, alt?}` shown alongside the prompt) and `meta` (an arbitrary dict surfaced in the transcript header).
|
||||||
|
|
||||||
|
**`summary.json`** - per-variant header for the report, not aggregate stats (the report recomputes those from `results.jsonl`). All optional; `target` is one of `"system_prompt" | "skill" | "tools" | "code"`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "description": "Enable web_search tool",
|
||||||
|
"target": "system_prompt",
|
||||||
|
"suspicious": "val lift not replicated on a second seed" }
|
||||||
|
```
|
||||||
|
|
||||||
|
**`traces/<id>_rep<k>.json`** - the verbatim conversation as a JSON list of `{role, content, thinking?, name?}` turns where `role` is `system | user | assistant | tool_call | tool_result`.
|
||||||
|
|
||||||
|
The `traces/` directories are what the analyzer reads between rounds. Keeping them per-round with one file per rep means that by round 3 the analyzer can diff `baseline/traces/case_17_rep0.json` against `v2/traces/case_17_rep0.json` and see exactly what behavior changed. `trajectory/scores.tsv` is the at-a-glance cross-round view: one row per case, one column per round, cell = that case's mean primary-metric score - derived by the report builder (full or lite, identically) from the `results.jsonl` files, so the runner doesn't write it and it can't drift.
|
||||||
|
|
||||||
|
**Make artifacts visible.** If the flow consumes or produces visual or structured artifacts - input images or PDFs, computer-use screenshots, generated HTML/SVG/plots, files the model wrote - make sure a human reviewing a case can actually see them, not just a filename - rendered in the Transcripts tab with the full viewer, opened from the referenced path otherwise. The full viewer has prebuilt slots for this; the runner just fills them:
|
||||||
|
|
||||||
|
- **Input artifacts** - on the `results.jsonl` row: `"attachments": [{"kind":"pdf","ref":"baseline/inputs/case_3.pdf","alt":"source doc"}]`. Renders above the first user turn.
|
||||||
|
- **Output artifacts** - on the trace turn that produced them: `{"role":"assistant","content":"...","attachments":[{"kind":"html","ref":"v2/out/case_3.html"}]}`. Renders below that turn. Write the artifact to disk under the variant dir and `ref` it relative to the flow root.
|
||||||
|
- **Rich content in the response text** - fenced ` ```html `, ` ```svg `, ` ```json ` blocks in an assistant turn's `content` get a "> Render" toggle automatically; nothing extra to write.
|
||||||
|
|
||||||
|
The full viewer renders `image`/`svg` inline, `html` in a sandboxed scrollable iframe, `pdf` in the browser's native viewer, `json`/`text` in a `<pre>` - each with a Hide/Show toggle. Anything else (`file`: docx, pptx, ...) shows as a download chip. Paths under ~2 MB are inlined into `report.html`; larger ones stay as download links so the report doesn't balloon. **One slot per artifact**: when a turn has `attachments`, the viewer suppresses its inline-render toggle for fenced blocks in that turn's text - so put the output in `attachments` once and the response text stays plain source. The lite report renders none of this - it links each trace file, and the analyzer and the user open the `ref`'d files directly - so keep every `ref` relative to the flow root either way. If a flow needs something the prebuilt viewer doesn't cover, edit `report/frontend/atoms.jsx` (`ArtifactView`) and rebuild via `frontend/scripts/build.sh` (EAP install only - the CLI doesn't extract the frontend).
|
||||||
|
|
||||||
|
**Split the prompt set so the analyzer can't overfit to the number you report.** The analyzer reads transcripts to propose changes - it will, by design, fix the specific cases it sees. The score you report must come from cases it never read. How you carve that depends on how many cases you have; pick the lightest structure that gives a held-out number you can trust:
|
||||||
|
|
||||||
|
- **Default - train / test.** *Train* is the set whose transcripts the analyzer reads each round. *Test* is everything else: scored every round alongside train, never opened by the analyzer; its score picks the winning round and is the headline. **Draw the split at random, stratified by `tags[0]` - never by baseline score.** Train needs enough failures to show a pattern (a handful to a couple dozen), but get them by making train big enough, not by hand-picking the worst cases: a train slice selected for low scores means the analyzer only ever sees pathological cases and tunes for the tail, and those cases regress toward the mean on re-run anyway - a healthy train gain with a flat test set is the signature. After the baseline, check that train and test means agree within noise; if they don't, re-draw before round 1. The analyzer can still *focus* on the failures within train.
|
||||||
|
- **Small set, or a cross-case metric** (pairwise ordering, ranking - anything that fragments inside a slice). Don't split. Score the whole set every round, lean on **reps** to tighten the noise, and have the analyzer read a few targeted failure transcripts rather than a fixed slice. Label per-round scores in the report as **directional**: an improvement that holds across reps is real signal, but with no held-out set the headline is an iterate-on number, not a publish number.
|
||||||
|
- **Large set** (~150+ cases) where you want a final number untouched by round selection: optionally carve a third *validation* slice - scored each round to pick the winner - and hold *test* back until the end. For most evals the extra bookkeeping isn't worth it.
|
||||||
|
|
||||||
|
Be honest with the user about what their split can and can't tell them. For a binary pass-rate the 95% CI half-width is roughly `1/sqrt(n·reps)` - 25 test cases at 2 reps is about ±14 points, 50 at 2 reps about ±10 - so show that number for their set and let them choose; reps and test-size are two knobs on the same dial. Whatever they pick, record the IDs in `_state.json` exactly as they appear in `baseline/results.jsonl`'s `prompt_id` (a runner that sanitizes ids for file paths keys its rows on the sanitized form), fix the split once, and don't change it.
|
||||||
|
|
||||||
|
**Reps per prompt** is the other knob. Model outputs vary run-to-run, and repeating each prompt tightens the estimate - especially worth it on a small set, or whenever the Step 2 budget has room. Offer it and let the user pick the count; if they choose more than one, record results as "k of N reps passed" rather than a single pass/fail. Don't default this silently in either direction. Reps tighten only the noise they re-sample - a runner that reuses a once-built generated artifact across reps leaves its build variance untouched (see the Step 0.5 rebuild check).
|
||||||
|
|
||||||
|
**Isolate ground truth from the model under test.** If the eval has reference answers, rubrics, or expected outputs, make sure they are **not reachable from the model's context** - not in its system prompt, not in a tool result it can read, not in a file its code-execution or bash tool can open, not in a fixture its container mounts. Keep them in the grader only. This has to be structural; "don't look at the answers" in a prompt is not a defense, and an agent under optimization pressure will eventually find a `cat evals.json` that wins the game without playing it. If the user's existing eval stores prompts and answers in the same file, split it before the first round. And if the eval derives from a public benchmark and the agent has web or network tools, the answers are also reachable *through the internet* - public mirrors of the benchmark often include solutions. Screen every passing transcript for fetches of the benchmark's repo or solution mirrors (and consider blocking egress to them); treat a pass accompanied by a solution-hosting fetch as invalid, and don't assume any automated contamination check will catch it.
|
||||||
|
|
||||||
|
**Handling non-text payloads in traces.** Don't embed raw base64 or binary blobs in the trace text - they bloat the file and render as noise. Instead, write each image or binary payload to a sidecar file and put a markdown reference at the point in the turn where it appeared - `` for an image, a link for anything else - so the report shows a thumbnail and the analyzer can still open the real file. Only fall back to a bare placeholder like `<[binary: 12kB]>` when the payload genuinely isn't worth keeping.
|
||||||
|
|
||||||
|
**Baseline.** Run the unmodified app across **the full set** at the chosen rep count, and record it in `baseline/` and in `_state.json`. Record an environment fingerprint with it - repo commit, lockfile hash, local patches or stubs, disabled tools, model id - and re-verify the fingerprint before each round's run: a changed fingerprint means re-baseline, because the comparison is broken either way. If time or an environment change later separates the baseline from a round, score a no-change control alongside the candidate and gate against the control, not the stale baseline number - identical-code drift of a few points between measurement days is common; where a stochastic build sits between the lever and the score, the control must re-run the build, not just the scorer. The control re-run also estimates the same-environment flip rate for free; don't set a keep gate inside that noise floor (Step 2's threshold sizing). (If cost matters and the pinned reps/split push the total above the Step 2 ceiling, mention it before this run.) You can run the report builder (full or lite - Step 4 has the invocation) on the flow directory now if you want a look: with only a single variant on disk (just `baseline/`, or no `_state.json` yet) the full viewer shows only the Evals and Transcripts tabs - the Summary tab auto-hides until there's a second variant to compare.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 4: The loop
|
||||||
|
|
||||||
|
Each round is: **analyze -> apply -> run -> record**. Two rules are non-negotiable throughout: only the train split's transcripts are ever read, and neither the eval set nor the budget changes without going back to the user.
|
||||||
|
|
||||||
|
**Analyze.** If the next change is already clear - the user named a specific fix, or the last round's result points straight at one - skip the analyzer and write `vN/change.md` directly. Otherwise spawn **one fresh analyzer subagent** (the Claude Code Task tool) and give it: the previous round's `traces/` directory (train-split transcripts only), the **train rows of `results.jsonl`** so it sees every metric's per-case score, the **train rows of `trajectory/scores.tsv`** so it sees how each case has moved across every prior round, the current version of the artifact being iterated on, the scope and off-limits list from Step 1, and **which metric this round is targeting** - on round 1 that's the Step 1 goal, along with the guardrail metrics it must hold. The analyzer scans the scores to pick which transcripts to read, reads however it likes - sort by the target metric, diff low vs high scorers, correlate across metrics, spot cases stuck flat across rounds - and returns a proposed change with a short rationale that cites the specific traces motivating it. Save that rationale to `vN/change.md`. A fresh subagent each round keeps the outer session from accumulating transcript content in its own context.
|
||||||
|
|
||||||
|
The outer session **does not read transcripts itself** - for choosing changes it sees scores only. That separation is the data-isolation guarantee: nothing from the held-out test set can leak into a proposed change, because the thing proposing changes never sees anything but train.
|
||||||
|
|
||||||
|
Two steers to pass the analyzer. First, **generalize, don't memorize**: the change should describe the failure *behavior*, not the failure *content* - pasting specific nouns or phrases from train cases into the prompt is the fastest route to an overfit change that helps train and does nothing held-out. Second, transcripts show what a block makes the model *do*, not what it prevents or enables without visible action - when proposing to remove something, name which cases you expect to regress, not just which recover. Third, it's fine - especially early on - for the analyzer to propose trying a different lever entirely (a tool description, an API parameter) rather than another wording of the same sentence; exploring where the headroom is can be worth a round.
|
||||||
|
|
||||||
|
A sketch of the analyzer's prompt:
|
||||||
|
|
||||||
|
> Here is the current `<artifact>` we are iterating on. Below are the train-split rows from `results.jsonl` (each case's full `grade` dict) and the corresponding transcripts. **This round's target is `<metric>` (`<higher|lower>` is better); `<guardrail metrics>` must not regress.** The off-limits list is: `<...>`. Find the cases doing worst on `<metric>`, plus a couple doing best for contrast; name the single behavior that most often costs it, and propose **one** concrete change to the artifact as a unified diff. For every trace you cite as evidence, **quote the relevant lines verbatim** and append its trace file path (`<vN>/traces/<case_id>_rep<k>.json`) - and, if `report.html` was built by the full viewer, the deep link `report.html#tab=transcript&ex=<case_id>&cmp=<vN>&rrep=<k>` - so the user can open that exact rep with one click. Do not reference test cases.
|
||||||
|
|
||||||
|
When reading `trajectory/scores.tsv` to pick focus cases, filter to **train rows only** - feeding test-row movement back into the change proposal is a leak of the held-out signal.
|
||||||
|
|
||||||
|
**Apply.** (If `approve_each_round` is set, show the diff and one-line rationale and wait for a yes before running; a no counts as a reverted round with the user's reason recorded in `change.md`.) Before applying, do a **de-fluff pass** on the proposed change: cut anything that's a platitude, a restatement of default behavior, or advice with no operational content ("be careful," "think step by step"). Do this every round - fluff accumulates one reasonable-sounding sentence at a time. Then edit the actual files in the user's codebase and save the diff to `vN/change.patch` so it can be reverted cleanly (for a brand-new artifact with no prior version, diff against `/dev/null`). That patch is the round's record of what changed (and what the full viewer's diff drawer renders - click a variant row in Summary), so cut it against the user's real source paths - not a scratch copy under `.claude/hillclimb/` - so each hunk reads as an edit they can apply directly to their repo; if the loop is iterating on a temporary copy, diff the original file instead. Also snapshot the full post-change artifact - the system prompt, skill file, or whatever you're iterating on - to `vN/` (e.g., `vN/skill.md`) so each round is inspectable on its own without replaying patches. If the patch touches a path in `_state.json.harness_paths`, the next run will stop for `--approve-harness`: show the user the diff and wait for their OK rather than running the round unattended.
|
||||||
|
|
||||||
|
**Run.** Run the full eval - every case, at the chosen rep count. Running the entire set every round keeps every score in the history directly comparable. Keep the runner's concurrency maxed out (up to the rate limit) - the loop's cadence is gated on how fast each pass finishes - provided retries back off with jitter (Step 0.5); in a shared-quota environment, maxed-out concurrency with a hot retry loop converts someone else's burst into your zero-scores. Write per-case results to `vN/results.jsonl`, the aggregate to `vN/summary.json`, and the **train** transcripts to `vN/traces/<id>_rep<k>.json`. (`trajectory/scores.tsv` is regenerated by the report builder - full or lite - from those files; the runner doesn't write it.)
|
||||||
|
|
||||||
|
Two one-case gates before a round's full pass - each costs at most one case, against a pass that costs all of them:
|
||||||
|
|
||||||
|
- **Premise-probe config levers.** When the round's change is a config-surface lever (a model parameter, a tool config, `effort` - anything validated server-side at create or call time) rather than prompt content, run one case first and confirm the lever is accepted - and, where the response exposes it, echoed back. A loud validation error is the cheap outcome; the expensive one is a runner that degrades the config error into retries or scored zeros and runs the full set anyway.
|
||||||
|
- **Print the resolved scope.** Before the pass, have the runner print what it actually resolved - case count × reps × model × estimated cost - and compare it to the approved plan. A dry run that resolves a different case count than the plan is a stop, not a warning.
|
||||||
|
- **Canary before an unattended or expensive pass** - run one case and compare its error and latency profile to baseline's; if degraded, hold rather than burn the round.
|
||||||
|
|
||||||
|
Infra health per round - retries, timeouts, served-model mismatches - is in `errors.jsonl`; a round whose error profile differs grossly from baseline's is void-and-rerun, not a comparable data point.
|
||||||
|
|
||||||
|
**Record and report.** Update `_state.json` (round number, and `best` if this round's test score beats it). A number you'll report - including privately-authored held-out cases and their raw results - must land in the recorded `vN/` layout, never only in a run log. If the session or machine is ephemeral (a CI runner, a remote session), also copy each round's `vN/` to storage that survives it. Don't report a round's score until every case has landed - partial reads can show a sign that flips when the batch finishes; if you must report mid-run, flag it as `N/total`. After every round, write the status table (row layout below) at the top of `narrative.md` and keep it current - it is the per-round record, on disk even when the run is headless - then report in chat a one-line headline ("v3 test 0.71 -> 0.74, change: <one line>"). With the full viewer, follow the headline with a pointer to `report.html#tab=summary` instead of the table - the Summary tab is exactly this table, sortable and with the diff drawer one click away. With the lite report, which shows only the primary metric, paste the markdown table under the headline, since it is what carries the guardrail, perf, `$/run` and `spend` columns. `$/run` and `spend` come from `cost_usd` (Step 3: derived by the full viewer when it is on disk, otherwise computed by you from each row's `model` × `usage`). If tracking spend against a budget, cumulative spend is `sum(cost_usd)` over every `vN/results.jsonl`, plus the billed `usage` recorded on failed attempts in each variant's `errors.jsonl` sidecar (failed spend is still spend) - never a maintained counter. The row layout:
|
||||||
|
|
||||||
|
> | round | change (one line) | test | train | s/turn | out toks | tool calls | $/run | spend |
|
||||||
|
> |-------|----------------------|-------|-------|--------|---------------|--------------|----------------|--------|
|
||||||
|
> | 0 | baseline | 0.62 | 0.60 | 19.8 | 480 | 3.1 | $2.60 | 2.60 |
|
||||||
|
> | 1 | when-to-search rule | 0.70 | 0.73 | 19.5 | 492 (1.0×) | 4.2 (1.4×) (up) | $2.97 (1.1×) | 9.70 |
|
||||||
|
> | 2 | effort=medium | 0.68 | 0.71 | 11.2 | 310 (0.6×) (down) | 3.0 (1.0×) | $1.40 (0.5×) (down) | 12.90 |
|
||||||
|
>
|
||||||
|
> Best so far: round 1 (test 0.70). Next: combine round-1 rule with `effort=medium` and re-check latency.
|
||||||
|
|
||||||
|
After each round is scored, also **rewrite `narrative.md`** - a model-authored running exec summary of every harness change and its effect so far, not just this round's. Read all of the `vN/change.md` rationales and `vN/summary.json` results and write one short paragraph that says which variant is currently winning and *why*, in terms of the changes ("v4 has the best recall, but v3's prompt tightening traded a little recall for precision and nets the higher overall score"). Overwrite it wholesale each round - it's a snapshot of the story so far, not an append-only log. Keep the current status table above the paragraph. The full viewer's NARRATIVE panel renders this file, and without the full viewer `narrative.md` is the file to open - either way, keeping it current means the user (or a resumed session) can read the state of play at any point in one screen.
|
||||||
|
|
||||||
|
Alongside the status table, regenerate the **HTML report** so the user can drill in visually: run the report builder on `.claude/hillclimb/<flow>/` - `shared/evals/report/build-report.mjs` when it is on disk (EAP install), else `shared/evals/report/build-report-lite.mjs` (both paths relative to this skill's base directory), with `node` or `bun` (the selection line and the no-runtime fallback are in build-eval.md §Report builder). The full viewer writes a self-contained `report.html` into the flow directory (exec-summary table and trend charts, side-by-side transcript comparison, and the per-round diffs); the lite builder writes a summary table plus per-case rows with the primary metric per round and links to each trace file. Both write `trajectory/scores.tsv`. It reads the same `summary.json` / `results.jsonl` / `traces/` / `change.*` files you just wrote, so there is nothing extra to produce - run it **after the round's runner has exited**, not while it's still appending (the partial variant's row would show scores from however many cases have landed so far - the full viewer badges it as a partial `N/M cases` run, the lite report just shows the lower case count - don't publish either). **The report is there for when the user wants it, not news to deliver:** give its path once after the baseline and again in the final summary, end each round's status message with the path as a bare last line, and otherwise don't bring it up - no remarks on its size, its notes, or that they should open it - unless the build exits non-zero or they ask. **Re-apply the Step 0.5 spot-checks to the new round's row - in the status table and, with the full viewer, the Summary tab - before pointing the user at it**: every metric and perf column present, plausible, and consistent with this round's change - a `$0.00` cost, `0.0s` latency (or the `usage` / `latency_s` fields behind them missing from the rows), or a column that didn't move the way the change predicts is a runner bug, not a result. Also spot-check that one transcript renders as distinct turn cards rather than a single text blob (full viewer) or that a linked trace file is a JSON list of `{role, content}` turns (lite). The rest are full-viewer features: `build-report.mjs <flow> --check` flags the common trace-format mistakes without rendering; `build-report.mjs --index .claude/hillclimb/` writes an `index.html` linking every child flow's report when several flows run in parallel; and a run directory of a different shape takes a small adapter per `shared/evals/report/SCHEMA.md` - typically a few dozen lines: assemble `Turn[]` from your raw content blocks, compute `RepResult.perf` from `usage`, declare your metrics - handed to `render()` directly.
|
||||||
|
|
||||||
|
**Every metric that informs your recommendation must be on the record - on the rows, in the status table, in the report - before you make the call.** If, mid-loop, you compute a new metric in a scratch script and it changes which variant you'd pick, stop and fold it in: add it to the runner's grader so every row carries it, declare it in `_state.json` under `metrics`, re-grade the existing variants in place so the comparison is apples-to-apples, and rebuild the report and the status table - *then* recommend. The user must be able to verify every number behind your recommendation from the flow directory alone (`report.html`, `narrative.md`, the `vN/` files), without your chat history. For metrics that are inherently aggregates - inter-rep consistency, or anything else computed across cases rather than per-row - the same rule holds: put a per-variant comparison table in `metrics.md` so the record carries the comparison (the full viewer renders it), not just your prose description of it.
|
||||||
|
|
||||||
|
If the grader is a model-as-judge and the score jumps by more than the change could plausibly explain, **treat it as suspicious before treating it as good news**: spot-check a handful of outputs by hand, show the user, and confirm the judge isn't rewarding a surface pattern the change happened to introduce. Record the concern as a one-line `suspicious` string in that round's `summary.json` so the concern stays attached to the variant (the full viewer shows it as a warning badge). An LLM judge being gamed looks exactly like a breakthrough until you check.
|
||||||
|
|
||||||
|
**Separate "did the mechanism engage" from "did it help."** Track a leading indicator of the mechanism firing - how often the agent wrote to memory, called the tool, produced the artifact - as its own column, distinct from the score. It's the in-loop counterpart to the Step 0.5 wiring probe: the probe proved the mechanism *can* work; this proves it *did* this round. A score that moved while the engagement rate didn't is probably noise or a harness artifact - find out which before stacking another change on top.
|
||||||
|
|
||||||
|
If train went up and test didn't, the change overfit to the cases the analyzer read - revert it and try a different angle next round. If a round regresses on train too, revert before the next round rather than stacking changes on top of it. If train went *down* but test went *up*, treat it as noise at low rep counts - keep the change only if the pattern repeats on a second run. On ties, prefer the later round.
|
||||||
|
|
||||||
|
**Decide.** Check the stopping condition from Step 2. Treat the budget as a **guide, not a wall**: as you approach it with the score still climbing or an obvious idea untried, say so and offer to extend rather than stopping cold. Conversely, if several consecutive rounds haven't moved the score *outside noise* - point estimates drifting but intervals overlapping - you're likely at a plateau even though the numbers look like they're climbing: run Step 4.5's categorization before another content round. To tighten a variant's interval, append more reps to its `results.jsonl` (and baseline's, for a fair comparison) and rebuild - the report recomputes from whatever rows are there; no new round directory needed. Otherwise, once the Step 1 goal has plateaued, offer to change the target before stopping: pick the guardrail metric or perf field with the most headroom that hasn't been tried, and run another round with the analyzer pointed at it under the constraint of not regressing what's already won - but ask first, since the user set the goal and may consider it done. Only stop when no metric has obvious room, or report best-so-far and ask. If the user asked for check-ins and you've hit the interval, report and wait. Otherwise, loop.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 4.5: When the loop stalls, categorize before grinding
|
||||||
|
|
||||||
|
The analyze -> apply -> run loop assumes each failure is caused by the artifact you're tuning. Once the easy content gaps are filled, that stops being true - remaining failures increasingly come from the grader, the harness, the artifact's structure, or plain variance, and another content round can't move them. The tell is **two or three consecutive rounds where the test score hasn't cleared the noise band** despite changes that should have helped. When that happens, stop iterating content and spend one round categorizing instead.
|
||||||
|
|
||||||
|
Spawn a fresh analyzer subagent (same isolation as Step 4's Analyze) to bucket every remaining train-split failure by root cause, reading each transcript far enough to tell which:
|
||||||
|
|
||||||
|
| Bucket | Tell | What to do instead of another content round |
|
||||||
|
|---|---|---|
|
||||||
|
| **Artifact gap** | Model never had the fact it needed; transcript shows it guessing or searching | This is the loop's home turf - keep going |
|
||||||
|
| **Grader disagreement** | Model's output looks correct to you but the grader marks it wrong; or the prompt and the rubric ask for different things | Fix the grader, then re-grade *every* variant in place from stored outputs. Before overwriting, compare old vs new grades - how many cases moved, and did the variant ranking change? If the previous best is still the best and its lead over baseline held, keep going. If the ranking flipped or the lead collapsed to noise, the prior rounds were tuned to the wrong signal: show the before/after table and propose restarting the loop from baseline. |
|
||||||
|
| **Harness / infra** | Case errored before the model produced a scorable output - auth failure, timeout, rate-limit, env setup. Some harnesses *score* the failure instead of erroring it: zero-scored cases whose transcripts carry infra markers (retries exhausted, stall ceilings, empty outputs) belong here too | Fix the harness; exclude errored cases from the denominator until then. For scored-in zeros, decide the handling rule before comparing scores |
|
||||||
|
| **Structural** | The content exists in the artifact but the model didn't reach it; or the same review finding recurs across rounds; or one dimension (a language, a provider) underperforms regardless of which feature you target | Reorganize - consolidate duplicated facts into one table, split a monolith file, fix the routing - rather than adding more of the unreached content |
|
||||||
|
| **Variance** | Pass<->fail flips between identical-code runs are as large as the round-over-round delta | You're at the noise floor on this lever. Report best-so-far; offer to raise reps or change target |
|
||||||
|
|
||||||
|
A failure that fits none of these is itself a signal: the artifact you're tuning may not be the bottleneck for that slice - offer to change target rather than forcing it into a bucket.
|
||||||
|
|
||||||
|
Write the bucket counts to `vN/change.md` in place of a content diff for that round, and tell the user: N of the remaining M failures aren't artifact gaps - here's what each cluster needs. Then dispatch per bucket rather than running another content round against all of them.
|
||||||
|
|
||||||
|
Two patterns this surfaces that the per-round analyzer can't:
|
||||||
|
|
||||||
|
- **The long tail.** The analyzer's "single behavior that most often costs the grade" is worst-bucket-first and never reaches a tail of many small buckets each costing one or two cases. If categorization shows a dozen dimensions each contributing <=2 failures and none of them have artifact coverage, a one-shot **breadth pass** - draft minimal coverage for every uncovered dimension in parallel, apply all at once - covers more ground in one round than the serial loop will in ten. This deliberately breaks one-change-per-round: the dimensions are independent, the question is coverage not attribution, and no single one would move the score enough to measure on its own.
|
||||||
|
- **Mid-run grader drift.** Step 0.5 proved the eval was trustworthy at the start. A rubric that's subtly wrong for one feature, or a canonical answer that's gone stale, won't show up as an implausible jump - it shows up as a feature that won't move no matter what content you add. When one bucket resists three rounds of content that looks correct to you, re-read its rubric before writing round four - and if you do change it, re-grade everything, quantify the shift, and decide with the user whether the existing rounds still stand.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 5: Report and hand back
|
||||||
|
|
||||||
|
When the loop ends, put the codebase at the version that won on test. The headline is the **test-score delta, baseline vs winner** - you already have both numbers from the per-round runs. (If Step 3 chose no split, report the whole-set delta and label it **directional**; if it chose the optional three-way split, run the held-back test slice now on baseline and winner only.) Rewrite `narrative.md` one last time as the final status table (kept on top, as in Step 4) followed by the four-part exec summary - **Recommended change**, **Versus baseline**, **Why trust this**, **What else was tried** - then regenerate `report.html` one last time (full or lite builder, as in Step 4); it is the artifact you point the user at for per-case detail. In parallel, produce a short text report (in the user's PR description if they want a PR, or as a markdown file otherwise) - this is a **companion** to `report.html`, not a replacement, so point at it for transcripts (full viewer) or trace files (lite) and per-case detail rather than duplicating them inline. It covers:
|
||||||
|
|
||||||
|
- **Headline:** test score at baseline -> test score at the winning round, each with a confidence interval, and the delta. This is the result. Train improvement is supporting detail, not the claim. **If the test delta is within noise of zero - the CIs overlap, or a paired test over cases isn't significant - say so plainly and recommend not merging.** An honest "this didn't move the needle, here's what I'd try with more budget" is more useful to the user than a dressed-up marginal gain.
|
||||||
|
- **Per-round table:** round, one-line description of the change, train score, test score, and the guardrail columns with their baseline ratios. Flag only the deltas that clear noise; suppress or grey out the ones that don't, so the user's eye lands on what actually moved. The train vs test columns side by side are the generalization-gap trajectory - if they diverge round over round, say so explicitly.
|
||||||
|
- The changes that are actually applied to the codebase right now, each with its one-sentence "why" from `change.md`, and each tagged **`[REQUIRED]`** (fixes something broken - e.g., a parameter that errors on the target model) or **`[TUNE]`** (a judgment call that improved the score but that the user could reasonably decline). This lets the user accept the diff selectively.
|
||||||
|
- **A failure taxonomy, when zeros have mixed causes:** how many failures were refusals, harness or serving errors, and timeouts, versus genuine capability misses - a single rate hides it. And when the loop compared models, classify failures per model before quoting a gap: a failure mode only one model triggers (say, a tool-calling convention the harness rejects from that model) is a harness bug confounding the comparison, not a capability difference; report the gap with and without those attempts.
|
||||||
|
- **A second-model check, if the artifact will serve more than one model:** re-run the winner once on the other model(s) before recommending it, and report per-model numbers - failures are model-dependent, and a win measured on one model doesn't transfer by default.
|
||||||
|
- **Two or three before/after transcript pairs** - the same prompt under baseline and under the winning version, side by side - so the user can see the quality change with their own eyes rather than taking the number on faith. Pick cases that illustrate the behavior the changes were targeting.
|
||||||
|
- **What you'd try next.** Proactively list the concrete levers still on the table - "`effort=medium` looked promising on latency but I didn't re-tune the prompt for it; the `summarize` tool description is still vague; judge could move to `claude-sonnet-5`" - rather than waiting for the user to ask whether there's more. Include anything that seemed to need a bigger change than the target allowed.
|
||||||
|
|
||||||
|
The report is what lets the user trust the diff enough to merge it. Be specific about *why* each change helps; "reworded the system prompt" is not enough.
|
||||||
|
|
||||||
|
If the eval and flow directory aren't already committed, offer the same three-way choice as `build-eval.md` §Make it durable (commit eval / commit eval + transcripts / don't), with fresh file and size counts now that there are multiple rounds. Recommend committing the eval - the harness change going into this PR is only half the value; the other half is being able to re-baseline on the next model without rebuilding the eval.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Failure modes to avoid
|
||||||
|
|
||||||
|
- **Touching the held-out set.** The split is the only thing standing between a real improvement and an overfit one. Don't open test transcripts, and don't let test-case content inform a proposed change - the analyzer reads train, the headline comes from test, and that wall is the result's credibility.
|
||||||
|
- **Leaving ground truth reachable.** If the model-under-test can read the expected answers from disk, the loop will eventually find that path and "win" without improving anything. Isolate answers structurally; don't rely on instructions. On a public benchmark, "reachable" includes the internet - a web-enabled agent can fetch a solutions mirror (see Step 3).
|
||||||
|
- **Trusting an implausible jump.** When a model-graded score leaps further than the change could reasonably explain, the likeliest cause is the judge being gamed, not the app getting better. Spot-check by hand before celebrating.
|
||||||
|
- **Climbing on an untrustworthy eval.** Skipping Step 0.5 means you might be tuning against a disconnected mechanism or a mis-aggregated headline number - "improving" an artifact and shipping nothing. Prove the mechanism is wired and the headline recomputes from raw per-case results *before* the first round.
|
||||||
|
- **Grinding content at a wall.** Adding more content for a feature that hasn't moved in three rounds, without first asking whether the failure is the grader's, the harness's, or structural. Step 4.5 is the check.
|
||||||
|
- **Averaging refusals into the score.** A safety refusal is not a capability failure, and a harness-killed attempt is neither. Record a failure class per attempt (refusal / harness-or-serving error / timeout / genuine failure), report refusal-zeros separately from capability-zeros, and pre-register the scrub predicate for anomalous zeros (e.g. completed with score 0 at a wall-clock and request count far below the task's normal floor), reporting raw and scrubbed - decide the rule before the scores exist.
|
||||||
|
- **Letting the platform shift under the loop.** If the serving platform or harness changes execution semantics mid-run - environment reuse, batching, defaults - rounds stop being comparable. Pin the runner and its dependencies for the whole loop, and verify the semantics you depend on from run artifacts (e.g. one environment per case) rather than assuming them.
|
||||||
|
- **Climbing on a gain you can't explain.** If the score moved but you can't point to the behavior that moved it - a shift in how often the mechanism engaged, specific flips in the traces - the "win" is as likely noise or a measurement artifact as a real improvement. Tie every delta to a mechanism; distrust the ones you can't.
|
||||||
|
- **Overgeneralizing from one case.** Seeing a pattern in a single failure and rewriting the whole prompt around it is the most common way to make the score go down. The analyzer should cite the traces that motivate a change, describe the *behavior* rather than pasting the *content* of the failures into the prompt, and prefer narrow changes over sweeping ones.
|
||||||
|
- **Untracked bundling.** Stacking several unrelated edits into one round's change means that if it helps you won't know which part did the work, and if it hurts you won't know which part to revert. One idea per round.
|
||||||
|
- **Accumulating fluff.** Without the per-round de-fluff pass, prompts grow a sediment of vague, unfalsifiable advice that costs tokens and dilutes the instructions that matter.
|
||||||
|
- **Losing state.** If the session is interrupted, the next session should be able to read `_state.json` and the `vN/` directories and pick up exactly where this one left off. Write state after every round, not at the end. If the proposer/analyzer runs as its own long-lived session, its working artifacts - the traces and scores it was handed, and its rationale for each change - belong under the flow directory too, so an interrupted loop can reconstruct the proposer, not just the scores.
|
||||||
|
- **Editing off-limits content.** The user told you what not to touch in Step 1. A change that improves the score but violates a constraint the user stated is not an improvement.
|
||||||
|
- **Treating the budget as a wall (or ignoring it)** - when cost is a guardrail. Recompute cumulative spend from the `results.jsonl` files - plus the billed usage on any `errors.jsonl` failed attempts - and check it against the Step 2 ceiling every round. If you're going to exceed it, ask first. Equally, don't stop cold at the limit while test is clearly still climbing without *offering* to continue.
|
||||||
253
skills/claude-api/shared/evals/report/SCHEMA.md
Normal file
253
skills/claude-api/shared/evals/report/SCHEMA.md
Normal file
@@ -0,0 +1,253 @@
|
|||||||
|
# Hillclimb state schema (v2)
|
||||||
|
|
||||||
|
`state.json` is the single handoff between an **adapter** (which reads
|
||||||
|
whatever your run directory looks like) and the **renderer** (which
|
||||||
|
produces `report.html`). Every field below is optional unless marked
|
||||||
|
**required** - the renderer shows what is present and hides what is
|
||||||
|
absent, so a minimal state with just `metrics`, `variants` and
|
||||||
|
`examples` renders fine, and a maximal one with reps, splits, judge
|
||||||
|
explanations, attachments and CIs renders all of those too.
|
||||||
|
|
||||||
|
Dialect: JSON. Arrays preserve order. Field names are `snake_case`.
|
||||||
|
|
||||||
|
> **Built-in adapter tolerance.** `adapter.load()` is forgiving about
|
||||||
|
> the on-disk input: in `results.jsonl` the case id may be spelled
|
||||||
|
> `prompt_id`, `id`, or `case_id`; if `_state.json` omits `metrics`
|
||||||
|
> they are inferred from the union of `grade` keys. The schema below
|
||||||
|
> is what the adapter *produces*, not what it requires.
|
||||||
|
|
||||||
|
## Top level
|
||||||
|
|
||||||
|
```ts
|
||||||
|
{
|
||||||
|
schema: "hillclimb/v2",
|
||||||
|
|
||||||
|
source?: { // provenance - shown as a grey header bar
|
||||||
|
path: string, // relative path of the data dir
|
||||||
|
n_files: number,
|
||||||
|
content_sha: string, // sha256 over sorted (relpath, file-sha) pairs
|
||||||
|
generated_at: string, // ISO 8601
|
||||||
|
},
|
||||||
|
|
||||||
|
metrics: Metric[], // REQUIRED - what each example is graded on
|
||||||
|
perf_fields?: PerfField[], // runtime fields to surface (default set below)
|
||||||
|
|
||||||
|
variants: Variant[], // REQUIRED - baseline first
|
||||||
|
examples: Example[], // REQUIRED - every row in the eval set
|
||||||
|
metrics_md?: string, // free-text rubric (markdown)
|
||||||
|
|
||||||
|
// The next three are stderr/--check only: load() returns them in memory for
|
||||||
|
// build-report.mjs to print, but they are NOT written to state.json or
|
||||||
|
// report.html (they can carry absolute paths and fs error text).
|
||||||
|
warnings?: string[], // adapter diagnostics - stderr under --check
|
||||||
|
errors?: string[], // only; build-report strips all three before
|
||||||
|
trace_stats?: object[], // writing state.json / report.html
|
||||||
|
|
||||||
|
strtab?: { [key]: string }, // report.html embed only (never state.json):
|
||||||
|
// strings >=1 KB that repeat across transcripts
|
||||||
|
// are stored once here and referenced as
|
||||||
|
// "\u0001S:<key>"; hc-adapt.js resolves them at
|
||||||
|
// load. Tool payloads >24 KB are also clipped
|
||||||
|
// in the embed with a pointer to the trace file.
|
||||||
|
|
||||||
|
summary?: {
|
||||||
|
narrative?: string, // markdown - model-authored running exec
|
||||||
|
// summary; rewritten after every round,
|
||||||
|
// finalized as the 4-part summary in Step 5
|
||||||
|
best_variant?: string, // variant id
|
||||||
|
headline_metric?: string, // metric id that test/val/train below
|
||||||
|
// were computed over; titles the
|
||||||
|
// score-by-split chart
|
||||||
|
test?: SplitScore, // headline - shown with CI bars
|
||||||
|
val?: SplitScore,
|
||||||
|
train?: SplitScore,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## `Metric`
|
||||||
|
|
||||||
|
```ts
|
||||||
|
{
|
||||||
|
id: string, // REQUIRED - key used in scores{}
|
||||||
|
label?: string, // defaults to id; keep <=14 chars - the
|
||||||
|
// legend has limited width and truncates
|
||||||
|
// with an ellipsis
|
||||||
|
kind: "binary" | "float" | "judge",
|
||||||
|
// binary -> % (n/N); float -> mean±sd;
|
||||||
|
// judge -> float score with per-rep `explanation`
|
||||||
|
scale?: number, // upper bound of the raw score range;
|
||||||
|
// default: 1 for binary, 10 for float/judge.
|
||||||
|
// Set explicitly for anything else (e.g. 5, 100).
|
||||||
|
better?: "higher" | "lower", // default "higher"; drives delta colouring
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## `PerfField`
|
||||||
|
|
||||||
|
```ts
|
||||||
|
{ id: string, label?: string, unit?: string }
|
||||||
|
```
|
||||||
|
|
||||||
|
If `perf_fields` is absent the renderer uses the default set:
|
||||||
|
`cost_usd`, `in_tokens`, `out_tokens`, `web_searches`, `tool_calls`,
|
||||||
|
`latency_s`. The built-in adapter passes `perf_fields` (and
|
||||||
|
`metrics`) through from `.claude/hillclimb/<flow>/_state.json` when
|
||||||
|
present, so writing that file is how you override the columns
|
||||||
|
without writing a custom adapter.
|
||||||
|
|
||||||
|
## `Variant`
|
||||||
|
|
||||||
|
```ts
|
||||||
|
{
|
||||||
|
id: string, // REQUIRED - "baseline", "v1", ...
|
||||||
|
label?: string,
|
||||||
|
description?: string,
|
||||||
|
target?: "system_prompt" | "skill" | "tools" | "code",
|
||||||
|
change_rationale?: string, // markdown - rendered above the diffs
|
||||||
|
diffs?: {
|
||||||
|
incremental: [{ rel_path: string, unified_diff: string }], // vN vs vN-1 (change.patch)
|
||||||
|
cumulative: [{ rel_path: string, unified_diff: string }], // vN vs baseline (recomputed from snapshots)
|
||||||
|
},
|
||||||
|
model?: string | string[], // distinct row.model values; "mixed" chip if >1
|
||||||
|
suspicious?: { note: string }, // renderer shows a WARNING badge + tooltip
|
||||||
|
errors?: { total: number, by_class: { [cls]: number }, truncated: number },
|
||||||
|
// failed attempts from errors.jsonl + status:truncated rows;
|
||||||
|
// shown as a "WARNING N not scored" badge, never in the means
|
||||||
|
metrics?: { [metric_id]: number },
|
||||||
|
// summary-only metrics ONLY - metrics that
|
||||||
|
// appear in examples[].results are ignored
|
||||||
|
// here (the UI derives those from the rows)
|
||||||
|
paired?: { [split]: { [metric_id]: PairedDelta } },
|
||||||
|
// paired per-case delta vs baseline, per
|
||||||
|
// criterion. The renderer uses .significant
|
||||||
|
// to gate cell heat-tinting (within-noise ->
|
||||||
|
// neutral); the numbers stay here for audit.
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The first variant is treated as the baseline. `summary.best_variant`
|
||||||
|
names the winner; if absent, the last variant is assumed.
|
||||||
|
|
||||||
|
## `PairedDelta`
|
||||||
|
|
||||||
|
```ts
|
||||||
|
{
|
||||||
|
mean: number, // mean of per-case (variant_mean - ref_mean)
|
||||||
|
ci_lo: number, ci_hi: number, // Wald CI over per-case deltas
|
||||||
|
n: number, // cases present in BOTH variants
|
||||||
|
significant: boolean, // CI excludes zero
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
A paired comparison: for each case present in both variants, take the
|
||||||
|
mean across that variant's reps minus the mean across the reference's
|
||||||
|
reps, then a CI over those per-case deltas. More powerful than
|
||||||
|
comparing two `SplitScore` CIs because between-case variance cancels -
|
||||||
|
two variants' unpaired CIs can overlap while the paired delta is
|
||||||
|
clearly non-zero.
|
||||||
|
|
||||||
|
## `Example`
|
||||||
|
|
||||||
|
```ts
|
||||||
|
{
|
||||||
|
id: string, // REQUIRED
|
||||||
|
prompt: string, // REQUIRED
|
||||||
|
split?: "train" | "val" | "test",
|
||||||
|
tags?: string[], // ORDERED - tags[0] is the primary
|
||||||
|
// grouping key the UI clusters rows by
|
||||||
|
// (replaces v1's singular `category`);
|
||||||
|
// further entries are secondary filters
|
||||||
|
meta?: { [k]: any }, // arbitrary sidecar data
|
||||||
|
attachments?: Attachment[], // input artifacts - render above the first
|
||||||
|
// user turn in the transcript view
|
||||||
|
results: { [variant_id]: RepResult[] }, // REQUIRED (may be empty per variant)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## `Attachment`
|
||||||
|
|
||||||
|
```ts
|
||||||
|
{
|
||||||
|
kind?: "image" | "svg" | "html" | "pdf" | "json" | "text" | "code"
|
||||||
|
| "file" | "url", // inferred from ref if omitted
|
||||||
|
ref: string, // path relative to the flow root, data: URI,
|
||||||
|
// or URL. Paths under 2 MB are inlined as
|
||||||
|
// data: at build time; larger -> download chip.
|
||||||
|
alt?: string,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`image`/`svg` render inline; `html` in a sandboxed scrollable iframe; `pdf`
|
||||||
|
via the browser's native viewer in a scrollable embed; `json`/`text`/`code`
|
||||||
|
in a `<pre>`; `file` (docx/pptx/anything else) and `url` as a download/open
|
||||||
|
chip. Every kind has a Hide/Show toggle.
|
||||||
|
|
||||||
|
## `RepResult`
|
||||||
|
|
||||||
|
```ts
|
||||||
|
{
|
||||||
|
rep?: number, // 0-based; default = array index
|
||||||
|
status?: string, // present only when not 'ok' (e.g. 'truncated'); scores is {} then
|
||||||
|
scores: { [metric_id]: number },
|
||||||
|
explanation?: { [metric_id]: string }, // judge rationale per metric
|
||||||
|
model?: string, // model id that produced this rep (from the response)
|
||||||
|
perf?: { [perf_field_id]: number },
|
||||||
|
attachment?: string, // relative path to a per-rep output screenshot
|
||||||
|
transcript?: Turn[],
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## `Turn`
|
||||||
|
|
||||||
|
```ts
|
||||||
|
{
|
||||||
|
role: "system" | "user" | "assistant" | "tool_call" | "tool_result",
|
||||||
|
content: string, // markdown for user/assistant/system;
|
||||||
|
// pretty-printed args/result for tool turns
|
||||||
|
name?: string, // tool name (tool_call / tool_result)
|
||||||
|
thinking?: string, // assistant extended-thinking (collapsible)
|
||||||
|
attachments?: Attachment[], // artifacts produced/consumed at this turn -
|
||||||
|
// render below the turn content. Use this for
|
||||||
|
// files the model wrote, generated plots, etc.
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
On the input side, the built-in adapter reads `traces/<id>.json`
|
||||||
|
directly as a `Turn[]` list - each tool call / result is its own
|
||||||
|
`{role: "tool_call", name, content}` / `{role: "tool_result", content}`
|
||||||
|
entry. See `build-eval.md` §Step 3 for the trace-writing spec.
|
||||||
|
|
||||||
|
## `SplitScore`
|
||||||
|
|
||||||
|
```ts
|
||||||
|
{
|
||||||
|
score: number,
|
||||||
|
ci_lo?: number,
|
||||||
|
ci_hi?: number,
|
||||||
|
n?: number,
|
||||||
|
significant?: boolean, // vs baseline - greys out & badges "within noise" when false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Rendering rules
|
||||||
|
|
||||||
|
* Every aggregate in the UI is computed from `examples[].results` at
|
||||||
|
render time, so the `% (n/N)` shown always matches the rows listed -
|
||||||
|
including under split/tag filters.
|
||||||
|
* `variants[].metrics` is a fallback for metrics that never appear in
|
||||||
|
any example's `scores` (e.g. a `train_score` pulled from
|
||||||
|
`summary.json`). If a metric does appear per-row, the per-variant
|
||||||
|
`metrics` value is ignored.
|
||||||
|
* Binary metrics with `reps > 1`: the per-cell display is the
|
||||||
|
rep-level pass rate, e.g. `67% (2/3)`. Float metrics: `mean ± sd`.
|
||||||
|
* A variant's `suspicious.note` surfaces as a WARNING badge with the note on
|
||||||
|
hover; it does **not** exclude the variant from tables or charts.
|
||||||
|
|
||||||
|
## Writing your own adapter
|
||||||
|
|
||||||
|
`adapter.load(path) -> dict` is the only contract. If your data is not
|
||||||
|
laid out like `.claude/hillclimb/<flow>/`, write a function that reads
|
||||||
|
whatever you have and returns a dict matching this document, then call
|
||||||
|
`render.render(state)` directly (see `build-report.mjs` for the
|
||||||
|
one-liner). The renderer has no opinion about where the data came from.
|
||||||
351
skills/claude-api/shared/evals/report/build-report-lite.mjs
Normal file
351
skills/claude-api/shared/evals/report/build-report-lite.mjs
Normal file
@@ -0,0 +1,351 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// Lite report builder for the build-eval / hillclimb loop: a single static
|
||||||
|
// report.html with no vendored runtime, fonts, or markdown engine.
|
||||||
|
//
|
||||||
|
// node build-report-lite.mjs .claude/hillclimb/<flow>/
|
||||||
|
//
|
||||||
|
// Reads the same on-disk layout as build-report.mjs (baseline/, v<N>/,
|
||||||
|
// results.jsonl, errors.jsonl, change.md, summary.json, traces/, _state.json)
|
||||||
|
// and derives the same numbers: per-variant mean of the primary metric over
|
||||||
|
// status-ok rows, per-case means, split (train/val/test) from _state.json,
|
||||||
|
// failed-attempt counts from errors.jsonl. It also writes
|
||||||
|
// trajectory/scores.tsv exactly as the full builder does, so hillclimb's
|
||||||
|
// per-round bookkeeping is identical whichever builder ran.
|
||||||
|
//
|
||||||
|
// What it deliberately does not do: render markdown, inline transcripts or
|
||||||
|
// attachments, or execute anything from the data. Every string from disk is
|
||||||
|
// HTML-escaped; traces are linked by relative path, not embedded. Sorting is
|
||||||
|
// a few lines of inline script over the rendered table only.
|
||||||
|
//
|
||||||
|
// Runs under node or bun. Node builtins only.
|
||||||
|
|
||||||
|
import { closeSync, constants as FS, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
||||||
|
import { dirname, join, resolve } from 'node:path';
|
||||||
|
|
||||||
|
const isNum = x => typeof x === 'number' && Number.isFinite(x);
|
||||||
|
// readText/readJSON refuse symlinks, like the full builder's lib/adapter.mjs:
|
||||||
|
// the flow dir is model-influenced, and a prompt-injected agent could plant
|
||||||
|
// `summary.json -> ~/.ssh/id_rsa`; the user later runs this builder (outside
|
||||||
|
// any sandbox) and the target lands in the shareable report.html. Open
|
||||||
|
// O_NOFOLLOW and fstat the fd (not lstat-then-read) so a concurrent writer
|
||||||
|
// can't swap in a symlink between the check and the read.
|
||||||
|
const readText = p => {
|
||||||
|
let fd;
|
||||||
|
try {
|
||||||
|
fd = openSync(p, FS.O_RDONLY | (FS.O_NOFOLLOW ?? 0));
|
||||||
|
if (!fstatSync(fd).isFile()) return '';
|
||||||
|
return readFileSync(fd, 'utf8');
|
||||||
|
} catch { return ''; }
|
||||||
|
finally { if (fd !== undefined) closeSync(fd); }
|
||||||
|
};
|
||||||
|
const readJSON = (p, dflt) => { try { return JSON.parse(readText(p)); } catch { return dflt; } };
|
||||||
|
const esc = s => String(s ?? '').replace(/[&<>"']/g, c =>
|
||||||
|
({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||||
|
const fmt = x => (x == null ? '' : x.toFixed(3));
|
||||||
|
// TSV id cells come from untrusted results.jsonl: strip the separators that
|
||||||
|
// would forge rows/columns in trajectory/scores.tsv, and neutralize a leading
|
||||||
|
// formula trigger so spreadsheet apps don't execute '=WEBSERVICE(...)' on
|
||||||
|
// open. Mirrored in the full builder's lib/adapter.mjs so both emit
|
||||||
|
// byte-identical scores.tsv.
|
||||||
|
const tsvCell = s => {
|
||||||
|
const flat = String(s).replace(/[\t\n\r]/g, ' ');
|
||||||
|
return /^[=+\-@]/.test(flat) ? "'" + flat : flat;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Variant directories: exactly `baseline` or `v<N>`, numeric order.
|
||||||
|
function discoverVariants(flow) {
|
||||||
|
const names = readdirSync(flow, { withFileTypes: true })
|
||||||
|
.filter(e => e.isDirectory() && /^(baseline|v\d+)$/.test(e.name))
|
||||||
|
.map(e => e.name);
|
||||||
|
const rank = n => (n === 'baseline' ? -1 : +n.slice(1));
|
||||||
|
return names.sort((a, b) => rank(a) - rank(b));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mirrors the full adapter: an object of numeric/boolean grades, a bare
|
||||||
|
// boolean, or a bare number (-> {score}).
|
||||||
|
function coerceScores(g) {
|
||||||
|
if (g && typeof g === 'object' && !Array.isArray(g)) {
|
||||||
|
const out = {};
|
||||||
|
for (const [k, v] of Object.entries(g)) if (isNum(v) || typeof v === 'boolean') out[k] = +v;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
if (typeof g === 'boolean') return { score: g ? 1 : 0 };
|
||||||
|
if (isNum(g)) return { score: g };
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadRows(p, warnings, dir) {
|
||||||
|
// Keyed by data-supplied ids: null-prototype so '__proto__' is a key, not a crash.
|
||||||
|
const byId = Object.create(null);
|
||||||
|
readText(p).split('\n').forEach((line, i) => {
|
||||||
|
line = line.trim();
|
||||||
|
if (!line) return;
|
||||||
|
let r;
|
||||||
|
try { r = JSON.parse(line); } catch { warnings.push(dir + '/results.jsonl:' + (i + 1) + ': malformed JSON, skipped'); return; }
|
||||||
|
const pid = String(r.prompt_id ?? r.id ?? r.case_id ?? '');
|
||||||
|
if (!pid) { warnings.push(dir + '/results.jsonl:' + (i + 1) + ': no prompt_id, skipped'); return; }
|
||||||
|
(byId[pid] ||= []).push(r);
|
||||||
|
});
|
||||||
|
return byId;
|
||||||
|
}
|
||||||
|
|
||||||
|
function countErrors(vdir) {
|
||||||
|
let total = 0;
|
||||||
|
const byClass = Object.create(null);
|
||||||
|
for (const line of readText(join(vdir, 'errors.jsonl')).split('\n')) {
|
||||||
|
if (!line.trim()) continue;
|
||||||
|
let e; try { e = JSON.parse(line); } catch { continue; }
|
||||||
|
total++;
|
||||||
|
const c = String(e?.failure_class ?? 'error');
|
||||||
|
byClass[c] = (byClass[c] || 0) + 1;
|
||||||
|
}
|
||||||
|
return { total, byClass };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Inferred metrics, mirroring the full builder's inferMetrics: any
|
||||||
|
// explanation for a key -> judge, all-0/1 values -> binary, else float;
|
||||||
|
// first-seen order.
|
||||||
|
function inferMetrics(rows, variants) {
|
||||||
|
const seen = new Map();
|
||||||
|
for (const v of variants) for (const reps of Object.values(rows[v])) for (const r of reps) {
|
||||||
|
const expl = r.explanation && typeof r.explanation === 'object' ? r.explanation : {};
|
||||||
|
for (const [k, val] of Object.entries(coerceScores(r.grade))) {
|
||||||
|
const m = seen.get(k) || { binary: true, judge: false };
|
||||||
|
if (val !== 0 && val !== 1) m.binary = false;
|
||||||
|
if (k in expl) m.judge = true;
|
||||||
|
seen.set(k, m);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [...seen.entries()].map(([id, s]) => ({ id, kind: s.judge ? 'judge' : s.binary ? 'binary' : 'float' }));
|
||||||
|
}
|
||||||
|
|
||||||
|
function build(flowArg) {
|
||||||
|
const flow = resolve(flowArg);
|
||||||
|
if (!statSync(flow, { throwIfNoEntry: false })?.isDirectory()) throw new Error('not a directory: ' + flow);
|
||||||
|
const variants = discoverVariants(flow);
|
||||||
|
if (!variants.length) throw new Error('no variant directories (baseline/, v1/, ...) under ' + flow);
|
||||||
|
const warnings = [];
|
||||||
|
// Same warning the full builder gives: a mis-named variant dir is the usual
|
||||||
|
// reason the header shows one variant fewer than expected.
|
||||||
|
const nonVariant = new Set(['trajectory', 'attachments', 'refs', 'ref', 'inputs', 'out', '__pycache__']);
|
||||||
|
for (const e of readdirSync(flow, { withFileTypes: true }))
|
||||||
|
if (e.isDirectory() && !variants.includes(e.name) && !nonVariant.has(e.name)
|
||||||
|
&& !e.name.startsWith('.') && !e.name.startsWith('_'))
|
||||||
|
warnings.push("ignored directory '" + e.name + "/' - variant dirs must be named 'baseline' or 'v<N>'; put the descriptive name in change.md's first line instead");
|
||||||
|
const state = readJSON(join(flow, '_state.json'), {}) || {};
|
||||||
|
|
||||||
|
const splitOf = Object.create(null);
|
||||||
|
for (const sp of ['train', 'val', 'test']) for (const pid of state[sp + '_ids'] || []) splitOf[String(pid)] = sp;
|
||||||
|
|
||||||
|
const rows = Object.create(null);
|
||||||
|
for (const v of variants) rows[v] = loadRows(join(flow, v, 'results.jsonl'), warnings, v);
|
||||||
|
|
||||||
|
// Same as the full builder: drop non-baseline variants with zero result
|
||||||
|
// rows (a vN/ holding only change.md while the run warms up would render a
|
||||||
|
// blank column), and refuse to build when the first variant itself has none
|
||||||
|
// rather than overwrite a good trajectory/scores.tsv with a header-only file.
|
||||||
|
for (let i = variants.length - 1; i > 0; i--) {
|
||||||
|
const v = variants[i];
|
||||||
|
if (Object.keys(rows[v]).length) continue;
|
||||||
|
warnings.push(v + ': zero result rows - dropping (run not started or results.jsonl missing/empty)');
|
||||||
|
variants.splice(i, 1);
|
||||||
|
}
|
||||||
|
if (!Object.keys(rows[variants[0]]).length)
|
||||||
|
throw new Error(variants[0] + '/ has no result rows under ' + flow + ' - nothing to report');
|
||||||
|
|
||||||
|
const header = Object.create(null);
|
||||||
|
for (const v of variants) {
|
||||||
|
const vdir = join(flow, v);
|
||||||
|
const change = readText(join(vdir, 'change.md')).split('\n').find(l => l.trim()) || '';
|
||||||
|
const summary = readJSON(join(vdir, 'summary.json'), {}) || {};
|
||||||
|
// Model: summary.json wins, else the most common row.model (what the app called).
|
||||||
|
const tally = Object.create(null);
|
||||||
|
for (const reps of Object.values(rows[v])) for (const r of reps) if (typeof r.model === 'string') tally[r.model] = (tally[r.model] || 0) + 1;
|
||||||
|
const rowModel = Object.entries(tally).sort((a, b) => b[1] - a[1])[0]?.[0] || '';
|
||||||
|
header[v] = { change: change.replace(/^#+\s*/, ''), model: summary.model || rowModel, errors: countErrors(vdir) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Metrics: _state.json `metrics` (or the legacy `criteria` key) wins,
|
||||||
|
// keeping each declared `kind`; else inferred from grade keys. Primary is
|
||||||
|
// the first declared-or-inferred binary metric, else the first - the same
|
||||||
|
// selection the full builder's lib/adapter.mjs makes, so both builders
|
||||||
|
// report the same metric's numbers on the same flow.
|
||||||
|
const metricsCfg = state.metrics || state.criteria;
|
||||||
|
const declared = (Array.isArray(metricsCfg) ? metricsCfg : [])
|
||||||
|
.map(m => (typeof m === 'string' ? { id: m } : { id: m?.id, kind: m?.kind }))
|
||||||
|
.filter(m => m.id);
|
||||||
|
const metrics = declared.length ? declared : inferMetrics(rows, variants);
|
||||||
|
if (!metrics.length) metrics.push({ id: 'score', kind: 'float' });
|
||||||
|
const primary = (metrics.find(m => m.kind === 'binary') || metrics[0]).id;
|
||||||
|
|
||||||
|
// Cases: union of ids across variants, in first-seen order.
|
||||||
|
const ids = [];
|
||||||
|
const seenId = new Set();
|
||||||
|
for (const v of variants) for (const pid of Object.keys(rows[v])) if (!seenId.has(pid)) { seenId.add(pid); ids.push(pid); }
|
||||||
|
|
||||||
|
const okReps = reps => reps.filter(r => r.status == null || r.status === 'ok');
|
||||||
|
const caseMean = (reps, m) => {
|
||||||
|
const vals = okReps(reps).map(r => coerceScores(r.grade)[m]).filter(isNum);
|
||||||
|
return vals.length ? vals.reduce((s, x) => s + x, 0) / vals.length : null;
|
||||||
|
};
|
||||||
|
const cases = ids.map(pid => {
|
||||||
|
const first = variants.map(v => rows[v][pid]?.[0]).find(Boolean) || {};
|
||||||
|
const tags = Array.isArray(first.tags) ? first.tags.map(String) : [];
|
||||||
|
const per = {};
|
||||||
|
for (const v of variants) {
|
||||||
|
const reps = rows[v][pid] || [];
|
||||||
|
per[v] = {
|
||||||
|
mean: caseMean(reps, primary),
|
||||||
|
reps: reps.length,
|
||||||
|
truncated: reps.filter(r => r.status === 'truncated').length,
|
||||||
|
traces: reps.map((r, k) => {
|
||||||
|
// Link only to files directly inside this variant's traces/ dir:
|
||||||
|
// ids and reps come from results.jsonl (data, not trusted), so the
|
||||||
|
// composed path must not resolve anywhere else, and a symlinked
|
||||||
|
// trace must not become a link out of the tree. Keep the rep
|
||||||
|
// number so the link label matches the file it points at even when
|
||||||
|
// earlier reps have no trace. For rep 0 also accept the flat
|
||||||
|
// traces/<id>.json a single-rep runner may write (the full builder
|
||||||
|
// reads it as rep 0 too).
|
||||||
|
const rep = r.rep ?? k;
|
||||||
|
const stems = +rep === 0 ? [pid + '_rep' + rep, pid] : [pid + '_rep' + rep];
|
||||||
|
for (const stem of stems) {
|
||||||
|
const rel = v + '/traces/' + stem + '.json';
|
||||||
|
const abs = resolve(flow, rel);
|
||||||
|
if (dirname(abs) !== join(flow, v, 'traces')) return null;
|
||||||
|
if (lstatSync(abs, { throwIfNoEntry: false })?.isFile()) return { rep, rel };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}).filter(Boolean),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return { id: pid, split: splitOf[pid] || '', tags, prompt: String(first.prompt ?? ''), per };
|
||||||
|
});
|
||||||
|
|
||||||
|
// Per-variant aggregate: mean over cases that have a value, per split.
|
||||||
|
const agg = {};
|
||||||
|
for (const v of variants) {
|
||||||
|
const all = cases.map(c => c.per[v].mean).filter(isNum);
|
||||||
|
const test = cases.filter(c => c.split === 'test').map(c => c.per[v].mean).filter(isNum);
|
||||||
|
const m = xs => (xs.length ? xs.reduce((s, x) => s + x, 0) / xs.length : null);
|
||||||
|
agg[v] = { all: m(all), n: all.length, test: m(test), nTest: test.length,
|
||||||
|
truncated: cases.reduce((s, c) => s + c.per[v].truncated, 0) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// trajectory/scores.tsv - same shape as the full builder.
|
||||||
|
mkdirSync(join(flow, 'trajectory'), { recursive: true });
|
||||||
|
const tsv = [['id', 'split', ...variants].join('\t')];
|
||||||
|
for (const c of cases) tsv.push([tsvCell(c.id), tsvCell(c.split || 'all'), ...variants.map(v => fmt(c.per[v].mean))].join('\t'));
|
||||||
|
writeFileSync(join(flow, 'trajectory', 'scores.tsv'), tsv.join('\n') + '\n');
|
||||||
|
|
||||||
|
// _state.json's `best` is {round, test_score}; map the round to a variant
|
||||||
|
// name the way the full builder does (0 = baseline), and drop it when the
|
||||||
|
// named variant isn't on disk.
|
||||||
|
let best = null;
|
||||||
|
if (Number.isInteger(state.best?.round)) {
|
||||||
|
best = state.best.round === 0 ? 'baseline' : 'v' + state.best.round;
|
||||||
|
if (!variants.includes(best)) best = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const html = render({ flow, variants, header, agg, cases, primary, metrics: metrics.map(m => m.id), warnings, best });
|
||||||
|
writeFileSync(join(flow, 'report.html'), html);
|
||||||
|
return { variants: variants.length, cases: cases.length, warnings };
|
||||||
|
}
|
||||||
|
|
||||||
|
function render({ flow, variants, header, agg, cases, primary, metrics, warnings, best }) {
|
||||||
|
const hasSplit = cases.some(c => c.split);
|
||||||
|
const hasTest = variants.some(v => agg[v].nTest > 0);
|
||||||
|
const th = (label, key) => '<th data-k="' + esc(key) + '">' + esc(label) + '</th>';
|
||||||
|
|
||||||
|
const variantRows = variants.map(v => {
|
||||||
|
const h = header[v], a = agg[v];
|
||||||
|
const err = h.errors.total
|
||||||
|
? h.errors.total + ' (' + Object.entries(h.errors.byClass).map(([k, n]) => esc(k) + ' ' + n).join(', ') + ')'
|
||||||
|
: '0';
|
||||||
|
return '<tr' + (best === v ? ' class="best"' : '') + '><td>' + esc(v) + (best === v ? ' <span class="pill">best</span>' : '') + '</td>'
|
||||||
|
+ '<td>' + esc(h.change) + '</td><td>' + esc(h.model) + '</td>'
|
||||||
|
+ '<td class="num">' + fmt(a.all) + '</td><td class="num">' + a.n + '</td>'
|
||||||
|
+ (hasTest ? '<td class="num">' + fmt(a.test) + '</td><td class="num">' + a.nTest + '</td>' : '')
|
||||||
|
+ '<td class="num">' + a.truncated + '</td><td>' + err + '</td></tr>';
|
||||||
|
}).join('\n');
|
||||||
|
|
||||||
|
const caseRows = cases.map(c => {
|
||||||
|
const cells = variants.map(v => {
|
||||||
|
const p = c.per[v];
|
||||||
|
const links = p.traces.map(t => '<a href="' + esc(t.rel) + '">rep' + esc(t.rep) + '</a>').join(' ');
|
||||||
|
return '<td class="num" data-v="' + fmt(p.mean) + '">' + fmt(p.mean)
|
||||||
|
+ (p.truncated ? ' <span class="pill warn">' + p.truncated + ' truncated</span>' : '')
|
||||||
|
+ (links ? '<div class="links">' + links + '</div>' : '') + '</td>';
|
||||||
|
}).join('');
|
||||||
|
const prompt = c.prompt.length > 600 ? c.prompt.slice(0, 600) + '...' : c.prompt;
|
||||||
|
return '<tr><td class="id">' + esc(c.id) + '</td>'
|
||||||
|
+ (hasSplit ? '<td>' + esc(c.split) + '</td>' : '')
|
||||||
|
+ '<td>' + c.tags.map(t => '<span class="pill">' + esc(t) + '</span>').join(' ') + '</td>'
|
||||||
|
+ cells
|
||||||
|
+ '<td class="prompt"><details><summary>' + esc(prompt.split('\n')[0].slice(0, 80)) + '</summary><pre>' + esc(prompt) + '</pre></details></td></tr>';
|
||||||
|
}).join('\n');
|
||||||
|
|
||||||
|
const warn = warnings.length
|
||||||
|
? '<section class="warnings"><h2>Warnings</h2><ul>' + warnings.map(w => '<li>' + esc(w) + '</li>').join('') + '</ul></section>'
|
||||||
|
: '';
|
||||||
|
|
||||||
|
return '<!DOCTYPE html>\n<html lang="en"><head><meta charset="utf-8">'
|
||||||
|
+ '<meta name="viewport" content="width=device-width, initial-scale=1">'
|
||||||
|
+ '<title>' + esc(flow.split(/[\\/]/).pop()) + ' - eval report</title>'
|
||||||
|
+ '<style>' + CSS + '</style></head><body>'
|
||||||
|
+ '<header><h1>' + esc(flow.split(/[\\/]/).pop()) + '</h1>'
|
||||||
|
+ '<p class="meta">' + variants.length + ' variant' + (variants.length === 1 ? '' : 's') + ' · ' + cases.length + ' cases'
|
||||||
|
+ ' · primary metric <code>' + esc(primary) + '</code>'
|
||||||
|
+ (metrics.length > 1 ? ' (also: ' + metrics.filter(m => m !== primary).map(esc).join(', ') + ')' : '')
|
||||||
|
+ ' · generated ' + new Date().toISOString().slice(0, 19).replace('T', ' ') + ' UTC'
|
||||||
|
+ ' · lite report (no transcripts inlined; click rep links)</p></header>'
|
||||||
|
+ '<section><h2>Variants</h2><table><thead><tr>' + th('variant', 's') + th('change', 's') + th('model', 's')
|
||||||
|
+ th('mean ' + primary, 'n') + th('cases', 'n')
|
||||||
|
+ (hasTest ? th('test mean', 'n') + th('test cases', 'n') : '')
|
||||||
|
+ th('truncated', 'n') + th('failed attempts', 's') + '</tr></thead><tbody>' + variantRows + '</tbody></table></section>'
|
||||||
|
+ '<section><h2>Cases</h2><p class="hint">Click a column header to sort. Per-case values are the mean of <code>' + esc(primary) + '</code> over status-ok reps.</p>'
|
||||||
|
+ '<table id="cases"><thead><tr>' + th('id', 's') + (hasSplit ? th('split', 's') : '') + th('tags', 's')
|
||||||
|
+ variants.map(v => th(v, 'n')).join('') + th('prompt', 's') + '</tr></thead><tbody>' + caseRows + '</tbody></table></section>'
|
||||||
|
+ warn
|
||||||
|
+ '<script>' + SORT_JS + '</script></body></html>\n';
|
||||||
|
}
|
||||||
|
|
||||||
|
const CSS = [
|
||||||
|
':root{color-scheme:light dark;--fg:#1a1a1a;--bg:#fff;--muted:#666;--line:#ddd;--pill:#eee;--warn:#b45309;--best:#ecfdf5}',
|
||||||
|
'@media(prefers-color-scheme:dark){:root{--fg:#e6e6e6;--bg:#121212;--muted:#9a9a9a;--line:#333;--pill:#2a2a2a;--warn:#f59e0b;--best:#0f2a1f}}',
|
||||||
|
'body{font:14px/1.45 system-ui,-apple-system,Segoe UI,Roboto,sans-serif;color:var(--fg);background:var(--bg);margin:0;padding:24px;max-width:1400px}',
|
||||||
|
'h1{font-size:22px;margin:0 0 4px}h2{font-size:16px;margin:28px 0 8px}.meta,.hint{color:var(--muted);margin:0 0 8px}',
|
||||||
|
'table{border-collapse:collapse;width:100%}th,td{border-bottom:1px solid var(--line);padding:6px 8px;text-align:left;vertical-align:top}',
|
||||||
|
'th{cursor:pointer;user-select:none;white-space:nowrap}th.asc:after{content:" \\25B4"}th.desc:after{content:" \\25BE"}',
|
||||||
|
'td.num{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}td.id{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;white-space:nowrap}',
|
||||||
|
'.pill{display:inline-block;background:var(--pill);border-radius:10px;padding:0 8px;font-size:12px}.pill.warn{color:var(--warn)}',
|
||||||
|
'tr.best td{background:var(--best)}.links{font-size:12px}.links a{margin-right:6px}',
|
||||||
|
'td.prompt{max-width:520px}details summary{cursor:pointer;color:var(--muted)}pre{white-space:pre-wrap;font-size:12px;margin:6px 0 0}',
|
||||||
|
'.warnings{color:var(--warn)}code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace}',
|
||||||
|
].join('');
|
||||||
|
|
||||||
|
const SORT_JS = [
|
||||||
|
'document.querySelectorAll("th[data-k]").forEach(function(th){th.addEventListener("click",function(){',
|
||||||
|
'var t=th.closest("table"),tb=t.tBodies[0],i=Array.prototype.indexOf.call(th.parentNode.children,th);',
|
||||||
|
'var asc=!th.classList.contains("asc");t.querySelectorAll("th").forEach(function(h){h.classList.remove("asc","desc")});',
|
||||||
|
'th.classList.add(asc?"asc":"desc");var num=th.dataset.k==="n";',
|
||||||
|
'var rows=Array.prototype.slice.call(tb.rows);rows.sort(function(a,b){var x=a.cells[i],y=b.cells[i];',
|
||||||
|
'var u=num?parseFloat(x.dataset.v||x.textContent):x.textContent.trim().toLowerCase();',
|
||||||
|
'var w=num?parseFloat(y.dataset.v||y.textContent):y.textContent.trim().toLowerCase();',
|
||||||
|
'if(num){if(isNaN(u))u=-Infinity;if(isNaN(w))w=-Infinity}return (u<w?-1:u>w?1:0)*(asc?1:-1)});',
|
||||||
|
'rows.forEach(function(r){tb.appendChild(r)})})});',
|
||||||
|
].join('');
|
||||||
|
|
||||||
|
const arg = process.argv[2];
|
||||||
|
if (!arg || arg === '-h' || arg === '--help') {
|
||||||
|
console.error('usage: node build-report-lite.mjs <flow-dir> (e.g. .claude/hillclimb/<flow>/)');
|
||||||
|
process.exit(arg ? 0 : 2);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const { variants, cases, warnings } = build(arg);
|
||||||
|
for (const w of warnings) console.error('warning: ' + w);
|
||||||
|
console.error('wrote ' + join(resolve(arg), 'report.html') + ' (' + variants + ' variants, ' + cases + ' cases) and trajectory/scores.tsv');
|
||||||
|
} catch (e) {
|
||||||
|
console.error('build-report-lite: ' + (e?.message || e));
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
419
skills/claude-api/shared/evals/report/runner-scaffold.mjs
Normal file
419
skills/claude-api/shared/evals/report/runner-scaffold.mjs
Normal file
@@ -0,0 +1,419 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// Runner scaffold for the build-eval / hillclimb loop. Copy this into the
|
||||||
|
// user's repo and fill in loadCases / runCase / gradeCase below - the I/O
|
||||||
|
// shape, file naming, resume, and CLI surface are already hillclimb-ready
|
||||||
|
// so adding v2, v3, ... is `--variant v3`, not a refactor.
|
||||||
|
//
|
||||||
|
// node run-eval.mjs --flow .claude/hillclimb/<name> --variant baseline --reps 2
|
||||||
|
//
|
||||||
|
// Structural properties this encodes (so you don't have to remember them):
|
||||||
|
// - parameterized by --variant / --model / --reps (no hardcoded A/B pair)
|
||||||
|
// - rep-aware filenames + resume (traces/<id>_rep<k>.json)
|
||||||
|
// - reads _state.json, never writes it (loop state belongs to the orchestrator) -
|
||||||
|
// the ONE exception is --approve-harness recording `harness_sha` (see below)
|
||||||
|
// - refuses to run when the harness (this file + _state.json.harness_paths) has
|
||||||
|
// changed since the sha a human last approved with --approve-harness, so a
|
||||||
|
// round that edits the runner cannot execute unreviewed under a standing
|
||||||
|
// session allowlist
|
||||||
|
// - pairwise graders judge against frozen baseline/ref/<id>.* on disk
|
||||||
|
// - writes rows as cases complete (crash-safe)
|
||||||
|
// - jittered exponential backoff on transient 429/overloaded/5xx errors
|
||||||
|
// - hard per-case wall-clock ceiling (--timeout-s; stream keepalives don't reset it)
|
||||||
|
// - served-model assertion (response model must match --model; documented alias->snapshot
|
||||||
|
// shapes tolerated: 'foo-latest'/'foo-0'/'foo' -> 'foo-20250101' / 'foo@20250101' / 'foo-2025-01-01')
|
||||||
|
// - failed attempts land in errors.jsonl with a failure class and, when the call
|
||||||
|
// completed, the billed model/usage (never in results.jsonl)
|
||||||
|
// - row ids, trace filenames, and frozen refs share one path-safe id
|
||||||
|
// (original id kept in meta.original_id when sanitization changed it)
|
||||||
|
|
||||||
|
import { createHash } from 'node:crypto';
|
||||||
|
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||||
|
import { join, relative, resolve } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
// --- fill these in ----------------------------------------------------------
|
||||||
|
|
||||||
|
/** Return the list of input cases. Each must have a stable `id`. */
|
||||||
|
async function loadCases() {
|
||||||
|
// e.g. return JSON.parse(readFileSync('eval/cases.json', 'utf8'));
|
||||||
|
throw new Error('TODO: loadCases');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run the app on one input. Return everything the grader and the report need.
|
||||||
|
* `ctx.model` and `ctx.variant` are the CLI args; use them to pick the model
|
||||||
|
* and (for hillclimb) the harness/prompt under test.
|
||||||
|
*/
|
||||||
|
async function runCase(input, ctx) {
|
||||||
|
// const res = await client.messages.create({ model: ctx.model, ... });
|
||||||
|
// return {
|
||||||
|
// output: res.content.at(-1).text, // or a file you wrote, an HTML page, ...
|
||||||
|
// transcript: [...], // Turn[] - see SCHEMA.md
|
||||||
|
// model: res.model, usage: res.usage, stop_reason: res.stop_reason,
|
||||||
|
// // optional, for model-graded cost: judge_model, judge_usage
|
||||||
|
// // optional, per-turn artifacts: attachments: [{kind, ref, alt}]
|
||||||
|
// };
|
||||||
|
throw new Error('TODO: runCase');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Grade one output. For pairwise, `ref` is the FROZEN baseline output read
|
||||||
|
* from disk (baseline/ref/<id>.*) - never a freshly co-generated one.
|
||||||
|
* Return { grade: {metric_id: number, ...}, explanation?: {metric_id: string},
|
||||||
|
* judge_model?, judge_usage? }.
|
||||||
|
* If the judge call succeeded but grading still fails (parse error, bad
|
||||||
|
* schema), attach judge_model/judge_usage to the thrown error - the errors
|
||||||
|
* sidecar reads them so billed judge spend on failed attempts stays counted.
|
||||||
|
*/
|
||||||
|
async function gradeCase(input, run, ref, ctx) {
|
||||||
|
// return { grade: { pass: run.output.includes(input.expected) ? 1 : 0 } };
|
||||||
|
throw new Error('TODO: gradeCase');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Side-channel perf fields beyond the built-ins (latency_s etc.). */
|
||||||
|
function perfFrom(run) { return {}; }
|
||||||
|
|
||||||
|
// --- harness (you usually won't need to touch below this line) --------------
|
||||||
|
|
||||||
|
function parseArgs(argv) {
|
||||||
|
const a = { flow: '.claude/hillclimb/flow', variant: 'baseline',
|
||||||
|
model: undefined, reps: 1, concurrency: 4, timeoutS: 1800,
|
||||||
|
approveHarness: false };
|
||||||
|
// A flag at the end of argv would otherwise consume undefined - which for
|
||||||
|
// --model equals the default and silently disables the served-model check.
|
||||||
|
const val = (i) => { if (argv[i] === undefined) { console.error(`missing value for ${argv[i - 1]}`); usage(); process.exit(2); } return argv[i]; };
|
||||||
|
for (let i = 0; i < argv.length; i++) {
|
||||||
|
const k = argv[i];
|
||||||
|
if (k === '--flow') a.flow = val(++i);
|
||||||
|
else if (k === '--variant') a.variant = val(++i);
|
||||||
|
else if (k === '--model') a.model = val(++i);
|
||||||
|
else if (k === '--reps') a.reps = +val(++i);
|
||||||
|
else if (k === '--concurrency') a.concurrency = +val(++i);
|
||||||
|
else if (k === '--timeout-s') a.timeoutS = +val(++i);
|
||||||
|
else if (k === '--approve-harness') a.approveHarness = true;
|
||||||
|
else if (k === '-h' || k === '--help') { usage(); process.exit(0); }
|
||||||
|
else { console.error(`unknown argument: ${k}`); usage(); process.exit(2); }
|
||||||
|
}
|
||||||
|
if (!/^(baseline|v[1-9]\d*)$/.test(a.variant)) {
|
||||||
|
// The report only reads directories named 'baseline' or 'v<N>' - any other
|
||||||
|
// name runs to completion but spends the pass into a directory the Summary,
|
||||||
|
// trajectory, and budget arithmetic never see.
|
||||||
|
console.error(`--variant must be 'baseline' or 'v<N>', got '${a.variant}'`);
|
||||||
|
usage(); process.exit(2);
|
||||||
|
}
|
||||||
|
if (!Number.isFinite(a.timeoutS) || a.timeoutS < 0
|
||||||
|
|| a.timeoutS * 1000 > 2147483647 // setTimeout clamps >2^31-1 ms to 1 ms - the ceiling would fire instantly
|
||||||
|
|| !Number.isInteger(a.reps) || a.reps < 1
|
||||||
|
|| !Number.isInteger(a.concurrency) || a.concurrency < 1) { usage(); process.exit(2); }
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
function usage() {
|
||||||
|
console.error('usage: node run-eval.mjs --flow DIR --variant ID [--model ID] [--reps N] [--concurrency N] [--timeout-s N (0 = no ceiling)] [--approve-harness]');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Harness integrity gate. The hillclimb loop gets this runner command
|
||||||
|
// allowlisted for the session and then runs rounds unattended, while the
|
||||||
|
// per-round change (proposed by an analyzer fed untrusted transcripts) may
|
||||||
|
// legitimately edit harness code. Without this gate a round that rewrites the
|
||||||
|
// runner would execute attacker-chosen code on the next unattended run under
|
||||||
|
// the user's one-time approval. So: sha256 over this file plus every path in
|
||||||
|
// `_state.json.harness_paths` (relative to the directory the runner is invoked
|
||||||
|
// from, i.e. the repo root); compare to `_state.json.harness_sha`; refuse on
|
||||||
|
// absent/mismatch unless a human passes --approve-harness, which records the
|
||||||
|
// new sha. That write is the one sanctioned exception to "never write
|
||||||
|
// _state.json".
|
||||||
|
function checkHarness(statePath, st, approve) {
|
||||||
|
const self = fileURLToPath(import.meta.url);
|
||||||
|
const listed = Array.isArray(st.harness_paths) ? st.harness_paths.map(String) : [];
|
||||||
|
const paths = [...new Set([self, ...listed.map(p => resolve(p))])].sort();
|
||||||
|
const h = createHash('sha256');
|
||||||
|
const hashed = [];
|
||||||
|
for (const p of paths) {
|
||||||
|
let buf;
|
||||||
|
try { buf = readFileSync(p); }
|
||||||
|
catch (e) {
|
||||||
|
if (p === self) throw e;
|
||||||
|
console.error(`warning: harness path '${relative(process.cwd(), p)}' not readable (${e?.code || 'error'}) - skipped`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
h.update(relative(process.cwd(), p)).update('\0').update(buf).update('\0');
|
||||||
|
hashed.push(relative(process.cwd(), p));
|
||||||
|
}
|
||||||
|
const sha = h.digest('hex');
|
||||||
|
if (st.harness_sha === sha) return;
|
||||||
|
if (approve) {
|
||||||
|
st.harness_sha = sha;
|
||||||
|
writeFileSync(statePath, JSON.stringify(st, null, 2) + '\n');
|
||||||
|
console.error(`harness approved: sha256 ${sha.slice(0, 12)} over ${hashed.length} file(s) recorded in ${statePath}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (st.harness_sha == null) {
|
||||||
|
console.error(`no approved harness sha in ${statePath} (computed ${sha.slice(0, 12)} over: ${hashed.join(', ')}).`);
|
||||||
|
console.error('Review the harness, then run once with --approve-harness to record it.');
|
||||||
|
} else {
|
||||||
|
console.error(`harness changed since last approved run (files: ${hashed.join(', ')}); `
|
||||||
|
+ `approved ${String(st.harness_sha).slice(0, 12)}, now ${sha.slice(0, 12)}.`);
|
||||||
|
console.error('Re-run with --approve-harness after reviewing the diff.');
|
||||||
|
}
|
||||||
|
process.exit(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Transient provider errors (429 / overloaded / 5xx) retry with jittered
|
||||||
|
// exponential backoff - a zero-delay retry loop multiplies cost invisibly
|
||||||
|
// under rate limits and can turn one transient 429 into a torn-down batch.
|
||||||
|
// The attempt count lands in the row's meta (or the errors sidecar) so retry
|
||||||
|
// churn is visible in the data, not just the bill.
|
||||||
|
async function withBackoff(fn, retry, deadline = Infinity, tries = 5) {
|
||||||
|
for (let attempt = 0; ; attempt++) {
|
||||||
|
// Checked before every attempt, not just before sleeps: once the case's
|
||||||
|
// ceiling has passed, an abandoned chain must not issue another call
|
||||||
|
// (e.g. a judge call after the app call consumed the whole ceiling).
|
||||||
|
if (Date.now() >= deadline) {
|
||||||
|
const e = new Error('wall-clock ceiling exceeded before attempt');
|
||||||
|
e.failure_class = 'timeout';
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
try { return await fn(); } catch (e) {
|
||||||
|
const status = e?.status ?? e?.response?.status;
|
||||||
|
const transient = status === 429 || status === 529 || (status >= 500 && status < 600)
|
||||||
|
|| /overloaded|rate.?limit/i.test(String(e?.message ?? ''));
|
||||||
|
if (!transient || attempt >= tries - 1) throw e;
|
||||||
|
const delay = Math.min(60_000, 1000 * 2 ** attempt) * (0.5 + Math.random());
|
||||||
|
// Never start a retry that would outlive the case's wall-clock ceiling -
|
||||||
|
// otherwise an abandoned chain keeps issuing API calls after the case failed.
|
||||||
|
if (Date.now() + delay >= deadline) throw e;
|
||||||
|
retry.count++;
|
||||||
|
await new Promise(r => setTimeout(r, delay));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hard per-case wall-clock ceiling, independent of stream liveness - a hung
|
||||||
|
// SSE stream can emit keepalives forever, defeating inactivity-based timers.
|
||||||
|
// The underlying call may keep running; the case fails and the slot is freed.
|
||||||
|
function withTimeout(promise, seconds, label) {
|
||||||
|
if (!(seconds > 0)) return promise;
|
||||||
|
let timer;
|
||||||
|
const ceiling = new Promise((_, reject) => {
|
||||||
|
timer = setTimeout(() => {
|
||||||
|
const e = new Error(`${label}: exceeded ${seconds}s wall-clock ceiling`);
|
||||||
|
e.failure_class = 'timeout';
|
||||||
|
reject(e);
|
||||||
|
}, seconds * 1000);
|
||||||
|
});
|
||||||
|
return Promise.race([promise, ceiling]).finally(() => clearTimeout(timer));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Case ids appear in file paths AND as the row/file join key the report uses,
|
||||||
|
// so rows, trace filenames, and frozen refs all carry the same path-safe id.
|
||||||
|
// When sanitization changes the id, a short content hash keeps distinct ids
|
||||||
|
// distinct ('case/1' vs 'case_1'); the original rides in meta.original_id.
|
||||||
|
function pathSafeId(id) {
|
||||||
|
const raw = String(id);
|
||||||
|
const cleaned = raw.replace(/[^\w.-]/g, '_');
|
||||||
|
// Idempotent by construction: anything already path-safe and within the
|
||||||
|
// length bound - including this function's own truncated+suffixed output -
|
||||||
|
// passes through unchanged. Long ids (URLs, prompt text as id) truncate to
|
||||||
|
// 120 chars plus an 8-hex hash of the full original, so they fail here, not
|
||||||
|
// at the trace write after the spend, and distinct ids stay distinct.
|
||||||
|
if (cleaned === raw && raw.length <= 129) return raw;
|
||||||
|
return `${cleaned.slice(0, 120)}-${createHash('sha256').update(raw).digest('hex').slice(0, 8)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const args = parseArgs(process.argv.slice(2));
|
||||||
|
const vdir = join(args.flow, args.variant);
|
||||||
|
mkdirSync(join(vdir, 'traces'), { recursive: true });
|
||||||
|
// _state.json is READ-ONLY here. The orchestrator owns it. Absent is fine
|
||||||
|
// (a baseline-only run has no loop state yet), but present-and-unparsable
|
||||||
|
// must not let the id-space gate below pass vacuously over a corrupt file.
|
||||||
|
const statePath = join(args.flow, '_state.json');
|
||||||
|
let st = {};
|
||||||
|
if (existsSync(statePath)) {
|
||||||
|
try { st = JSON.parse(readFileSync(statePath, 'utf8')) || {}; }
|
||||||
|
catch (e) { console.error(`${statePath} exists but is not valid JSON (${e?.message || e}) - fix it before spending a pass`); process.exit(2); }
|
||||||
|
}
|
||||||
|
checkHarness(statePath, st, args.approveHarness);
|
||||||
|
const ctx = { ...args, state: st };
|
||||||
|
|
||||||
|
// Resume: which (id, rep) pairs already have a row?
|
||||||
|
const resultsPath = join(vdir, 'results.jsonl');
|
||||||
|
const done = new Set();
|
||||||
|
if (existsSync(resultsPath))
|
||||||
|
for (const ln of readFileSync(resultsPath, 'utf8').split('\n')) {
|
||||||
|
if (!ln.trim()) continue;
|
||||||
|
try { const r = JSON.parse(ln); done.add(`${r.prompt_id}\0${r.rep}`); } catch {}
|
||||||
|
}
|
||||||
|
// Rows key on the path-safe id (see pathSafeId), so resume must too.
|
||||||
|
|
||||||
|
const cases = await loadCases();
|
||||||
|
// Validate the id space before spending anything: duplicate path-safe ids -
|
||||||
|
// including case-insensitive twins, which macOS/Windows filesystems collapse -
|
||||||
|
// would silently overwrite traces and frozen refs; and a _state.json split id
|
||||||
|
// that matches no case would silently shrink the scored denominator.
|
||||||
|
const seen = new Map();
|
||||||
|
for (const c of cases) {
|
||||||
|
const k = pathSafeId(c.id).toLowerCase();
|
||||||
|
if (seen.has(k)) {
|
||||||
|
console.error(`duplicate case id after sanitization: '${c.id}' collides with '${seen.get(k)}'`);
|
||||||
|
process.exit(2);
|
||||||
|
}
|
||||||
|
seen.set(k, c.id);
|
||||||
|
}
|
||||||
|
const safeIds = new Set(cases.map(c => pathSafeId(c.id)));
|
||||||
|
for (const sid of [...(st.train_ids ?? []), ...(st.val_ids ?? []), ...(st.test_ids ?? [])]) {
|
||||||
|
const s = String(sid); // the adapter joins with String() on both sides - numeric ids are fine
|
||||||
|
if (safeIds.has(s)) continue; // matches a loaded case - definitionally valid
|
||||||
|
if (s !== pathSafeId(s)) {
|
||||||
|
// Can never match a row: rows key on path-safe ids. This is the silent
|
||||||
|
// shrunken-denominator bug - fail before anything is spent.
|
||||||
|
console.error(`_state.json split id '${s}' is not a path-safe id - record split ids exactly as they appear in results.jsonl's prompt_id`);
|
||||||
|
process.exit(2);
|
||||||
|
}
|
||||||
|
// Well-formed but absent is legitimate (a trimmed top-K subset run) - note it, don't fail.
|
||||||
|
console.error(`note: split id '${s}' matches no loaded case (expected for a trimmed subset run)`);
|
||||||
|
}
|
||||||
|
const refDir = join(args.flow, 'baseline', 'ref');
|
||||||
|
const tasks = [];
|
||||||
|
for (const c of cases) for (let rep = 0; rep < args.reps; rep++) {
|
||||||
|
if (done.has(`${pathSafeId(c.id)}\0${rep}`)) continue;
|
||||||
|
tasks.push({ c, rep });
|
||||||
|
}
|
||||||
|
console.error(`[${args.variant}] ${tasks.length} of ${cases.length * args.reps} (id,rep) to run`);
|
||||||
|
|
||||||
|
let i = 0, ok = 0, fail = 0;
|
||||||
|
const errorsPath = join(vdir, 'errors.jsonl');
|
||||||
|
// A hard crash (power loss, ENOSPC) can leave a torn final line with no
|
||||||
|
// trailing newline; the next append would merge two rows into one permanently
|
||||||
|
// unparseable line. Isolate any fragment before appending anything.
|
||||||
|
for (const p of [resultsPath, errorsPath]) {
|
||||||
|
if (!existsSync(p)) continue;
|
||||||
|
const buf = readFileSync(p);
|
||||||
|
if (buf.length && buf[buf.length - 1] !== 0x0a) appendFileSync(p, '\n');
|
||||||
|
}
|
||||||
|
async function worker() {
|
||||||
|
while (i < tasks.length) {
|
||||||
|
const { c, rep } = tasks[i++];
|
||||||
|
const safeId = pathSafeId(c.id);
|
||||||
|
const t0 = Date.now();
|
||||||
|
let lastRun = null; // survives into the catch - billed spend on a failed attempt
|
||||||
|
let rowWritten = false; // set once the results row lands - the attempt is scored
|
||||||
|
const deadline = args.timeoutS > 0 ? t0 + args.timeoutS * 1000 : Infinity;
|
||||||
|
const appRetry = { count: 0 }, judgeRetry = { count: 0 };
|
||||||
|
try {
|
||||||
|
// One ceiling over the whole case - app call, identity check, and grading -
|
||||||
|
// so a hung judge stream can't hold the slot either.
|
||||||
|
const { run, g, latency_s } = await withTimeout((async () => {
|
||||||
|
let tAttempt = t0;
|
||||||
|
const run = await withBackoff(() => { tAttempt = Date.now(); return runCase(c, ctx); },
|
||||||
|
appRetry, deadline);
|
||||||
|
lastRun = run;
|
||||||
|
// latency_s = the final app attempt only; backoff sleeps, failed
|
||||||
|
// attempts, and judge time are excluded (retry counts are in meta).
|
||||||
|
const latency_s = (Date.now() - tAttempt) / 1000;
|
||||||
|
// Serving identity: fail loudly when the response was served by a model
|
||||||
|
// other than the one requested. Accept exact match or a documented
|
||||||
|
// alias->snapshot resolution - 'foo-latest'/'foo-0'/'foo' served as
|
||||||
|
// 'foo-20250101', 'foo@20250101', or 'foo-2025-01-01'. Anything else -
|
||||||
|
// another snapshot of the requested pin, a sibling model, or the bare
|
||||||
|
// base id ('foo-latest' served as 'foo', an unversioned echo that can
|
||||||
|
// hide snapshot drift across rounds) - fails the attempt. Non-Anthropic
|
||||||
|
// id schemes (e.g. Bedrock's 'anthropic.claude-...-v1:0') need their own
|
||||||
|
// rule here.
|
||||||
|
if (ctx.model && run.model && run.model !== ctx.model) {
|
||||||
|
const base = ctx.model.replace(/-latest$|-0$/, '');
|
||||||
|
const rest = String(run.model).startsWith(base)
|
||||||
|
? String(run.model).slice(base.length) : null;
|
||||||
|
if (!(rest != null && /^[-@](\d{8}|\d{4}-\d{2}-\d{2})$/.test(rest))) {
|
||||||
|
const e = new Error(`served model ${run.model} != requested ${ctx.model}`);
|
||||||
|
e.failure_class = 'serving_substitution';
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Frozen pairwise reference (never regenerated): baseline/ref/<id>.*
|
||||||
|
let ref = null;
|
||||||
|
if (args.variant !== 'baseline') {
|
||||||
|
const p = join(refDir, safeId);
|
||||||
|
for (const ext of ['', '.html', '.txt', '.json'])
|
||||||
|
if (existsSync(p + ext)) { ref = readFileSync(p + ext, 'utf8'); break; }
|
||||||
|
}
|
||||||
|
const g = await withBackoff(() => gradeCase(c, run, ref, ctx), judgeRetry, deadline);
|
||||||
|
return { run, g, latency_s };
|
||||||
|
})(), args.timeoutS, `${c.id} rep${rep}`);
|
||||||
|
const row = {
|
||||||
|
prompt_id: safeId, rep, prompt: c.prompt ?? c.input ?? c.id,
|
||||||
|
tags: c.tags, attachments: c.attachments,
|
||||||
|
meta: safeId !== String(c.id) || appRetry.count || judgeRetry.count
|
||||||
|
? { ...(c.meta ?? {}),
|
||||||
|
...(safeId !== String(c.id) ? { original_id: String(c.id) } : {}),
|
||||||
|
...(appRetry.count ? { retries: appRetry.count } : {}),
|
||||||
|
...(judgeRetry.count ? { judge_retries: judgeRetry.count } : {}) }
|
||||||
|
: c.meta,
|
||||||
|
model: run.model, usage: run.usage, stop_reason: run.stop_reason,
|
||||||
|
judge_model: g.judge_model ?? run.judge_model,
|
||||||
|
judge_usage: g.judge_usage ?? run.judge_usage,
|
||||||
|
latency_s, ...perfFrom(run),
|
||||||
|
grade: g.grade, explanation: g.explanation,
|
||||||
|
};
|
||||||
|
appendFileSync(resultsPath, JSON.stringify(row) + '\n');
|
||||||
|
rowWritten = true; // past this point the attempt is scored - a later throw (trace write, ref freeze) must not also append an error row
|
||||||
|
if (run.transcript)
|
||||||
|
writeFileSync(join(vdir, 'traces', `${safeId}_rep${rep}.json`),
|
||||||
|
JSON.stringify(run.transcript, null, 2));
|
||||||
|
// For pairwise: on the baseline run, freeze the reference output once.
|
||||||
|
if (args.variant === 'baseline' && run.output != null && !existsSync(join(refDir, safeId))) {
|
||||||
|
mkdirSync(refDir, { recursive: true });
|
||||||
|
writeFileSync(join(refDir, safeId),
|
||||||
|
typeof run.output === 'string' ? run.output : JSON.stringify(run.output));
|
||||||
|
}
|
||||||
|
ok++;
|
||||||
|
} catch (e) {
|
||||||
|
fail++;
|
||||||
|
if (rowWritten) {
|
||||||
|
// The attempt scored; only a post-row write (trace, ref) failed. An error
|
||||||
|
// row here would double-count the billed usage under the budget rule.
|
||||||
|
console.error(` [${args.variant}] ${c.id} rep${rep} scored, but a post-row write failed: ${e?.message || e}`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// Failed attempts are data too - but they must not occupy the (case, rep)
|
||||||
|
// slot in results.jsonl, or resume would never re-run them.
|
||||||
|
appendFileSync(errorsPath, JSON.stringify({
|
||||||
|
prompt_id: safeId, rep,
|
||||||
|
...(safeId !== String(c.id) ? { original_id: String(c.id) } : {}),
|
||||||
|
failure_class: e?.failure_class ?? 'error',
|
||||||
|
error: String(e?.message || e),
|
||||||
|
retries: appRetry.count, judge_retries: judgeRetry.count,
|
||||||
|
// Billed-but-failed spend stays countable: when the app call completed
|
||||||
|
// before the failure (e.g. a served-model mismatch, a judge-stage
|
||||||
|
// ceiling), carry its identity and usage on the error row.
|
||||||
|
model: lastRun?.model, usage: lastRun?.usage,
|
||||||
|
judge_model: e?.judge_model ?? lastRun?.judge_model,
|
||||||
|
judge_usage: e?.judge_usage ?? lastRun?.judge_usage,
|
||||||
|
latency_s: (Date.now() - t0) / 1000,
|
||||||
|
}) + '\n');
|
||||||
|
console.error(` [${args.variant}] ${c.id} rep${rep} FAILED: ${e?.message || e}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// One progress line every 30s (and to <vdir>/progress.txt) so "how far along
|
||||||
|
// is it?" is answerable from the background shell's output or one file read,
|
||||||
|
// without the orchestrator parsing results.jsonl mid-write. ETA is a plain
|
||||||
|
// rate extrapolation from this pass.
|
||||||
|
const t0 = Date.now();
|
||||||
|
const progress = () => {
|
||||||
|
const done = ok + fail, total = tasks.length;
|
||||||
|
const el = (Date.now() - t0) / 1000;
|
||||||
|
const eta = done ? Math.round((el / done) * (total - done)) : null;
|
||||||
|
const line = `[${args.variant}] ${done}/${total} done (${ok} ok, ${fail} failed), `
|
||||||
|
+ `${Math.round(el)}s elapsed` + (eta != null ? `, ~${eta}s left` : '');
|
||||||
|
console.error(line);
|
||||||
|
try { writeFileSync(join(vdir, 'progress.txt'), line + '\n'); } catch {}
|
||||||
|
};
|
||||||
|
const tick = setInterval(progress, 30_000);
|
||||||
|
await Promise.all(Array.from({ length: Math.max(1, args.concurrency) }, worker));
|
||||||
|
clearInterval(tick); progress();
|
||||||
|
console.error(`[${args.variant}] done - ${ok} ok, ${fail} failed -> ${resultsPath}`);
|
||||||
|
process.exit(fail ? 1 : 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
main();
|
||||||
@@ -18,7 +18,7 @@ This file contains WebFetch URLs for fetching current information from platform.
|
|||||||
| Models Overview | `https://platform.claude.com/docs/en/about-claude/models/overview.md` | "Extract current model IDs, context windows, and pricing for all Claude models" |
|
| Models Overview | `https://platform.claude.com/docs/en/about-claude/models/overview.md` | "Extract current model IDs, context windows, and pricing for all Claude models" |
|
||||||
| Migration Guide | `https://platform.claude.com/docs/en/about-claude/models/migration-guide.md` | "Extract breaking changes, deprecated parameters, and per-model migration steps when moving to a newer Claude model" |
|
| Migration Guide | `https://platform.claude.com/docs/en/about-claude/models/migration-guide.md` | "Extract breaking changes, deprecated parameters, and per-model migration steps when moving to a newer Claude model" |
|
||||||
| Introducing Claude Fable 5 | `https://platform.claude.com/docs/en/about-claude/models/introducing-claude-fable-5.md` | "Extract capabilities, API changes, and availability stages for Claude Fable 5 and Claude Mythos 5" |
|
| Introducing Claude Fable 5 | `https://platform.claude.com/docs/en/about-claude/models/introducing-claude-fable-5.md` | "Extract capabilities, API changes, and availability stages for Claude Fable 5 and Claude Mythos 5" |
|
||||||
| Pricing | `https://platform.claude.com/docs/en/pricing.md` | "Extract current pricing per million tokens for input and output" |
|
| Pricing | `https://platform.claude.com/docs/en/about-claude/pricing.md` | "Extract current pricing per million tokens for input and output" |
|
||||||
| Cost Optimization | `https://platform.claude.com/docs/en/about-claude/models/optimizing-for-cost-and-intelligence.md` | "Extract measured cost levers, cache and batch savings, effort and model cost-per-task comparisons, budget controls, and multi-model guidance" |
|
| Cost Optimization | `https://platform.claude.com/docs/en/about-claude/models/optimizing-for-cost-and-intelligence.md` | "Extract measured cost levers, cache and batch savings, effort and model cost-per-task comparisons, budget controls, and multi-model guidance" |
|
||||||
|
|
||||||
### Core Features
|
### Core Features
|
||||||
@@ -69,13 +69,13 @@ This file contains WebFetch URLs for fetching current information from platform.
|
|||||||
| Topic | URL | Extraction Prompt |
|
| Topic | URL | Extraction Prompt |
|
||||||
| -------------- | -------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
|
| -------------- | -------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
|
||||||
| Code Execution | `https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool.md` | "Extract code execution tool setup, file upload, container reuse, and response handling" |
|
| Code Execution | `https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool.md` | "Extract code execution tool setup, file upload, container reuse, and response handling" |
|
||||||
| Computer Use | `https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use.md` | "Extract computer use tool setup, capabilities, and implementation examples" |
|
| Computer Use | `https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool.md` | "Extract the computer_toolset_20260801 setup (configs, member tools, batch actions, toolset_name on results), the Compatibility matrix, and the migration steps from computer_20251124" |
|
||||||
| Bash Tool | `https://platform.claude.com/docs/en/agents-and-tools/tool-use/bash-tool.md` | "Extract bash tool schema, reference implementation, and security considerations" |
|
| Bash Tool | `https://platform.claude.com/docs/en/agents-and-tools/tool-use/bash-tool.md` | "Extract bash tool schema, reference implementation, and security considerations" |
|
||||||
| Text Editor | `https://platform.claude.com/docs/en/agents-and-tools/tool-use/text-editor-tool.md` | "Extract text editor tool commands, schema, and reference implementation" |
|
| Text Editor | `https://platform.claude.com/docs/en/agents-and-tools/tool-use/text-editor-tool.md` | "Extract text editor tool commands, schema, and reference implementation" |
|
||||||
| Memory Tool | `https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool.md` | "Extract memory tool commands, directory structure, and implementation patterns" |
|
| Memory Tool | `https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool.md` | "Extract memory tool commands, directory structure, and implementation patterns" |
|
||||||
| Tool Search | `https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool.md` | "Extract tool search setup, when to use, and cache interaction" |
|
| Tool Search | `https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool.md` | "Extract tool search setup, when to use, and cache interaction" |
|
||||||
| Programmatic Tool Calling | `https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling.md` | "Extract PTC setup, script execution model, and tool invocation from code" |
|
| Programmatic Tool Calling | `https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling.md` | "Extract PTC setup, script execution model, and tool invocation from code" |
|
||||||
| Skills | `https://platform.claude.com/docs/en/agents-and-tools/skills.md` | "Extract skill folder structure, SKILL.md format, and loading behavior" |
|
| Skills | `https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview.md` | "Extract skill folder structure, SKILL.md format, and loading behavior" |
|
||||||
| Skills Guide | `https://platform.claude.com/docs/en/build-with-claude/skills-guide.md` | "Extract the Skills API (/v1/skills) usage and the migration steps from skills-2025-10-02" |
|
| Skills Guide | `https://platform.claude.com/docs/en/build-with-claude/skills-guide.md` | "Extract the Skills API (/v1/skills) usage and the migration steps from skills-2025-10-02" |
|
||||||
|
|
||||||
### Advanced Features
|
### Advanced Features
|
||||||
@@ -124,7 +124,7 @@ The `ant` CLI provides terminal access to the Claude API. Every API resource is
|
|||||||
|
|
||||||
| Topic | URL | Extraction Prompt |
|
| Topic | URL | Extraction Prompt |
|
||||||
| ------------- | ------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
|
| ------------- | ------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
|
||||||
| Anthropic CLI | `https://platform.claude.com/docs/en/api/sdks/cli.md` | "Extract CLI install, authentication, command structure, and the beta:agents/environments/sessions commands" |
|
| Anthropic CLI | `https://platform.claude.com/docs/en/cli-sdks-libraries/cli/quickstart.md` | "Extract CLI install, authentication, command structure, and sending a first request" |
|
||||||
| `ant beta:sessions connect` | `https://platform.claude.com/docs/en/cli-sdks-libraries/cli/sessions-connect.md` | "Extract the interactive session viewer: keybindings, tool-call allow/deny prompt, `--web` local viewer and its URL/lifetime rules" |
|
| `ant beta:sessions connect` | `https://platform.claude.com/docs/en/cli-sdks-libraries/cli/sessions-connect.md` | "Extract the interactive session viewer: keybindings, tool-call allow/deny prompt, `--web` local viewer and its URL/lifetime rules" |
|
||||||
| Authentication overview | `https://platform.claude.com/docs/en/manage-claude/authentication.md` | "Extract the credential options (API keys, interactive OAuth login, Workload Identity Federation) and when to use each" |
|
| Authentication overview | `https://platform.claude.com/docs/en/manage-claude/authentication.md` | "Extract the credential options (API keys, interactive OAuth login, Workload Identity Federation) and when to use each" |
|
||||||
| WIF reference | `https://platform.claude.com/docs/en/manage-claude/wif-reference.md` | "Extract credential precedence order, the profile configuration file schema, and the configuration directory layout" |
|
| WIF reference | `https://platform.claude.com/docs/en/manage-claude/wif-reference.md` | "Extract credential precedence order, the profile configuration file schema, and the configuration directory layout" |
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ Their description does the interview's work. Draft the agent config from it and
|
|||||||
|
|
||||||
- **Tools** - enable the full prebuilt toolset by default (`agent_toolset_20260401`: `bash`, `read`, `write`, `edit`, `glob`, `grep`, `web_fetch`, `web_search`). **Suggest MCP servers** for any third-party service the job names (GitHub, Linear, Slack, ...) - and flag the credential each one implies as you suggest it ("Linear MCP -> you'll need a Linear API token at kickoff"), so §4's auth step is a formality, not a surprise. Collection itself waits for §4. Custom tools only if the user's own app must answer calls (name, description, input schema - their handler code is theirs; don't generate it).
|
- **Tools** - enable the full prebuilt toolset by default (`agent_toolset_20260401`: `bash`, `read`, `write`, `edit`, `glob`, `grep`, `web_fetch`, `web_search`). **Suggest MCP servers** for any third-party service the job names (GitHub, Linear, Slack, ...) - and flag the credential each one implies as you suggest it ("Linear MCP -> you'll need a Linear API token at kickoff"), so §4's auth step is a formality, not a surprise. Collection itself waits for §4. Custom tools only if the user's own app must answer calls (name, description, input schema - their handler code is theirs; don't generate it).
|
||||||
- **Skills** - **suggest** prebuilt `xlsx`/`docx`/`pptx`/`pdf` when the job produces those artifacts; custom by `skill_id` (max 20 total per agent, prebuilt + custom combined).
|
- **Skills** - **suggest** prebuilt `xlsx`/`docx`/`pptx`/`pdf` when the job produces those artifacts; custom by `skill_id` (max 20 total per agent, prebuilt + custom combined).
|
||||||
- **Outcome** - if the description implies checkable "done" criteria (or you can elicit them in the follow-up: not "a good report" but "a CSV with a numeric `price` column per SKU"), **suggest an Outcome kickoff** - the harness grades and iterates against a rubric (`shared/managed-agents-outcomes.md`).
|
- **Outcome - the default kickoff for any job with a deliverable.** If the job produces something checkable (an artifact, a report, a PR, a dataset), draft a starter rubric from the description - explicit, independently gradeable criteria: not "a good report" but "a CSV with a numeric `price` column per SKU" - and propose it inline with the config; the harness grades and iterates against it (`shared/managed-agents-outcomes.md`). The user not having a rubric is not a reason to skip this - drafting one is your job; mark it as a starter to tune. Fall back to a conversational kickoff only when the job is genuinely interactive (a chat surface, human-in-the-loop steering).
|
||||||
- **On-hand resources** - repos on disk (`github_repository`: URL, optional `mount_path`/`checkout`; token comes in §4), files to seed (Files API upload -> `{type: "file", file_id, mount_path}`; read-only), if the job references them.
|
- **On-hand resources** - repos on disk (`github_repository`: URL, optional `mount_path`/`checkout`; token comes in §4), files to seed (Files API upload -> `{type: "file", file_id, mount_path}`; read-only), if the job references them.
|
||||||
- **Model** - default `claude-opus-5`; `claude-fable-5-1` for the hardest long-horizon work (`shared/model-migration.md` -> Migrating to Claude Fable 5.1).
|
- **Model** - default `claude-opus-5`; `claude-fable-5-1` for the hardest long-horizon work (`shared/model-migration.md` -> Migrating to Claude Fable 5.1).
|
||||||
|
|
||||||
@@ -44,9 +44,9 @@ Usually zero or one question:
|
|||||||
|
|
||||||
**Silent viability gate - run this yourself before emitting anything; surface only the gaps.** Walk the job clause by clause: every verb maps to an enabled tool or MCP server ("open a PR" -> GitHub MCP, not just the mount); every MCP server and repo mount has its credential from the auth step; every external host is reachable under the networking choice; every file/repo/dataset the job references is mounted; "done" is checkable. If something's missing, say so and resolve it - don't emit a config you already know is under-resourced.
|
**Silent viability gate - run this yourself before emitting anything; surface only the gaps.** Walk the job clause by clause: every verb maps to an enabled tool or MCP server ("open a PR" -> GitHub MCP, not just the mount); every MCP server and repo mount has its credential from the auth step; every external host is reachable under the networking choice; every file/repo/dataset the job references is mounted; "done" is checkable. If something's missing, say so and resolve it - don't emit a config you already know is under-resourced.
|
||||||
|
|
||||||
**Kickoff - pick one, never both:**
|
**Kickoff - pick one, never both. Outcome is the default:**
|
||||||
- `user.message` - conversational.
|
- `user.define_outcome` + rubric - the default whenever the job has a deliverable (§2 drafts the rubric); the harness iterates and grades until the rubric passes.
|
||||||
- `user.define_outcome` + rubric - when §2 settled on an Outcome; the harness iterates and grades until the rubric passes.
|
- `user.message` - only for genuinely conversational sessions.
|
||||||
- **Scheduled shape?** Skip per-session kickoff entirely - create a **deployment** (`deployments.create()` with `schedule` + `initial_events`); each firing creates the session autonomously. See `shared/managed-agents-scheduled-deployments.md`.
|
- **Scheduled shape?** Skip per-session kickoff entirely - create a **deployment** (`deployments.create()` with `schedule` + `initial_events`); each firing creates the session autonomously. See `shared/managed-agents-scheduled-deployments.md`.
|
||||||
|
|
||||||
Mechanics to bake into the runtime code: session creation resolves resources (a bad mount surfaces there, before tokens) but does not itself provision the sandbox; open the event stream *before* sending the kickoff; break on `session.status_terminated`, or `session.status_idle` with any non-`requires_action` `stop_reason` - terminal, or `budget_reached`, which is not terminal (only a budget change/removal resumes it) (`shared/managed-agents-client-patterns.md` Pattern 5); usage lands on `span.model_request_end`; artifacts land in `/mnt/session/outputs/` (`files.list({scope_id: session.id, ...})`).
|
Mechanics to bake into the runtime code: session creation resolves resources (a bad mount surfaces there, before tokens) but does not itself provision the sandbox; open the event stream *before* sending the kickoff; break on `session.status_terminated`, or `session.status_idle` with any non-`requires_action` `stop_reason` - terminal, or `budget_reached`, which is not terminal (only a budget change/removal resumes it) (`shared/managed-agents-client-patterns.md` Pattern 5); usage lands on `span.model_request_end`; artifacts land in `/mnt/session/outputs/` (`files.list({scope_id: session.id, ...})`).
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ An **outcome** elevates a session from *conversation* to *work*: you state what
|
|||||||
|
|
||||||
The SDK sets the `managed-agents-2026-04-01` beta header automatically on all `client.beta.sessions.*` calls; no additional header is required for outcomes.
|
The SDK sets the `managed-agents-2026-04-01` beta header automatically on all `client.beta.sessions.*` calls; no additional header is required for outcomes.
|
||||||
|
|
||||||
|
**Codegen default:** when generating Managed Agents client code for a task with a deliverable (an artifact, a report, a PR, a dataset), kick the session off with `user.define_outcome` rather than `user.message` - draft a starter rubric from the task description and mark it for the user to tune. Reserve plain `user.message` kickoffs for genuinely conversational sessions.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## The `user.define_outcome` event
|
## The `user.define_outcome` event
|
||||||
@@ -42,7 +44,7 @@ client.beta.sessions.events.send(
|
|||||||
|
|
||||||
The event is echoed back on the stream with a server-assigned `outcome_id` and `processed_at`.
|
The event is echoed back on the stream with a server-assigned `outcome_id` and `processed_at`.
|
||||||
|
|
||||||
> **Writing rubrics.** Use explicit, gradeable criteria ("CSV has a numeric `price` column"), not vibes ("data looks good") - the grader scores each criterion independently, so vague criteria produce noisy loops. If you don't have a rubric, have Claude analyze a known-good artifact and turn that analysis into one.
|
> **Writing rubrics.** Use explicit, gradeable criteria ("CSV has a numeric `price` column"), not vibes ("data looks good") - the grader scores each criterion independently, so vague criteria produce noisy loops. If you don't have a rubric, have Claude analyze a known-good artifact and turn that analysis into one. When generating code for a user who supplied no rubric, draft one yourself from their task description - 5-10 concrete criteria covering the artifact's format, required content, and quality floor - and comment it as a starter rubric to tune; never omit the outcome because the rubric wasn't handed to you.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ Requires the `managed-agents-2026-04-01` beta header (the SDK sets it automatica
|
|||||||
A deployment bundles everything a session needs (agent, environment, optional files / GitHub / memory stores / vaults) plus a `schedule` and the `initial_events` that kick off each run:
|
A deployment bundles everything a session needs (agent, environment, optional files / GitHub / memory stores / vaults) plus a `schedule` and the `initial_events` that kick off each run:
|
||||||
|
|
||||||
- `agent` and `environment_id` are required - same shapes as `sessions.create` (see `shared/managed-agents-core.md`). A deployment targeting a **self-hosted** environment can attach `memory_store` resources (SDK worker required - `shared/managed-agents-self-hosted-sandboxes.md` § Memory stores); `file` and `github_repository` resources need a cloud environment. The Console deployment form doesn't offer memory stores for self-hosted environments - attach them via the API/SDK.
|
- `agent` and `environment_id` are required - same shapes as `sessions.create` (see `shared/managed-agents-core.md`). A deployment targeting a **self-hosted** environment can attach `memory_store` resources (SDK worker required - `shared/managed-agents-self-hosted-sandboxes.md` § Memory stores); `file` and `github_repository` resources need a cloud environment. The Console deployment form doesn't offer memory stores for self-hosted environments - attach them via the API/SDK.
|
||||||
- `initial_events` must contain at least one starting event - a `user.message` **or** a `user.define_outcome`. (A deployment's `initial_events` also accepts `system.message`, which a session's does not.)
|
- `initial_events` must contain at least one starting event - a `user.message` **or** a `user.define_outcome`. Same default as sessions: a scheduled run that produces a deliverable (the weekly report, the compliance scan's findings file, a dataset) starts with `user.define_outcome` plus a drafted starter rubric (`shared/managed-agents-outcomes.md`); use `user.message` only when the run is genuinely conversational or has no checkable output. (A deployment's `initial_events` also accepts `system.message`, which a session's does not.)
|
||||||
- `schedule` takes a cron `expression` and an IANA `timezone`. Minute-level granularity is the maximum.
|
- `schedule` takes a cron `expression` and an IANA `timezone`. Minute-level granularity is the maximum.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
@@ -27,7 +27,10 @@ For the latest, authoritative version (with code samples in every supported lang
|
|||||||
| Claude Fable 5.1 Migration Checklist | The required vs optional items for Claude Fable 5.1, tagged `[BLOCKS]` / `[TUNE]` |
|
| Claude Fable 5.1 Migration Checklist | The required vs optional items for Claude Fable 5.1, tagged `[BLOCKS]` / `[TUNE]` |
|
||||||
| Migrating to Claude Fable 5.1 from Claude Fable 5 | Migrating Claude Fable 5 / Claude Opus 5 / Claude Mythos 5 -> Claude Fable 5.1 or Claude Mythos 5.1 (forced `tool_choice` 400s; "preserved thinking" - model-bound blocks and the history-editing check; per-message effort; append-only per-turn reminders; `display: "updates"` progress updates; cheaper cache reads; behavioral re-tuning) |
|
| Migrating to Claude Fable 5.1 from Claude Fable 5 | Migrating Claude Fable 5 / Claude Opus 5 / Claude Mythos 5 -> Claude Fable 5.1 or Claude Mythos 5.1 (forced `tool_choice` 400s; "preserved thinking" - model-bound blocks and the history-editing check; per-message effort; append-only per-turn reminders; `display: "updates"` progress updates; cheaper cache reads; behavioral re-tuning) |
|
||||||
| Claude Fable 5.1 from Claude Fable 5 Migration Checklist | The required vs optional items for the Claude Fable 5 -> Claude Fable 5.1 move, tagged `[BLOCKS]` / `[TUNE]` |
|
| Claude Fable 5.1 from Claude Fable 5 Migration Checklist | The required vs optional items for the Claude Fable 5 -> Claude Fable 5.1 move, tagged `[BLOCKS]` / `[TUNE]` |
|
||||||
|
| Migrating to Claude Opus 5.5 | Migrating Claude Opus 5 -> Claude Opus 5.5 (thinking can't be disabled; forced `tool_choice` 400s; preserved thinking; computer use via the toolset only; progress updates as thinking blocks; default effort `medium`; broader classifiers; effort tuning + prompting guidance) |
|
||||||
|
| Claude Opus 5.5 Migration Checklist | The required vs optional items for Claude Opus 5.5, tagged `[BLOCKS]` / `[TUNE]` |
|
||||||
| Verify the Migration | After edits - runtime spot-check |
|
| Verify the Migration | After edits - runtime spot-check |
|
||||||
|
| Ground the migration with an eval | User reports a behavioral regression on the new model |
|
||||||
|
|
||||||
**TL;DR:** Change the model ID string. If you were using `budget_tokens`, switch to `thinking: {type: "adaptive"}`. If you were using assistant prefills, they 400 on both Opus 4.6 and Sonnet 4.6 - switch to one of the prefill replacements (most often `output_config.format`; see the table in Breaking Changes by Source Model). If you're moving from Sonnet 4.5 to Sonnet 4.6, set `effort` explicitly - 4.6 defaults to `high`. Remove the `effort-2025-11-24` and `fine-grained-tool-streaming-2025-05-14` beta headers (GA on 4.6); remove `interleaved-thinking-2025-05-14` once you're on adaptive thinking (keep it only while using the transitional `budget_tokens` escape hatch). Then drop back from `client.beta.messages.create` to `client.messages.create`. Dial back any aggressive "CRITICAL: YOU MUST" tool instructions; 4.6 follows the system prompt much more closely.
|
**TL;DR:** Change the model ID string. If you were using `budget_tokens`, switch to `thinking: {type: "adaptive"}`. If you were using assistant prefills, they 400 on both Opus 4.6 and Sonnet 4.6 - switch to one of the prefill replacements (most often `output_config.format`; see the table in Breaking Changes by Source Model). If you're moving from Sonnet 4.5 to Sonnet 4.6, set `effort` explicitly - 4.6 defaults to `high`. Remove the `effort-2025-11-24` and `fine-grained-tool-streaming-2025-05-14` beta headers (GA on 4.6); remove `interleaved-thinking-2025-05-14` once you're on adaptive thinking (keep it only while using the transitional `budget_tokens` escape hatch). Then drop back from `client.beta.messages.create` to `client.messages.create`. Dial back any aggressive "CRITICAL: YOU MUST" tool instructions; 4.6 follows the system prompt much more closely.
|
||||||
|
|
||||||
@@ -75,7 +78,7 @@ Not every file that contains the old model ID is a **caller** of the API. Before
|
|||||||
| 1 | **Calls the API/SDK** | `client.messages.create(model=...)`, `anthropic.Anthropic()`, request payloads | Swap the model ID **and** apply the breaking-change checklist for the target version (below). |
|
| 1 | **Calls the API/SDK** | `client.messages.create(model=...)`, `anthropic.Anthropic()`, request payloads | Swap the model ID **and** apply the breaking-change checklist for the target version (below). |
|
||||||
| 2 | **Defines or serves the model** | Model registries, OpenAPI specs, routing/queue configs, model-policy enums, generated catalogs | The old entry **stays** (the model is still served). Ask whether to (a) add the new model alongside, (b) leave alone, or (c) retire the old model - never blind-replace. **If you can't ask, default to (a): add the new model alongside and flag it** - replacing would de-register a model that's still in production. |
|
| 2 | **Defines or serves the model** | Model registries, OpenAPI specs, routing/queue configs, model-policy enums, generated catalogs | The old entry **stays** (the model is still served). Ask whether to (a) add the new model alongside, (b) leave alone, or (c) retire the old model - never blind-replace. **If you can't ask, default to (a): add the new model alongside and flag it** - replacing would de-register a model that's still in production. |
|
||||||
| 3 | **References the ID as an opaque string** | UI fallback constants, capability-gate substring checks, generic test fixtures, label parsers, env defaults | Usually swap the string and verify any parser/regex/substring match handles the new ID - but check the sub-cases below first. |
|
| 3 | **References the ID as an opaque string** | UI fallback constants, capability-gate substring checks, generic test fixtures, label parsers, env defaults | Usually swap the string and verify any parser/regex/substring match handles the new ID - but check the sub-cases below first. |
|
||||||
| 4 | **Suffixed variant ID** | `claude-<model>-<suffix>` like `-fast`, `-1024k`, `-200k`, `[1m]`, dated snapshots | These are deployment/routing identifiers, not the public model ID. **Do not assume a new-model equivalent exists.** Verify in the registry first; if absent, leave the string alone and flag it. **Exception: `-fast` strings (e.g. `claude-opus-4-6-fast`) are handled by the Fast Mode section below**, which rewrites them to Opus 4.8 plus `speed="fast"` and the `fast-mode-2026-02-01` beta rather than leaving them in place. |
|
| 4 | **Suffixed variant ID** | `claude-<model>-<suffix>` like `-fast`, `-1024k`, `-200k`, `[1m]`, dated snapshots | These are deployment/routing identifiers, not the public model ID. **Do not assume a new-model equivalent exists.** Verify in the registry first; if absent, leave the string alone and flag it. **Exception: `-fast` strings (e.g. `claude-opus-4-6-fast`) are handled by the Fast Mode section below**, which rewrites them to Claude Opus 5 plus `speed="fast"` and the `fast-mode-2026-02-01` beta rather than leaving them in place. |
|
||||||
|
|
||||||
**Bucket 3 sub-cases - before swapping a string reference, check:**
|
**Bucket 3 sub-cases - before swapping a string reference, check:**
|
||||||
|
|
||||||
@@ -169,14 +172,14 @@ If you're applying several prompt-tuning edits at once, offer them as a short li
|
|||||||
|
|
||||||
1. **Confirm the target model ID.** Use only the exact strings from `shared/models.md` - do not append date suffixes to aliases (`claude-opus-4-6`, not `claude-opus-4-6-20251101`). Guessing an ID will 404.
|
1. **Confirm the target model ID.** Use only the exact strings from `shared/models.md` - do not append date suffixes to aliases (`claude-opus-4-6`, not `claude-opus-4-6-20251101`). Guessing an ID will 404.
|
||||||
2. **Check which features your code uses** with this checklist:
|
2. **Check which features your code uses** with this checklist:
|
||||||
- `thinking: {type: "enabled", budget_tokens: N}` -> migrate to adaptive thinking on Opus 4.6 / Sonnet 4.6 (still functional but deprecated)
|
- `thinking: {type: "enabled", budget_tokens: N}` -> migrate to adaptive thinking on Opus 4.6 / Sonnet 4.6 (still functional but deprecated)
|
||||||
- Assistant-turn prefills (`messages` ending with `role: "assistant"`) -> must change on Opus 4.6 / Sonnet 4.6 (returns 400)
|
- Assistant-turn prefills (`messages` ending with `role: "assistant"`) -> must change on Opus 4.6 / Sonnet 4.6 (returns 400)
|
||||||
- `output_format` parameter on `messages.create()` -> must change on all models (deprecated API-wide)
|
- `output_format` parameter on `messages.create()` -> must change on all models (deprecated API-wide)
|
||||||
- `max_tokens > ~16000` -> must stream on any model (above ~16K risks SDK HTTP timeouts). When streaming, every current model reaches 128K except Haiku 4.5, which caps at 64K
|
- `max_tokens > ~16000` -> must stream on any model (above ~16K risks SDK HTTP timeouts). When streaming, every current model reaches 128K except Haiku 4.5, which caps at 64K
|
||||||
- Beta headers `effort-2025-11-24`, `fine-grained-tool-streaming-2025-05-14`, `interleaved-thinking-2025-05-14` -> GA on 4.6, remove them and switch from `client.beta.messages.create` to `client.messages.create`
|
- Beta headers `effort-2025-11-24`, `fine-grained-tool-streaming-2025-05-14`, `interleaved-thinking-2025-05-14` -> GA on 4.6, remove them and switch from `client.beta.messages.create` to `client.messages.create`
|
||||||
- Moving Sonnet 4.5 -> Sonnet 4.6 with no `effort` set -> 4.6 defaults to `high`, which may change your latency/cost profile
|
- Moving Sonnet 4.5 -> Sonnet 4.6 with no `effort` set -> 4.6 defaults to `high`, which may change your latency/cost profile
|
||||||
- System prompts with `CRITICAL`, `MUST`, `If in doubt, use X` language -> likely to overtrigger on 4.6 (see Prompt-Behavior Changes)
|
- System prompts with `CRITICAL`, `MUST`, `If in doubt, use X` language -> likely to overtrigger on 4.6 (see Prompt-Behavior Changes)
|
||||||
- Coming from 3.x / 4.0 / 4.1: also check sampling params (`temperature` + `top_p`), tool versions (`text_editor_20250728`), `refusal` + `model_context_window_exceeded` stop reasons, trailing-newline tool-param handling
|
- Coming from 3.x / 4.0 / 4.1: also check sampling params (`temperature` + `top_p`), tool versions (`text_editor_20250728`), `refusal` + `model_context_window_exceeded` stop reasons, trailing-newline tool-param handling
|
||||||
3. **Test on a single request first.** Run one call against the new model, inspect the response, then roll out.
|
3. **Test on a single request first.** Run one call against the new model, inspect the response, then roll out.
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -188,6 +191,7 @@ If you're applying several prompt-tuning edits at once, offer them as a short li
|
|||||||
| Claude Mythos Preview (`claude-mythos-preview`) | `claude-mythos-5-1` (Project Glasswing successor) or `claude-fable-5-1` (GA) | Same tokenizer family - mostly a model-ID swap; remove `thinking` config and prefill; see Migrating to Claude Fable 5.1 |
|
| Claude Mythos Preview (`claude-mythos-preview`) | `claude-mythos-5-1` (Project Glasswing successor) or `claude-fable-5-1` (GA) | Same tokenizer family - mostly a model-ID swap; remove `thinking` config and prefill; see Migrating to Claude Fable 5.1 |
|
||||||
| Claude Fable 5 (`claude-fable-5`) | `claude-fable-5-1` | Same tier, same per-token price, same tokenizer; three breaking changes (forced `tool_choice` 400s, "preserved thinking") - see Migrating to Claude Fable 5.1 from Claude Fable 5 |
|
| Claude Fable 5 (`claude-fable-5`) | `claude-fable-5-1` | Same tier, same per-token price, same tokenizer; three breaking changes (forced `tool_choice` 400s, "preserved thinking") - see Migrating to Claude Fable 5.1 from Claude Fable 5 |
|
||||||
| Claude Mythos 5 (`claude-mythos-5`) | `claude-mythos-5-1` | Same path as claude-fable-5 -> claude-fable-5-1; see § Claude Mythos 5.1 under Migrating to Claude Fable 5.1 from Claude Fable 5 |
|
| Claude Mythos 5 (`claude-mythos-5`) | `claude-mythos-5-1` | Same path as claude-fable-5 -> claude-fable-5-1; see § Claude Mythos 5.1 under Migrating to Claude Fable 5.1 from Claude Fable 5 |
|
||||||
|
| Claude Opus 5 (`claude-opus-5`) | `claude-opus-5-5` - only when the user names Claude Opus 5.5 (launching) | Lower price ($4 / $20 vs $5 / $25), same context window and tokenizer; four breaking changes (thinking can't be disabled, forced `tool_choice` 400s, preserved thinking, computer use via the toolset only) - see Migrating to Claude Opus 5.5 |
|
||||||
| Opus 4.8 | `claude-opus-5` | The current Opus. Two breaking changes (thinking on by default; disabling thinking capped at `high` effort) plus prompt re-tuning - see Migrating to Claude Opus 5 |
|
| Opus 4.8 | `claude-opus-5` | The current Opus. Two breaking changes (thinking on by default; disabling thinking capped at `high` effort) plus prompt re-tuning - see Migrating to Claude Opus 5 |
|
||||||
| Opus 4.7 | `claude-opus-5` | Apply the Opus 4.8 section (prompt re-tuning, no new breaking changes), then the Claude Opus 5 section |
|
| Opus 4.7 | `claude-opus-5` | Apply the Opus 4.8 section (prompt re-tuning, no new breaking changes), then the Claude Opus 5 section |
|
||||||
| Opus 4.6 | `claude-opus-5` | Apply the Opus 4.7 breaking changes, then 4.8 re-tuning, then the Claude Opus 5 section |
|
| Opus 4.6 | `claude-opus-5` | Apply the Opus 4.7 breaking changes, then 4.8 re-tuning, then the Claude Opus 5 section |
|
||||||
@@ -196,7 +200,7 @@ If you're applying several prompt-tuning edits at once, offer them as a short li
|
|||||||
| Sonnet 4.0 / 4.5 / 3.7 / 3.5 | `claude-sonnet-5` | Apply the Sonnet 4.6 changes first, then the Claude Sonnet 5 section |
|
| Sonnet 4.0 / 4.5 / 3.7 / 3.5 | `claude-sonnet-5` | Apply the Sonnet 4.6 changes first, then the Claude Sonnet 5 section |
|
||||||
| Haiku 3 / 3.5 | `claude-haiku-4-5` | Fastest and most cost-effective |
|
| Haiku 3 / 3.5 | `claude-haiku-4-5` | Fastest and most cost-effective |
|
||||||
|
|
||||||
Default to the latest Opus for the caller's tier unless they explicitly chose otherwise. The Opus migrations layer: if you're on Opus 4.6 or older, apply each version's section in order up to your target (e.g. 4.5 -> 4.8 means the 4.6, 4.7, and 4.8 sections in sequence). A 4.7 -> 4.8 move has no new breaking changes - see Migrating to Opus 4.8 below.
|
Default to the latest Opus for the caller's tier unless they explicitly chose otherwise - except Claude Opus 5.5, which is launching: migrate to it only when the user names it. The Opus migrations layer: if you're on Opus 4.6 or older, apply each version's section in order up to your target (e.g. 4.5 -> 4.8 means the 4.6, 4.7, and 4.8 sections in sequence). A 4.7 -> 4.8 move has no new breaking changes - see Migrating to Opus 4.8 below.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -494,6 +498,7 @@ If the model is now overtriggering a tool or skill, the fix is almost always to
|
|||||||
| `claude-opus-4-5` | `claude-opus-5` |
|
| `claude-opus-4-5` | `claude-opus-5` |
|
||||||
| `claude-opus-4-1` | `claude-opus-5` |
|
| `claude-opus-4-1` | `claude-opus-5` |
|
||||||
| `claude-opus-4-0` | `claude-opus-5` |
|
| `claude-opus-4-0` | `claude-opus-5` |
|
||||||
|
| `claude-opus-5` | `claude-opus-5-5` - only when the user names Claude Opus 5.5 |
|
||||||
| `claude-mythos-preview` | `claude-mythos-5-1` (Project Glasswing) or `claude-fable-5-1` |
|
| `claude-mythos-preview` | `claude-mythos-5-1` (Project Glasswing) or `claude-fable-5-1` |
|
||||||
| `claude-fable-5` | `claude-fable-5-1` |
|
| `claude-fable-5` | `claude-fable-5-1` |
|
||||||
| `claude-mythos-5` | `claude-mythos-5-1` |
|
| `claude-mythos-5` | `claude-mythos-5-1` |
|
||||||
@@ -511,6 +516,7 @@ If the code uses the `AnthropicBedrockMantle` client (Python `anthropic[bedrock]
|
|||||||
|---|---|
|
|---|---|
|
||||||
| `claude-opus-4-8` | `anthropic.claude-opus-4-8` |
|
| `claude-opus-4-8` | `anthropic.claude-opus-4-8` |
|
||||||
| `claude-opus-5` | `anthropic.claude-opus-5` |
|
| `claude-opus-5` | `anthropic.claude-opus-5` |
|
||||||
|
| `claude-opus-5-5` | `anthropic.claude-opus-5-5` |
|
||||||
| `claude-fable-5-1` | `anthropic.claude-fable-5-1` |
|
| `claude-fable-5-1` | `anthropic.claude-fable-5-1` |
|
||||||
| `claude-fable-5` | `anthropic.claude-fable-5` |
|
| `claude-fable-5` | `anthropic.claude-fable-5` |
|
||||||
| `claude-mythos-5-1` | `anthropic.claude-mythos-5-1` (us-east-1 only, not publicly listed) |
|
| `claude-mythos-5-1` | `anthropic.claude-mythos-5-1` (us-east-1 only, not publicly listed) |
|
||||||
@@ -520,7 +526,7 @@ If the code uses the `AnthropicBedrockMantle` client (Python `anthropic[bedrock]
|
|||||||
|
|
||||||
When migrating a Bedrock file, apply the same rename-table row as first-party, then keep/add the `anthropic.` prefix. Do **not** generate a first-party `claude-*` ID for a Bedrock client - it will 400.
|
When migrating a Bedrock file, apply the same rename-table row as first-party, then keep/add the `anthropic.` prefix. Do **not** generate a first-party `claude-*` ID for a Bedrock client - it will 400.
|
||||||
|
|
||||||
**Skip for Bedrock:** the `code_execution_*` tool-version checklist item and the **Task Budgets** section - neither is available on Bedrock (see `shared/platform-availability.md` for the per-feature table). Everything else in this guide - `effort`, adaptive/extended thinking, `output_config.format`, `thinking.display`, fine-grained tool streaming, token counting - is available on Bedrock.
|
**Skip for Bedrock:** the `code_execution_*` tool-version checklist item and the **Task Budgets** section - neither is available on Bedrock (see `shared/platform-availability.md` for the per-feature table). Everything else in this guide - `effort`, adaptive/extended thinking, `output_config.format`, `thinking.display`, token counting - is available on Bedrock; fine-grained tool streaming (`eager_input_streaming`) is available on Bedrock's newer serving stack only (see the per-model note in `shared/platform-availability.md`).
|
||||||
|
|
||||||
> **Out of scope:** the legacy Amazon Bedrock integration (`InvokeModel` / `Converse` APIs with ARN-versioned IDs like `anthropic.claude-3-5-sonnet-20241022-v2:0`) uses a different request shape and model-ID format. This guide does not cover it; WebFetch the Bedrock page in `shared/live-sources.md` if the user is migrating between the two Bedrock integrations.
|
> **Out of scope:** the legacy Amazon Bedrock integration (`InvokeModel` / `Converse` APIs with ARN-versioned IDs like `anthropic.claude-3-5-sonnet-20241022-v2:0`) uses a different request shape and model-ID format. This guide does not cover it; WebFetch the Bedrock page in `shared/live-sources.md` if the user is migrating between the two Bedrock integrations.
|
||||||
|
|
||||||
@@ -699,11 +705,11 @@ Beyond resolution, Opus 4.7 also improves on low-level perception (pointing, mea
|
|||||||
|
|
||||||
Requests that involve prohibited or high-risk topics may lead to refusals.
|
Requests that involve prohibited or high-risk topics may lead to refusals.
|
||||||
|
|
||||||
### Fast Mode: Claude Opus 5 / Opus 4.8 only
|
### Fast Mode: Claude Opus 5 / Claude Opus 5.5 / Opus 4.8 only
|
||||||
|
|
||||||
Fast mode is available on Claude Opus 5 and Opus 4.8. Only surface this if the caller's code actually uses fast mode (e.g. `model="claude-opus-4-6-fast"`, or `speed="fast"` on an unsupported model); if the word "fast" does not appear in the code, say nothing about Fast Mode.
|
Fast mode is available on Claude Opus 5, Claude Opus 5.5, and Opus 4.8. Only surface this if the caller's code actually uses fast mode (e.g. `model="claude-opus-4-6-fast"`, or `speed="fast"` on an unsupported model); if the word "fast" does not appear in the code, say nothing about Fast Mode.
|
||||||
|
|
||||||
When you see `model="claude-opus-4-6-fast"` (or any retired `-fast` model string), **the migration edit is** to move the fast-mode traffic onto Claude Opus 5, the current fast-capable default (Opus 4.8 also works if the caller is staying on that tier):
|
When you see `model="claude-opus-4-6-fast"` (or any retired `-fast` model string), **the migration edit is** to move the fast-mode traffic onto Claude Opus 5, the current fast-capable default (Opus 4.8 also works if the caller is staying on that tier; Claude Opus 5.5 supports it too, at $8 / $40 - its fast-mode docs flip after the model launch, confirm before quoting - use it when the user names it):
|
||||||
|
|
||||||
```python
|
```python
|
||||||
# Request fast mode on Claude Opus 5.
|
# Request fast mode on Claude Opus 5.
|
||||||
@@ -714,7 +720,7 @@ client.beta.messages.create(
|
|||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
That is: switch the model to Claude Opus 5 (or Opus 4.8) and request fast mode the supported way, using the beta `client.beta.messages....` endpoint, the `fast-mode-2026-02-01` beta flag, and `speed="fast"` as a top-level request parameter (per-language form in SKILL.md § Fast Mode). Opus 4.7 fast mode has also been removed, so do not land on Opus 4.7 either. Do **not** leave the code on a retired `-fast` model string - the failure mode differs by version: `claude-opus-4-6-fast` is retired and the API **silently falls back** to standard Opus 4.6 (no error - the caller loses fast-mode speed without noticing); `claude-opus-4-7-fast` and `speed="fast"` on Opus 4.7 instead return an **API error** (hard failure - requests break outright rather than degrading). Either way, migrate to Opus 4.8 fast mode now.
|
That is: switch the model to Claude Opus 5 (or Opus 4.8) and request fast mode the supported way, using the beta `client.beta.messages....` endpoint, the `fast-mode-2026-02-01` beta flag, and `speed="fast"` as a top-level request parameter (per-language form in SKILL.md § Fast Mode). Opus 4.7 fast mode has also been removed, so do not land on Opus 4.7 either. Do **not** leave the code on a retired `-fast` model string - the failure mode differs by version: `claude-opus-4-6-fast` is retired and the API **silently falls back** to standard Opus 4.6 (no error - the caller loses fast-mode speed without noticing); `claude-opus-4-7-fast` and `speed="fast"` on Opus 4.7 instead return an **API error** (hard failure - requests break outright rather than degrading). Either way, migrate to a supported fast-mode model (Claude Opus 5 by default) now.
|
||||||
|
|
||||||
### Behavioral shifts (prompt-tunable)
|
### Behavioral shifts (prompt-tunable)
|
||||||
|
|
||||||
@@ -1598,7 +1604,7 @@ Keep passing thinking blocks back unchanged when you switch models - the API dro
|
|||||||
|
|
||||||
The published docs file this and breaking change 2 together under *preserved thinking* ("pass blocks back unchanged and let the API decide which the model can use"); this one is the conversation check - editing earlier turns invalidates every later thinking block. The API field names for it say `prefix_mismatch_behavior` / `prefix_binding_mismatch` - the same check.
|
The published docs file this and breaking change 2 together under *preserved thinking* ("pass blocks back unchanged and let the API decide which the model can use"); this one is the conversation check - editing earlier turns invalidates every later thinking block. The API field names for it say `prefix_mismatch_behavior` / `prefix_binding_mismatch` - the same check.
|
||||||
|
|
||||||
A Claude Fable 5.1 thinking block's `signature` also records the conversation prefix that produced it - the top-level `system` prompt, the set of tools in `tools`, and every message before the block (with server-side compaction, the prefix starts at the most recent compaction block) - plus a chain to the previous thinking block across turns (earlier thinking blocks aren't part of the prefix, but each block records the one before it, which is why blocks can be removed from the *front* of the history and not from the middle). When the transcript comes back, the API checks that this prefix is unchanged. Claude Code, claude.ai, Managed Agents, and the Agent SDK keep the prefix intact for you; **if your code builds the `messages` array itself, check it before migrating** (the three-step check is below). **Who is enforced:** new accounts **created on or after August 31, 2026** (Claude API organizations, Amazon Bedrock accounts, Google Cloud projects, Microsoft Foundry resources). Anthropic plans to enforce it for every account on future models, so adopt the patterns now even if your account isn't enforced today. For accounts created earlier the API *records* the mismatch but acts on it only when the request opts in: setting `thinking.block_binding.prefix_mismatch_behavior` - **any value, including `"error"`, opts the request into enforcement**, which is also how you test from an older organization - or sending the `thinking-binding-controls-2026-08-01` header alone, which opts the request into the beta's default, `drop_block`. If you ship a tool or framework that people run with their own API key, test with the field set: your users on new organizations are enforced before you are. To see whether your own organization is enforced by default, send a request that edits history without the beta header - a 400 that names the header means it is. Platform note: the opt-in controls themselves (the beta header, `prefix_mismatch_behavior`, `input_transformations`) are on the Claude API and Claude Platform on AWS at launch, arrive per model on Amazon Bedrock and Google Cloud (until then the header is rejected there), and aren't offered on Microsoft Foundry - on a platform without the controls the opt-in test path doesn't apply and recovery is strip-and-retry (`shared/platform-availability.md` has the matrix).
|
A Claude Fable 5.1 thinking block's `signature` also records the conversation prefix that produced it - the top-level `system` prompt, the set of tools in `tools`, and every message before the block (with server-side compaction, the prefix starts at the most recent compaction block) - plus a chain to the previous thinking block across turns (earlier thinking blocks aren't part of the prefix, but each block records the one before it, which is why blocks can be removed from the *front* of the history and not from the middle). When the transcript comes back, the API checks that this prefix is unchanged. Claude Code, claude.ai, Managed Agents, and the Agent SDK keep the prefix intact for you; **if your code builds the `messages` array itself, check it before migrating** (the three-step check is below). **Who is enforced:** new accounts **created on or after August 31, 2026** (Claude API organizations, Amazon Bedrock accounts, Google Cloud projects, Microsoft Foundry resources). Enforcement scope is decided per model - Claude Opus 5.5 also enforces it for new accounts only - so make your application compatible regardless of your account's age: the same patterns keep the prompt cache warm, and you can test against the check from any account by sending `prefix_mismatch_behavior`. For accounts created earlier the API *records* the mismatch but acts on it only when the request opts in: setting `thinking.block_binding.prefix_mismatch_behavior` - **any value, including `"error"`, opts the request into enforcement**, which is also how you test from an older organization - or sending the `thinking-binding-controls-2026-08-01` header alone, which opts the request into the beta's default, `drop_block`. If you ship a tool or framework that people run with their own API key, test with the field set: your users on new organizations are enforced before you are. To see whether your own organization is enforced by default, send a request that edits history without the beta header - a 400 that names the header means it is. Platform note: the opt-in controls themselves (the beta header, `prefix_mismatch_behavior`, `input_transformations`) are on the Claude API and Claude Platform on AWS at launch, arrive per model on Amazon Bedrock and Google Cloud (until then the header is rejected there), and aren't offered on Microsoft Foundry - on a platform without the controls the opt-in test path doesn't apply and recovery is strip-and-retry (`shared/platform-availability.md` has the matrix).
|
||||||
|
|
||||||
**What invalidates every later thinking block:**
|
**What invalidates every later thinking block:**
|
||||||
|
|
||||||
@@ -1840,7 +1846,7 @@ The second tells it to hold the scope the user set:
|
|||||||
- [ ] **[BLOCKS]** Coming from an Opus-tier or older model (not from Claude Fable 5): apply the Claude Fable 5.1 Migration Checklist above (the Opus-tier -> Fable migration) first, plus § Coming from Claude Opus 5 - `thinking: {type: "disabled"}` now 400s at any effort, between-tool narration moves into `thinking` blocks, ZDR is lost, price doubles
|
- [ ] **[BLOCKS]** Coming from an Opus-tier or older model (not from Claude Fable 5): apply the Claude Fable 5.1 Migration Checklist above (the Opus-tier -> Fable migration) first, plus § Coming from Claude Opus 5 - `thinking: {type: "disabled"}` now 400s at any effort, between-tool narration moves into `thinking` blocks, ZDR is lost, price doubles
|
||||||
- [ ] **[BLOCKS]** Data retention: 30-day retention required (Covered Model; ZDR only if expressly authorized by Anthropic) - a ZDR org gets `400 invalid_request_error` on every request, as on Claude Fable 5; check the retention configuration before debugging the payload
|
- [ ] **[BLOCKS]** Data retention: 30-day retention required (Covered Model; ZDR only if expressly authorized by Anthropic) - a ZDR org gets `400 invalid_request_error` on every request, as on Claude Fable 5; check the retention configuration before debugging the payload
|
||||||
- [ ] **[BLOCKS]** Keep passing `thinking` blocks back unchanged on every turn, including empty ones and `redacted_thinking` - the history-editing check rejects edited history
|
- [ ] **[BLOCKS]** Keep passing `thinking` blocks back unchanged on every turn, including empty ones and `redacted_thinking` - the history-editing check rejects edited history
|
||||||
- [ ] **[BLOCKS]** Preserved thinking / the history-editing check (new accounts created on/after 2026-08-31 on every platform, and any request that sets `prefix_mismatch_behavior` or sends the controls beta header; later models enforce it for everyone): stop editing history between requests - freeze the top-level `system`, use `role: "system"` messages for mid-session instructions, `tool_addition`/`tool_removal` for tool changes, turn-scoped (`clear_at`) system messages - or, without that beta, retained user-message text blocks - appended after the tool results and never deleted, for per-turn reminders, server-side context editing / compaction (summary-only if client-side) for trimming, `file_id` for cross-turn files. Run the three-step check on a platform offering the controls beta (`shared/platform-availability.md`) (`prefix_mismatch_behavior: "drop_block"` + log `input_transformations`; fix every `prefix_binding_mismatch`, `model_binding_mismatch` after a model switch is expected; `"error"` in CI), then pick a production setting and monitor it. If you ship a tool others run with their own key, test with the field set. Keep-tail and background compaction need `"drop_block"` (per request - keep sending it) or stripped thinking on the retained turns; never compact mid tool round
|
- [ ] **[BLOCKS]** Preserved thinking / the history-editing check (new accounts created on/after 2026-08-31 on every platform, and any request that sets `prefix_mismatch_behavior` or sends the controls beta header; enforcement scope is decided per model, and Claude Opus 5.5 also enforces it for new accounts only): stop editing history between requests - freeze the top-level `system`, use `role: "system"` messages for mid-session instructions, `tool_addition`/`tool_removal` for tool changes, turn-scoped (`clear_at`) system messages - or, without that beta, retained user-message text blocks - appended after the tool results and never deleted, for per-turn reminders, server-side context editing / compaction (summary-only if client-side) for trimming, `file_id` for cross-turn files. Run the three-step check on a platform offering the controls beta (`shared/platform-availability.md`) (`prefix_mismatch_behavior: "drop_block"` + log `input_transformations`; fix every `prefix_binding_mismatch`, `model_binding_mismatch` after a model switch is expected; `"error"` in CI), then pick a production setting and monitor it. If you ship a tool others run with their own key, test with the field set. Keep-tail and background compaction need `"drop_block"` (per request - keep sending it) or stripped thinking on the retained turns; never compact mid tool round
|
||||||
- [ ] **[TUNE]** Fallbacks: keep server-side `fallbacks` (targets `claude-opus-4-8` / `claude-opus-5`; routing unpublished) or the SDK middleware; the fallback model can't read 5.1 thinking blocks (dropped, unbilled); fallback credit works as on Claude Fable 5
|
- [ ] **[TUNE]** Fallbacks: keep server-side `fallbacks` (targets `claude-opus-4-8` / `claude-opus-5`; routing unpublished) or the SDK middleware; the fallback model can't read 5.1 thinking blocks (dropped, unbilled); fallback credit works as on Claude Fable 5
|
||||||
- [ ] **[TUNE]** Adopt `thinking: {type: "adaptive", display: "updates"}` with `thinking-display-updates-2026-08-18` (all platforms) if users watch long tool-calling turns; render non-empty `thinking` blocks as status lines, handle the interrupted-response sentinel, echo them back unchanged
|
- [ ] **[TUNE]** Adopt `thinking: {type: "adaptive", display: "updates"}` with `thinking-display-updates-2026-08-18` (all platforms) if users watch long tool-calling turns; render non-empty `thinking` blocks as status lines, handle the interrupted-response sentinel, echo them back unchanged
|
||||||
- [ ] **[TUNE]** Adopt per-message effort (`mid-conversation-output-config-2026-07-01`; also on Claude Opus 5) where a loop mixes hard and routine steps - lowering is reliable, raising wants a big jump; re-run the effort sweep (`high` default; `medium` as cost control; `xhigh`/`max` only for capability-sensitive work; `low` often beats below-frontier models on cost per task); size `max_tokens` for `high`+
|
- [ ] **[TUNE]** Adopt per-message effort (`mid-conversation-output-config-2026-07-01`; also on Claude Opus 5) where a loop mixes hard and routine steps - lowering is reliable, raising wants a big jump; re-run the effort sweep (`high` default; `medium` as cost control; `xhigh`/`max` only for capability-sensitive work; `low` often beats below-frontier models on cost per task); size `max_tokens` for `high`+
|
||||||
@@ -1851,9 +1857,215 @@ The second tells it to hold the scope the user set:
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Migrating to Claude Opus 5.5
|
||||||
|
|
||||||
|
> **Model ID `claude-opus-5-5` is authoritative as written here.** When the user asks to migrate to Claude Opus 5.5, write `model="claude-opus-5-5"` exactly. Do **not** WebFetch to verify - this guide is the source of truth for migration target IDs. The corresponding entry exists in `shared/models.md`.
|
||||||
|
|
||||||
|
Claude Opus 5.5 succeeds Claude Opus 5 in the Opus line for long-running agentic coding and knowledge work, **at a lower price** - $4 / $20 per MTok input / output against Claude Opus 5's $5 / $25. Same 1M token context window (default and maximum), same 128K max output, same tokenizer as Claude Opus 5 (token counts unchanged; coming from a pre-Opus-4.7 model, follow the tokenizer guidance in the Claude Opus 5 section). Knowledge cutoff June 2026. Available at launch on the Claude API (`claude-opus-5-5`), Amazon Bedrock (`anthropic.claude-opus-5-5`), Claude Platform on AWS, Google Cloud, and Microsoft Foundry (all as `claude-opus-5-5`; on Foundry both the Anthropic-hosted and Microsoft-hosted paths, the latter subject to its own launch-day go/no-go); Claude Opus 5 stays available on all of them. Existing Claude Opus 5 prompts should perform well out of the box; the Claude Opus 5 prompting patterns below remain a reasonable starting point.
|
||||||
|
|
||||||
|
**Migrate to Claude Opus 5.5 when the user names it.** This section is written ahead of the launch: the skill's mandated default (`claude-opus-5`) and the pricing table in SKILL.md don't move until then. It is layered on top of the Claude Opus 5 migration above - a caller coming from Opus 4.8 or older applies § Migrating to Claude Opus 5 first (Opus 4.7 or older: the sections before that), with two exceptions to what that section (and the earlier ones) say: Claude Opus 5's "thinking can be disabled at `high` or below" does not carry over, and neither does the acceptance of the earlier `computer_20251124` tool (breaking change 4 below). Coming from Claude Sonnet 5: the request surface already matches (adaptive thinking, no sampling parameters, no prefill) - apply this section on top of the Claude Sonnet 5 code, re-baselining for Opus-tier pricing and rate limits.
|
||||||
|
|
||||||
|
**What changes, in one line:** four breaking changes for code running on Claude Opus 5 (thinking can't be disabled; forced `tool_choice` 400s; thinking blocks are tied to the model and the conversation - "preserved thinking"; the `computer_20251124` tool 400s - use the computer toolset), one response-shape change that fails no request (text between tool calls comes back in `thinking` blocks), a **default effort of `medium`** where Claude Opus 5's is `high`, and a broader safety-classifier set (`bio` and `reasoning_extraction` join `cyber`). The first three breaking changes are the same mechanisms Claude Fable 5.1 introduced - the sections below give the Claude Opus 5.5 specifics and point at § Migrating to Claude Fable 5.1 from Claude Fable 5 for the shared mechanics rather than repeating them. Everything else in the Claude Opus 5 request surface carries over: mid-conversation system messages and per-message effort (which some of the tips below use), mid-conversation tool changes, task budgets, compaction, the 512-token minimum cacheable prompt, batch, the Files API, PDF support, vision, and the server-side and client-side tools.
|
||||||
|
|
||||||
|
### Breaking change 1: thinking can't be disabled
|
||||||
|
|
||||||
|
On Claude Opus 5, thinking is on by default and `thinking: {type: "disabled"}` is accepted at effort `high` or below. On Claude Opus 5.5 thinking is **always on**: `{"type": "disabled"}` and `{"type": "enabled", "budget_tokens": N}` both return a 400 `invalid_request_error` at every effort level, with no beta header involved:
|
||||||
|
|
||||||
|
```text
|
||||||
|
"thinking.type.disabled" is not supported for this model. Use "thinking.type.adaptive" and "output_config.effort" to control thinking behavior.
|
||||||
|
```
|
||||||
|
|
||||||
|
(`"thinking.type.enabled" is not supported for this model. ...` for the budget form.) Omit the `thinking` field or send `{type: "adaptive"}`, which is equivalent. **Effort is now the control for how much the model thinks, and therefore for latency and cost** (§ Choosing an effort level below). Migrate a route that disables thinking or sets a budget as follows:
|
||||||
|
|
||||||
|
1. **Remove the `thinking` field** (or set it to `{type: "adaptive"}`).
|
||||||
|
2. **If time to first token matters, set `output_config.effort` to `low`.** At `low` the model keeps its thinking short; how often it skips thinking altogether depends on the prompts. Measure, and move to `medium` if quality drops. A system-prompt line such as *"Answer directly without deliberating."* can reduce thinking further (and with it TTFT and cost) - measure quality on your own use case before keeping it, since less thinking can cost accuracy.
|
||||||
|
3. **Size `max_tokens` for the thinking as well as the reply.** Thinking counts toward `max_tokens` even though its text isn't returned under the default `display`, so a limit sized for a no-thinking route cuts replies off. For long agentic coding turns, 64K has worked well.
|
||||||
|
4. **Read the response by block `type`, not position.** A response can begin with one or more `thinking` blocks; under the default `display: "omitted"` they come back with an empty `thinking` string. Set `display: "summarized"` for a readable summary of the reasoning. Pass `thinking` blocks back unmodified in tool-use loops.
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Before - accepted on Claude Opus 5, 400 on Claude Opus 5.5
|
||||||
|
client.messages.create(
|
||||||
|
model="claude-opus-5",
|
||||||
|
max_tokens=16000,
|
||||||
|
thinking={"type": "disabled"},
|
||||||
|
messages=[{"role": "user", "content": "..."}],
|
||||||
|
)
|
||||||
|
|
||||||
|
# After - thinking is always on; effort is the control
|
||||||
|
client.messages.create(
|
||||||
|
model="claude-opus-5-5",
|
||||||
|
max_tokens=16000,
|
||||||
|
output_config={"effort": "low"},
|
||||||
|
messages=[{"role": "user", "content": "..."}],
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Prompts written for thinking disabled.** Three follow-ups if the Claude Opus 5 integration ran with thinking off: (a) start at `low` and measure, as above; (b) **remove instructions that stood in for thinking** - a prompt that asked the model to write its reasoning into the response text as a substitute for thinking should go, and the reasoning read from `display: "summarized"` blocks instead; a prompt that pushes the model to reproduce its internal reasoning in the response can be **declined** with `stop_details.category: "reasoning_extraction"`; (c) re-test the two thinking-disabled mitigations from § Two failure modes when thinking is disabled under Claude Opus 5 - both address artifacts that appeared only with thinking off, so check whether the combined "brief sentence before a tool call / say so if no tool fits / no internal XML tags" instruction is still needed, and **delete any rule telling the model not to think either way** (it can't comply, and such rules increase tag leakage).
|
||||||
|
|
||||||
|
### Breaking change 2: forced tool use is rejected
|
||||||
|
|
||||||
|
As on Claude Fable 5.1: `tool_choice: {"type": "any"}` and `{"type": "tool", "name": "..."}` return a 400 `invalid_request_error` (`tool_choice: type "tool" and "any" are not supported for this model.`) on the Messages API, the Message Batches API, and the token-counting endpoint, where Claude Opus 5 accepts both. `{"type": "auto"}` (the default) and `{"type": "none"}` are unchanged; `disable_parallel_tool_use: true` still works with `auto` but now means *at most* one call. Migrate by intent - the full patterns (steering from the prompt, `strict: true` for schema-valid arguments, structured outputs for extraction, the advisor tool) are under § Breaking change 1: forced tool use is rejected in § Migrating to Claude Fable 5.1 from Claude Fable 5. The two most common:
|
||||||
|
|
||||||
|
- **Steering toward a tool:** `tool_choice: {"type": "auto"}` plus the expectation in the prompt ("Use the `get_weather` tool to answer"), with `strict: true` on the tool definition (schema sets `additionalProperties: false`) so the arguments match the schema. Because `auto` does not guarantee a call, **check that one was made and retry if it wasn't.**
|
||||||
|
- **Extracting structured data:** if the forced call existed only to get JSON back, replace it with structured outputs (`output_config.format`).
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Before - 400 on Claude Opus 5.5
|
||||||
|
response = client.messages.create(
|
||||||
|
model="claude-opus-5",
|
||||||
|
max_tokens=1024,
|
||||||
|
tools=tools,
|
||||||
|
tool_choice={"type": "tool", "name": "get_weather"},
|
||||||
|
messages=[{"role": "user", "content": "What's the weather in Paris?"}],
|
||||||
|
)
|
||||||
|
|
||||||
|
# After - auto + strict tool use, steering in the prompt, and a check that the call happened
|
||||||
|
response = client.messages.create(
|
||||||
|
model="claude-opus-5-5",
|
||||||
|
max_tokens=1024,
|
||||||
|
tools=[{**tool, "strict": True} for tool in tools],
|
||||||
|
tool_choice={"type": "auto"},
|
||||||
|
messages=[{"role": "user", "content": "What's the weather in Paris? Use the get_weather tool."}],
|
||||||
|
)
|
||||||
|
if not any(block.type == "tool_use" for block in response.content):
|
||||||
|
... # retry, or fall back to a text answer
|
||||||
|
```
|
||||||
|
|
||||||
|
### Breaking change 3: thinking blocks are tied to the model and the conversation
|
||||||
|
|
||||||
|
Both halves of "preserved thinking" from Claude Fable 5.1 apply to Claude Opus 5.5; the mechanics (what invalidates a block, the `drop_block` request shape, `input_transformations`, the three-step audit, the append-only replacements table, which client-side compaction shapes break) are under § Breaking change 2 and § Breaking change 3 in § Migrating to Claude Fable 5.1 from Claude Fable 5 and apply verbatim. What is specific to Claude Opus 5.5:
|
||||||
|
|
||||||
|
- **Model binding - who reads whose blocks.** Claude Opus 5.5 reads thinking blocks from Claude Opus 5 and earlier Opus, Sonnet, and Haiku models - a conversation that *moves onto* `claude-opus-5-5` keeps its reasoning - but **not** from any Fable or Mythos model. In the other direction, on the Claude API only Claude Fable 5.1 and Claude Mythos 5.1 read a Claude Opus 5.5 block; **no other model does** - so a router switch, a client-side retry on another model, or a classifier-refusal fallback (server-side or SDK middleware) to Claude Opus 5 / Claude Opus 4.8 runs the turns after the switch without Claude Opus 5.5's reasoning. The API drops what the target can't read before the model sees it: the request succeeds, dropped blocks aren't billed, and with the `thinking-binding-controls-2026-08-01` header the drop is reported in `input_transformations` with `reason: "model_binding_mismatch"`. Whether Claude Fable 5.1 / Claude Mythos 5.1 also keep Claude Opus 5.5's blocks on Amazon Bedrock and Google Cloud is open at launch - the docs claim it for the Claude API only. Keep passing blocks back unchanged when you switch models; don't strip them yourself.
|
||||||
|
- **Conversation binding - who is enforced.** Same posture as Claude Fable 5.1: on every platform the prefix check (the `system` prompt, the `tools` array, and every earlier message must be byte-identical to when the block was produced) is enforced by default for accounts **created on or after August 31, 2026, 00:00 UTC** - a replayed block after such an edit is a 400. Older accounts opt in by setting `thinking.block_binding.prefix_mismatch_behavior` (`"error"` or `"drop_block"`, beta `thinking-binding-controls-2026-08-01`). Claude Code, claude.ai, Managed Agents, and the Agent SDK keep the prefix intact; **if your code builds `messages` itself, run the three-step check before migrating** - and do it now even on an exempt account, because it also raises prompt-cache hit rates. The three edits that break the prefix and their append-only replacements: a per-turn reminder injected and later deleted, or a system prompt changed mid-session (append a mid-conversation `role: "system"` message instead; for a one-turn reminder the `clear_at: "next_user_message"` form under beta `mid-conversation-system-clear-at-2026-08-21` is a limited beta - without it, append the reminder as a text block after the `tool_result` blocks and leave earlier copies in place); tools added or removed mid-session (declare the full set at session start and send `tool_addition` / `tool_removal` blocks, beta `mid-conversation-tool-changes-2026-07-01`); and compaction that summarizes older turns while replaying newer ones with their thinking blocks (use server-side compaction or context editing - the on-demand `compaction` parameter under beta `compact-2026-09-04`, offered on the Claude API, Claude Platform on AWS, Google Cloud, and Microsoft Foundry but not yet Amazon Bedrock, is designed to keep the retained turns' blocks valid after the swap - or client-side *simple* compaction that replaces the whole history with a summary and replays no earlier thinking, or set `drop_block`). Two compaction details that follow Claude Fable 5.1: a threshold-compaction request with custom `instructions` summarizes from the visible conversation only - earlier thinking blocks are not part of the summarizer's input, so tell it what the summary must retain (on-demand compaction's summarizer reads earlier thinking with or without `instructions`); and any assistant turn you re-insert after a compaction block needs its `thinking` / `redacted_thinking` blocks removed, or `drop_block` set.
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /v1/messages
|
||||||
|
anthropic-beta: thinking-binding-controls-2026-08-01
|
||||||
|
|
||||||
|
{"model": "claude-opus-5-5", "max_tokens": 64000,
|
||||||
|
"thinking": {"type": "adaptive", "block_binding": {"prefix_mismatch_behavior": "drop_block"}},
|
||||||
|
"messages": [ ...full history with thinking blocks replayed verbatim... ]}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Breaking change 4: computer use only through the computer toolset
|
||||||
|
|
||||||
|
> **Confirm at launch.** The EAP guide marks the accepted computer-use tool versions and the toolset's platform availability as not final; the launch docs state the rule below. Re-check `shared/live-sources.md` -> Computer use before promising it on a partner platform.
|
||||||
|
|
||||||
|
Claude Opus 5 accepts computer use both as the `computer_toolset_20260801` toolset and, with the `computer-use-2025-11-24` beta header, as the earlier `computer_20251124` tool. **Claude Opus 5.5 accepts only the toolset**: a `tools` entry of type `computer_20251124` returns a 400 `invalid_request_error` that names the rejected type and then lists the accepted ones after `Did you mean one of` (it begins `'claude-opus-5-5' does not support tool types: computer_20251124.`). The toolset is GA on the Claude API and Google Cloud with no beta header; other platforms offer only the earlier beta versions today, so an integration on those platforms has no Claude Opus 5.5 computer-use path until they add the toolset - check the computer use tool's Compatibility section (`shared/tool-use-concepts.md` § Computer Use has the toolset summary). This is more than a `tools`-entry swap, so make and test the change on Claude Opus 5 first (it accepts both forms):
|
||||||
|
|
||||||
|
- **Request:** drop the beta header and the beta client namespace; the entry is `{"type": "computer_toolset_20260801"}` with **no `name`** and no `display_width_px` / `display_height_px`; an optional `configs` map turns individual member tools on or off (`{"zoom": {"enabled": false}}`). All 17 members, `zoom` included, are on by default. The entry can't share a request with a `computer_20251124` entry or another tool named `computer`.
|
||||||
|
- **Agent loop:** Claude's calls are `tool_use` blocks whose `name` is the member (`screenshot`, `left_click`, `type`, `zoom`, ...) - **the action is the block's `name`, not `input.action`** - carrying `"toolset_name": "computer"`, and there can be **several per turn** (a batch action), each its own block. Return one `tool_result` per `tool_use`, matched by `tool_use_id`, all in the next `user` message, **every one echoing `"toolset_name": "computer"`** (a result that omits it is rejected); only `screenshot` and `zoom` results need an image, a short `OK` is enough for the rest. Coordinates are in the pixel space of the full screenshots you return, also after a `zoom`. Screenshots must already fit the model's image limits (the toolset takes no display dimensions and the API doesn't downscale for you).
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Before - 400 on Claude Opus 5.5
|
||||||
|
client.beta.messages.create(
|
||||||
|
model="claude-opus-5",
|
||||||
|
max_tokens=4096,
|
||||||
|
betas=["computer-use-2025-11-24"],
|
||||||
|
tools=[{"type": "computer_20251124", "name": "computer",
|
||||||
|
"display_width_px": 1024, "display_height_px": 768}],
|
||||||
|
messages=[{"role": "user", "content": "Open the display settings."}],
|
||||||
|
)
|
||||||
|
|
||||||
|
# After - no beta header; the toolset entry takes no name or display size
|
||||||
|
client.messages.create(
|
||||||
|
model="claude-opus-5-5",
|
||||||
|
max_tokens=4096,
|
||||||
|
tools=[{"type": "computer_toolset_20260801"}],
|
||||||
|
messages=[{"role": "user", "content": "Open the display settings."}],
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
Integrations already on the toolset, and the browser use toolset (`browser_toolset_20260801`), need no change.
|
||||||
|
|
||||||
|
### Text between tool calls comes back in thinking blocks
|
||||||
|
|
||||||
|
On Claude Opus 5, the short notes the model writes between tool calls (what it just found, what it's doing next) come back as `text` blocks. On Claude Opus 5.5, as on Claude Fable 5.1, notes longer than a sentence or two come back as **progress-update `thinking` blocks**, at most one before each tool call, and under the default `display: "omitted"` their text is empty - no request fails, but a client that renders only `text` blocks goes quiet for the length of a long agentic turn. Fix: set `thinking.display: "updates"` (beta `thinking-display-updates-2026-08-18`) to get a short summary of each note as text while reasoning stays hidden (`"summarized"` returns both, mixed), render each non-empty `thinking` block ahead of the `tool_use` it precedes, and pass the blocks back unchanged - the consumption rules (streaming `thinking_delta`, the interrupted-work sentinel, zero-or-more per response) are under addition 3 in § New API features of § Migrating to Claude Fable 5.1 from Claude Fable 5:
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /v1/messages
|
||||||
|
anthropic-beta: thinking-display-updates-2026-08-18
|
||||||
|
|
||||||
|
{"model": "claude-opus-5-5", "max_tokens": 64000,
|
||||||
|
"thinking": {"type": "adaptive", "display": "updates"},
|
||||||
|
"tools": [...],
|
||||||
|
"messages": [{"role": "user", "content": "Review the PRs open against our billing service."}]}
|
||||||
|
```
|
||||||
|
|
||||||
|
Three levers on what users see:
|
||||||
|
|
||||||
|
1. **Receive them** - `display: "updates"` as above (a `"summarized"` display returns them too, mixed with the reasoning summaries).
|
||||||
|
2. **If the model may need to hand the user something *verbatim*** partway through a long turn - a code snippet, an exact value - give it a simple tool for sending the user a message and tell it to reserve the tool for that content. Declare the tool in `tools` from the **first** request of the session: adding it later edits the conversation's prefix and invalidates earlier thinking blocks (breaking change 3).
|
||||||
|
3. **For more frequent or predictable updates** - a one-line statement of intent before the first tool call and a short recap at the end - say so in the system prompt: when you want user-facing text and what it should contain. The model follows such instructions reasonably well; this helps most in pair programming and other human-in-the-loop work.
|
||||||
|
|
||||||
|
### Choosing an effort level - the default is `medium`, and the levels don't map 1:1 from Claude Opus 5
|
||||||
|
|
||||||
|
Effort is the main control for how much Claude Opus 5.5 thinks, and with adaptive-only thinking it is the first setting to adjust when trading off intelligence, latency, and cost. Two things change from Claude Opus 5:
|
||||||
|
|
||||||
|
- **The API default is `medium`** (Claude Opus 5 and earlier Opus models default to `high`), so a request that omits `effort` now runs one level lower than it did. **Set `effort` explicitly** and re-run the sweep rather than carrying the Claude Opus 5 setting over. Effort names don't mean the same amount of thinking across models: in Anthropic's testing, Claude Opus 5.5 at `medium` exceeds Claude Opus 5 at `high` on coding and knowledge-work evaluations, and on several coding evaluations `low` comes close to it at much lower cost. Start at `medium` and test the neighboring levels; reserve `xhigh` and `max` for work where you have measured a quality gain (all five levels are supported; `max` is uncapped).
|
||||||
|
- **At a given level, Claude Opus 5.5 tends to think more per turn than Claude Opus 5**, especially at `xhigh` and `max`. If you keep the `effort` value you set for Claude Opus 5, expect longer turns and more output tokens. To get less thinking, **lower the effort level before adding "think less" instructions** - lowering effort reduces thinking, cost, and latency more reliably than prompting does. Set `max_tokens` with room for the thinking as well as the reply (thinking counts toward it even though the text isn't returned - a limit sized for Claude Opus 5 with thinking off can cut replies off; 64K is a reasonable starting point for long agentic coding turns).
|
||||||
|
|
||||||
|
Change effort for individual turns without invalidating the prompt cache with a **per-message effort change** (beta `mid-conversation-output-config-2026-07-01`; the request shape is addition 1 under § New API features of § Migrating to Claude Fable 5.1 from Claude Fable 5, and Claude Opus 5 already supports it). Changing the **top-level** `effort` between requests does invalidate the prompt cache.
|
||||||
|
|
||||||
|
### Safeguards - a broader classifier set than Claude Opus 5
|
||||||
|
|
||||||
|
Claude Opus 5.5 runs cybersecurity **and biology** safety classifiers similar to Claude Fable 5.1's; coming from Claude Opus 5, the biology classifier is new. Everyday health and educational questions are unaffected, but requests the classifier treats as dual-use biology research (virology, toxicology, molecular design) are declined; on the cybersecurity side, finding vulnerabilities in source code is allowed. Separately - also new relative to Claude Opus 5 - a request that tries to get the model to reproduce its internal reasoning in the response text can be declined with `stop_details.category: "reasoning_extraction"`; if a prompt does this (for example, to get visible reasoning with thinking off), remove the instruction, set `display: "summarized"`, and read the `thinking` blocks. **`reasoning_extraction` declines are not retried on a fallback model.**
|
||||||
|
|
||||||
|
A classifier decline arrives as a normal HTTP 200 with `stop_reason: "refusal"` and a `stop_details` object naming the category (`"cyber"`, `"bio"`, `"reasoning_extraction"`, ...; branch on `stop_reason`, treat `stop_details` as informational - the full handling is § `refusal` stop reason under § Migrating to Claude Fable 5.1). A refusal before any output is not billed, but the request still counts against your rate limits (the billing wording is under revision at launch - confirm). Retry on another model with server-side fallbacks - `fallbacks: "default"` under beta `server-side-fallback-2026-07-01` retries on the model Anthropic recommends for that category, the array form under `server-side-fallback-2026-06-01` names your own targets (§ New API features under § Migrating to Claude Opus 5 has both shapes; the permitted targets for Claude Opus 5.5 are open at launch - expect Claude Opus 5 / claude-opus-4-8), the SDK middleware on platforms without server-side fallback, or your own retry. A fallback model runs without Claude Opus 5.5's thinking blocks (breaking change 3). **Ship the opt-in from day one**, as the Claude Fable 5.1 section says.
|
||||||
|
|
||||||
|
The classifiers can still flag benign requests - the fallback opt-in is what keeps a false positive from becoming an outage. (The EAP guide's prompt-side workarounds for specific false positives were not carried into the launch docs - don't cite them.)
|
||||||
|
|
||||||
|
### What carries over unchanged from Claude Opus 5 - and what's open at launch
|
||||||
|
|
||||||
|
- **Feature set:** per-message effort (beta), mid-conversation system messages (no header) and tool changes (beta), task budgets, compaction (including the on-demand `compaction` parameter, beta `compact-2026-09-04`, which has its own docs), prompt caching with the 512-token minimum, batch processing (up to 300K output tokens with the `output-300k-2026-03-24` beta), the Files API, PDF support, vision, structured outputs, strict tool use, and the same server-side and client-side tools - except computer use, which needs the toolset (breaking change 4). Programmatic tool calling lists the model.
|
||||||
|
- **Pricing:** $4 / $20 per MTok; 5-minute cache writes $5 and 1-hour cache writes $8 (derived from the standard 1.25x / 2x multipliers - confirm at launch); **cache reads $0.20 per MTok (0.05x base input)**; batch $2 / $10. The cache-read discount is deeper than Claude Opus 5's, so long agentic sessions that re-read a cached prefix save more, and a miss costs relatively more - keeping the cache warm (per-message effort, append-only histories, the keep-alive patterns in `shared/prompt-caching.md`) matters more.
|
||||||
|
- **Rate limits:** a separate pool from Claude Opus 5's (own per-tier numbers - may instead share Claude Opus 5's group; confirm at launch). Re-check your tier's Claude Opus 5.5 limits before moving volume.
|
||||||
|
- **Priority Tier:** not supported (as Claude Opus 5).
|
||||||
|
- **Fast mode:** research preview on the Claude API only (not Bedrock, Claude Platform on AWS, Google Cloud, or Foundry), `speed: "fast"` under beta `fast-mode-2026-02-01`, at **$8 / $40 per MTok** (2x the standard price, the same multiple as Claude Opus 5's $10 / $50) - the fast-mode docs flip after the model's own launch, so confirm before quoting.
|
||||||
|
- **Data retention / ZDR:** the launch docs say nothing new - treat Claude Opus 5.5 as Claude Opus 5 here, and check `shared/platform-availability.md` at launch.
|
||||||
|
- **SDK constants:** `Model.ClaudeOpus5_5` (C#), `anthropic.ModelClaudeOpus5_5` (Go), `Model.CLAUDE_OPUS_5_5` (Java, PHP), `Anthropic::Model::CLAUDE_OPUS_5_5` (Ruby) - published with each SDK's launch release; the bare string `"claude-opus-5-5"` works everywhere before then.
|
||||||
|
|
||||||
|
### Capability improvements versus Claude Opus 5
|
||||||
|
|
||||||
|
**Cheaper per solved task, not just per token.** On many coding, analysis, and vision tasks, Claude Opus 5.5 at its default effort matched or beat Claude Opus 5 while using fewer tokens, and its price per token is 20% lower than Claude Opus 5's (60% lower for cache reads) - so expect the cost per solved task to be significantly lower for most tasks, and re-baseline `shared/cost-optimization.md`'s Claude Opus 5 figures rather than scaling them by the list price alone.
|
||||||
|
|
||||||
|
- **Agentic coding and code review:** the largest measured gains are on multistep work in a real codebase (carrying a change through a large repository until its tests pass) - in Anthropic's testing, at its default `medium` effort it matched or beat Claude Opus 5's `high`-effort results on such tasks, in fewer steps and with about half the tokens - and on code review, where it catches more bugs with fewer false alarms. It explains its changes in plain language, which makes its work easier to review and trust. It tends to finish the same task with fewer tokens.
|
||||||
|
- **Knowledge work:** a more reliable analyst - much less likely than Claude Opus 5 to state a figure or cite a source the inputs don't support (citations pointed at the right source much more often in one customer's measurement); at `medium` it produced better long analytical deliverables than Claude Opus 5 at `high` with roughly 40% fewer output tokens; better at building and auditing financial models; more detail-oriented on large inputs (a date in a long thread that falls on the wrong weekday, a chart in a deck that doesn't match the figures) **without more false-positive flags**.
|
||||||
|
- **Communication and writing:** clearer prose, most noticeably in how it reports on agentic work - its updates while it works and its summary when it finishes say plainly what it did, what it found, and what it needs from you, with less jargon and fewer stock phrases.
|
||||||
|
- **Charts, diagrams, screenshots, and computer use:** reads visual material more accurately at every effort level without extra tooling - in Anthropic's testing, even at `low` it read charts more accurately than Claude Opus 5 at its highest effort, at roughly a tenth of the output tokens per chart (Claude Opus 5 read charts well only by running code to crop, zoom, and measure) - values on dense charts, and meaning that depends on position rather than text (which boxes an arrow connects, what changed between two diagram versions, exactly when a meeting starts and ends in a calendar screenshot). Also more reliable at multistep computer use from screenshots: at its default effort it matched the success rate Claude Opus 5 reached only at a much higher effort setting, in fewer steps and with roughly 40% fewer tokens.
|
||||||
|
|
||||||
|
### Behavioral shifts (prompt-tunable)
|
||||||
|
|
||||||
|
- **Re-evaluate Claude Opus 5-specific instructions.** Instructions tuned for Claude Opus 5's behavior (the verbosity, over-verification, and scope prompts under § Behavioral shifts of § Migrating to Claude Opus 5) may no longer be needed - keep them as the starting point, then re-test each on your own evals rather than carrying them over untouched.
|
||||||
|
- **Progress updates:** covered above - render the `thinking` blocks, and ask in the system prompt for the cadence you want.
|
||||||
|
- **Frontend design defaults:** asked for frontend work without design direction, it falls back on a few default styles, and a general instruction such as "avoid a generic AI look" mostly swaps one default for another. **It responds well to instructions that name specific patterns to avoid.** Work iteratively - look at which styles the first result used instead, and extend the list:
|
||||||
|
|
||||||
|
> *"Output a vanilla HTML/CSS personal website with placeholder data. Do not use a cream or off-white background, italic accent words in headlines, numbered "01/02/03" section labels, monospace labels, or pill-shaped buttons."*
|
||||||
|
|
||||||
|
- **Ingesting complex visual inputs:** it reads charts, diagrams, and screenshots considerably more precisely out of the box, so **harness scaffolding built for visual inputs on earlier models may no longer be needed - re-test it.** For the densest inputs, two things still add accuracy: higher-resolution images (most of all for technical drawings), and image-processing tools - run it as an agent with a container holding the raw images and libraries such as PIL and OpenCV so it can crop, zoom, measure, and verify; if a container is too much overhead, a cropping tool alone still helps. It uses these tools more effectively at higher effort levels; without tools, raising effort improves its reading of technical drawings but does little for charts.
|
||||||
|
- **Long turns:** at `xhigh` / `max`, turns run longer than on Claude Opus 5 - plan timeouts, streaming, and progress UX accordingly, and lower effort before prompting for brevity.
|
||||||
|
|
||||||
|
### Claude Opus 5.5 Migration Checklist
|
||||||
|
|
||||||
|
- [ ] **[BLOCKS]** Model ID -> `claude-opus-5-5` (Bedrock: `anthropic.claude-opus-5-5`). Coming from Opus 4.8 or older, the Claude Opus 5 checklist first - except that disabling thinking is not an option.
|
||||||
|
- [ ] **[BLOCKS]** Remove `thinking: {type: "disabled"}` and `{type: "enabled", budget_tokens}` on every route - both 400 at every effort level. Choose an effort level instead; size `max_tokens` for thinking plus the reply; read content blocks by `type`; pass `thinking` blocks back unmodified.
|
||||||
|
- [ ] **[BLOCKS]** Replace `tool_choice` `any` / `tool` with `auto` plus `strict: true` (steering in the prompt, and a check that the call happened) or structured outputs - on `count_tokens` and Batches too.
|
||||||
|
- [ ] **[BLOCKS]** Computer use: declare `{"type": "computer_toolset_20260801"}` (no beta header, no `name` / display size) instead of `computer_20251124`, and update the agent loop for member `tool_use` blocks (action = block `name`), batch actions, and `toolset_name` on every result; confirm the toolset is offered on your platform. Test on Claude Opus 5 first.
|
||||||
|
- [ ] **[BLOCKS]** If the harness builds `messages` itself: run the preserved-thinking three-step check (§ Migrating to Claude Fable 5.1 from Claude Fable 5) - accounts created on or after 2026-08-31 are enforced by default on every platform; set `prefix_mismatch_behavior` explicitly under `thinking-binding-controls-2026-08-01` and replace every history edit with its append-only form. Declare from the first request any tool the session may need later.
|
||||||
|
- [ ] **[BLOCKS]** Handle `stop_reason: "refusal"` before reading `content` (new `bio` and `reasoning_extraction` categories) and ship a fallback opt-in; `reasoning_extraction` is not retried on a fallback.
|
||||||
|
- [ ] **[TUNE]** Set `effort` explicitly - the default is `medium`, one level below Claude Opus 5's `high` - and re-run the sweep including `low` / `medium`; lower effort before adding "think less" prompts; reserve `xhigh` / `max` for measured gains; use per-message effort (beta) to vary it without a cache reset.
|
||||||
|
- [ ] **[TUNE]** If the UI showed text between tool calls: `display: "updates"` (beta) or `"summarized"`, render non-empty `thinking` blocks; give the model a send-message tool (declared at session start) for verbatim mid-turn content; ask in the system prompt for the update cadence you want.
|
||||||
|
- [ ] **[TUNE]** If a router or fallback can move the conversation to another model, expect it to run without Claude Opus 5.5's thinking blocks (only Claude Fable 5.1 / Claude Mythos 5.1 on the Claude API keep them).
|
||||||
|
- [ ] **[TUNE]** If thinking was disabled on Claude Opus 5: start at `low`, remove reasoning-in-the-response instructions, re-test the thinking-disabled mitigation instruction, delete any "don't think" rule.
|
||||||
|
- [ ] **[TUNE]** Re-test visual-input scaffolding (may be unnecessary now); for frontend work, name the specific default patterns to avoid rather than asking for "no generic look"; re-evaluate Claude Opus 5-specific verbosity / verification / scope instructions.
|
||||||
|
- [ ] **[TUNE]** Re-baseline cost and latency at the chosen effort level: $4 / $20, cache reads $0.20 per MTok; separate rate-limit pool; no Priority Tier; fast mode is Claude API only at $8 / $40.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
|
||||||
## Verify the Migration
|
## Verify the Migration
|
||||||
|
|
||||||
After updating, spot-check that the new model is actually being used. Replace `YOUR_TARGET_MODEL` with the model string you migrated to (e.g. `claude-fable-5-1`, `claude-opus-5`, `claude-opus-4-8`, `claude-opus-4-7`, `claude-sonnet-5`, `claude-sonnet-4-6`, `claude-haiku-4-5`) and keep the assertion prefix in sync:
|
After updating, spot-check that the new model is actually being used. Replace `YOUR_TARGET_MODEL` with the model string you migrated to (e.g. `claude-fable-5-1`, `claude-opus-5-5`, `claude-opus-5`, `claude-opus-4-8`, `claude-opus-4-7`, `claude-sonnet-5`, `claude-sonnet-4-6`, `claude-haiku-4-5`) and keep the assertion prefix in sync:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
YOUR_TARGET_MODEL = "claude-opus-5" # or "claude-opus-4-7", "claude-sonnet-5", "claude-sonnet-4-6", "claude-haiku-4-5"
|
YOUR_TARGET_MODEL = "claude-opus-5" # or "claude-opus-4-7", "claude-sonnet-5", "claude-sonnet-4-6", "claude-haiku-4-5"
|
||||||
@@ -1870,3 +2082,9 @@ m.capabilities["effort"]["max"]["supported"]
|
|||||||
```
|
```
|
||||||
|
|
||||||
See `shared/models.md` for the full capability lookup pattern.
|
See `shared/models.md` for the full capability lookup pattern.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ground the migration with an eval
|
||||||
|
|
||||||
|
A spot-check confirms the new model answers; it doesn't confirm the app still behaves the way the user wants. When the user reports a behavioral regression on the new model - e.g. *"it refuses things the old one handled fine"*, *"tool calls dropped off after the swap"*, *"responses got twice as long"* - don't tune the prompt by feel. Read `shared/evals/build-eval.md` and build a small eval that captures the regression, then read `shared/evals/eval-hillclimb.md` to iterate the prompt or harness against that eval until the score moves. Grounding the fix in an eval keeps the migration decision honest and leaves the user with a regression test for the next model swap.
|
||||||
|
|||||||
@@ -61,6 +61,7 @@ curl https://api.anthropic.com/v1/models/claude-opus-4-8 \
|
|||||||
| Claude Mythos 5.1 | `claude-mythos-5-1` | - | 1M | 128K | Active (Project Glasswing only) |
|
| Claude Mythos 5.1 | `claude-mythos-5-1` | - | 1M | 128K | Active (Project Glasswing only) |
|
||||||
| Claude Fable 5 | `claude-fable-5` | - | 1M | 128K | Active |
|
| Claude Fable 5 | `claude-fable-5` | - | 1M | 128K | Active |
|
||||||
| Claude Mythos 5 | `claude-mythos-5` | - | 1M | 128K | Active (Project Glasswing only) |
|
| Claude Mythos 5 | `claude-mythos-5` | - | 1M | 128K | Active (Project Glasswing only) |
|
||||||
|
| Claude Opus 5.5 | `claude-opus-5-5` | - | 1M | 128K | Active (launching; use only when the user names it) |
|
||||||
| Claude Opus 5 | `claude-opus-5` | - | 1M | 128K | Active |
|
| Claude Opus 5 | `claude-opus-5` | - | 1M | 128K | Active |
|
||||||
| Claude Opus 4.8 | `claude-opus-4-8` | - | 1M | 128K | Active |
|
| Claude Opus 4.8 | `claude-opus-4-8` | - | 1M | 128K | Active |
|
||||||
| Claude Opus 4.7 | `claude-opus-4-7` | - | 1M | 128K | Active |
|
| Claude Opus 4.7 | `claude-opus-4-7` | - | 1M | 128K | Active |
|
||||||
@@ -70,9 +71,10 @@ curl https://api.anthropic.com/v1/models/claude-opus-4-8 \
|
|||||||
| Claude Haiku 4.5 | `claude-haiku-4-5` | `claude-haiku-4-5-20251001` | 200K | 64K | Active |
|
| Claude Haiku 4.5 | `claude-haiku-4-5` | `claude-haiku-4-5-20251001` | 200K | 64K | Active |
|
||||||
|
|
||||||
### Model Descriptions
|
### Model Descriptions
|
||||||
- **Claude Fable 5.1** - Anthropic's most capable widely released model, for the most demanding reasoning and long-horizon agentic work. Successor to Claude Fable 5 in the same tier at the same per-token price ($10/$50 per MTok; cache reads $0.25/MTok - 0.025x, a quarter of Claude Fable 5's; batch $5/$25); stronger long-running agentic coding, knowledge work with documents/spreadsheets/slides, multistep research, vision, long-context retrieval, and computer use. Same API surface as Claude Fable 5 (thinking always on, no prefill, no sampling params, `refusal` stop reason, 512-token cache minimum) with three breaking changes: forced tool use (`tool_choice` `any` / `tool`) returns a 400; thinking blocks are bound to the producing model (only Claude Mythos 5.1 can read them - other models drop them); and editing earlier turns invalidates thinking blocks ("preserved thinking"; new accounts created on/after 2026-08-31 get a 400 on edited history; later models enforce it for everyone; the opt-in controls are per-platform - `shared/platform-availability.md`). Adds per-message `effort`, turn-scoped `clear_at` system messages, `thinking.display: "updates"` progress updates, and content provenance. Same tokenizer as Claude Fable 5; 1M context (default), 128K max output. Covered Model: 30-day retention required (ZDR only if expressly authorized by Anthropic) - ZDR orgs get `400 invalid_request_error`, as on Claude Fable 5. No Priority Tier; shares the Fable 5.x rate-limit pool. See `shared/model-migration.md` -> Migrating to Claude Fable 5.1 from Claude Fable 5.
|
- **Claude Fable 5.1** - Anthropic's most capable widely released model, for the most demanding reasoning and long-horizon agentic work. Successor to Claude Fable 5 in the same tier at the same per-token price ($10/$50 per MTok; cache reads $0.25/MTok - 0.025x, a quarter of Claude Fable 5's; batch $5/$25); stronger long-running agentic coding, knowledge work with documents/spreadsheets/slides, multistep research, vision, long-context retrieval, and computer use. Same API surface as Claude Fable 5 (thinking always on, no prefill, no sampling params, `refusal` stop reason, 512-token cache minimum) with three breaking changes: forced tool use (`tool_choice` `any` / `tool`) returns a 400; thinking blocks are bound to the producing model (only Claude Mythos 5.1 can read them - other models drop them); and editing earlier turns invalidates thinking blocks ("preserved thinking"; new accounts created on/after 2026-08-31 get a 400 on edited history on every platform, and enforcement scope is decided per model; the opt-in controls are per-platform - `shared/platform-availability.md`). Adds per-message `effort`, turn-scoped `clear_at` system messages, `thinking.display: "updates"` progress updates, and content provenance. Same tokenizer as Claude Fable 5; 1M context (default), 128K max output. Covered Model: 30-day retention required (ZDR only if expressly authorized by Anthropic) - ZDR orgs get `400 invalid_request_error`, as on Claude Fable 5. No Priority Tier; shares the Fable 5.x rate-limit pool. See `shared/model-migration.md` -> Migrating to Claude Fable 5.1 from Claude Fable 5.
|
||||||
- **Claude Fable 5** / **Claude Mythos 5** (`claude-fable-5` / `claude-mythos-5`) - the previous Fable / Mythos release: same tier, limits and per-token pricing as Claude Fable 5.1, which adds three breaking API changes over them (see above; cache reads here are $1/MTok rather than Claude Fable 5.1's $0.25); still served and selectable by id. Claude Mythos 5 ran no safety classifiers, so `stop_reason: "refusal"` does not occur on it. Prefer claude-fable-5-1 for new work.
|
- **Claude Fable 5** / **Claude Mythos 5** (`claude-fable-5` / `claude-mythos-5`) - the previous Fable / Mythos release: same tier, limits and per-token pricing as Claude Fable 5.1, which adds three breaking API changes over them (see above; cache reads here are $1/MTok rather than Claude Fable 5.1's $0.25); still served and selectable by id. Claude Mythos 5 ran no safety classifiers, so `stop_reason: "refusal"` does not occur on it. Prefer claude-fable-5-1 for new work.
|
||||||
- **Claude Mythos 5.1** - The same model as Claude Fable 5.1 (same capabilities, limits, per-token pricing, API behavior), offered only to approved Project Glasswing customers; successor to Claude Mythos 5 (which itself succeeded the invitation-only `claude-mythos-preview`). Unlike Claude Mythos 5 it runs safeguards that depend on the access program, so handle `stop_reason: "refusal"`. Not offered on Claude Platform on AWS. Use it only when the org participates in Project Glasswing; otherwise use `claude-fable-5-1`.
|
- **Claude Mythos 5.1** - The same model as Claude Fable 5.1 (same capabilities, limits, per-token pricing, API behavior), offered only to approved Project Glasswing customers; successor to Claude Mythos 5 (which itself succeeded the invitation-only `claude-mythos-preview`). Unlike Claude Mythos 5 it runs safeguards that depend on the access program, so handle `stop_reason: "refusal"`. Not offered on Claude Platform on AWS. Use it only when the org participates in Project Glasswing; otherwise use `claude-fable-5-1`.
|
||||||
|
- **Claude Opus 5.5** - Successor to Claude Opus 5 in the Opus line for long-running agentic coding and knowledge work, at a lower price ($4 / $20 per MTok; cache reads $0.20). Same 1M context, 128K output, tokenizer, and feature set as Claude Opus 5, with four breaking changes: thinking can't be disabled (effort is the only control, default `medium`), forced `tool_choice` 400s, thinking blocks are tied to the model and the conversation, and computer use needs the `computer_toolset_20260801` toolset. Broader safety classifiers (`bio` and `reasoning_extraction` join `cyber`). Use it only when the user names it until launch; see `shared/model-migration.md` -> Migrating to Claude Opus 5.5.
|
||||||
- **Claude Opus 5** - For complex agentic coding and enterprise work; a step-change over Claude Opus 4.8, strongest on deep reasoning, agentic and long-horizon work, and test-time compute scaling, at half the cost of Claude Fable 5.1 (Claude Fable 5.1 remains the highest-capability tier). Safety classifiers can return `stop_reason: "refusal"` - handle it before reading `content`. A drop-in upgrade at Opus 4.8's pricing ($5/$25 per MTok) with the same feature set. Thinking is on by default (omitting `thinking` runs adaptive; `{type: "adaptive"}` is equivalent), and `thinking: {type: "disabled"}` is available only at effort `high` or lower - pairing it with `xhigh`/`max` returns a 400. Raw thinking tokens are never returned. Full effort ladder through `max`; 512-token prompt-cache minimum (down from 1024 on Opus 4.8); fast mode on the Claude API only. Elevated cybersecurity safeguards. Separate rate-limit bucket from the combined Opus 4.x pool. 1M context window (default and maximum), 128K max output. See `shared/model-migration.md` -> Migrating to Claude Opus 5.
|
- **Claude Opus 5** - For complex agentic coding and enterprise work; a step-change over Claude Opus 4.8, strongest on deep reasoning, agentic and long-horizon work, and test-time compute scaling, at half the cost of Claude Fable 5.1 (Claude Fable 5.1 remains the highest-capability tier). Safety classifiers can return `stop_reason: "refusal"` - handle it before reading `content`. A drop-in upgrade at Opus 4.8's pricing ($5/$25 per MTok) with the same feature set. Thinking is on by default (omitting `thinking` runs adaptive; `{type: "adaptive"}` is equivalent), and `thinking: {type: "disabled"}` is available only at effort `high` or lower - pairing it with `xhigh`/`max` returns a 400. Raw thinking tokens are never returned. Full effort ladder through `max`; 512-token prompt-cache minimum (down from 1024 on Opus 4.8); fast mode on the Claude API only. Elevated cybersecurity safeguards. Separate rate-limit bucket from the combined Opus 4.x pool. 1M context window (default and maximum), 128K max output. See `shared/model-migration.md` -> Migrating to Claude Opus 5.
|
||||||
- **Claude Opus 4.8** - The most capable model in the Opus 4 series - highly autonomous, state-of-the-art on long-horizon agentic work, knowledge work, and memory; clearer, warmer writing. Same API surface as Opus 4.7 (adaptive thinking only; sampling parameters and `budget_tokens` removed). 1M context window at standard API pricing (no long-context premium). See `shared/model-migration.md` -> Migrating to Opus 4.8 - a 4.7 -> 4.8 move is a model-ID swap plus prompt re-tuning, no new breaking changes.
|
- **Claude Opus 4.8** - The most capable model in the Opus 4 series - highly autonomous, state-of-the-art on long-horizon agentic work, knowledge work, and memory; clearer, warmer writing. Same API surface as Opus 4.7 (adaptive thinking only; sampling parameters and `budget_tokens` removed). 1M context window at standard API pricing (no long-context premium). See `shared/model-migration.md` -> Migrating to Opus 4.8 - a 4.7 -> 4.8 move is a model-ID swap plus prompt re-tuning, no new breaking changes.
|
||||||
- **Claude Opus 4.7** - Previous-generation Opus. Highly autonomous; strong on long-horizon agentic work, knowledge work, vision, and memory. Adaptive thinking only; sampling parameters and `budget_tokens` removed. 1M context window. See `shared/model-migration.md` -> Migrating to Opus 4.7.
|
- **Claude Opus 4.7** - Previous-generation Opus. Highly autonomous; strong on long-horizon agentic work, knowledge work, vision, and memory. Adaptive thinking only; sampling parameters and `budget_tokens` removed. 1M context window. See `shared/model-migration.md` -> Migrating to Opus 4.7.
|
||||||
@@ -123,6 +125,7 @@ When a user asks for a model by name, use this table to find the correct model I
|
|||||||
| "mythos preview" | `claude-mythos-5-1` (successor to `claude-mythos-preview` - see migration guide) |
|
| "mythos preview" | `claude-mythos-5-1` (successor to `claude-mythos-preview` - see migration guide) |
|
||||||
| "opus" | `claude-opus-5` |
|
| "opus" | `claude-opus-5` |
|
||||||
| "opus 5" | `claude-opus-5` |
|
| "opus 5" | `claude-opus-5` |
|
||||||
|
| "opus 5.5" | `claude-opus-5-5` (launching - see migration guide) |
|
||||||
| "opus 4.8" | `claude-opus-4-8` |
|
| "opus 4.8" | `claude-opus-4-8` |
|
||||||
| "opus 4.7" | `claude-opus-4-7` |
|
| "opus 4.7" | `claude-opus-4-7` |
|
||||||
| "opus 4.6" | `claude-opus-4-6` |
|
| "opus 4.6" | `claude-opus-4-6` |
|
||||||
|
|||||||
@@ -7,47 +7,48 @@ Columns: **1P** = first-party Claude API, **P-AWS** = Claude Platform on AWS (An
|
|||||||
| Feature | 1P | P-AWS | Bedrock | Vertex | Foundry | Notes |
|
| Feature | 1P | P-AWS | Bedrock | Vertex | Foundry | Notes |
|
||||||
|---|---|---|---|---|---|---|
|
|---|---|---|---|---|---|---|
|
||||||
| Messages, streaming, tool use | Yes | Yes | Yes | Yes | Yes | Core API |
|
| Messages, streaming, tool use | Yes | Yes | Yes | Yes | Yes | Core API |
|
||||||
| PDF input | Yes | Yes | Yes | Yes | beta | |
|
| PDF input | Yes | Yes | Yes | Yes | Yes | |
|
||||||
| Structured outputs / strict tool use | Yes | Yes | Yes | Yes | beta | |
|
| Structured outputs / strict tool use | Yes | Yes | Yes | Yes | Yes | |
|
||||||
| Adaptive thinking / effort | Yes | Yes | Yes | Yes | beta | |
|
| Adaptive thinking / effort | Yes | Yes | Yes | Yes | Yes | |
|
||||||
| Extended thinking | Yes | Yes | Yes | Yes | beta | |
|
| Extended thinking | Yes | Yes | Yes | Yes | Yes | |
|
||||||
| Prompt caching (5m, 1h) | Yes | Yes | Yes | Yes | Yes | |
|
| Prompt caching (5m, 1h) | Yes | Yes | Yes | Yes | Yes | |
|
||||||
| Automatic prompt caching | Yes | Yes | Yes | Yes | Yes | The legacy Bedrock integration (Opus 4.6 and earlier) rejects top-level `cache_control` with a 400 - explicit breakpoints only there |
|
| Automatic prompt caching | Yes | Yes | Yes | Yes | Yes | The legacy Bedrock integration (Opus 4.6 and earlier) rejects top-level `cache_control` with a 400 - explicit breakpoints only there |
|
||||||
| Token counting | Yes | Yes | Yes | Yes | beta | |
|
| Token counting | Yes | Yes | Yes | Yes | Yes | |
|
||||||
| Citations | Yes | Yes | Yes | Yes | beta | |
|
| Citations | Yes | Yes | Yes | Yes | Yes | |
|
||||||
| Search results content blocks | Yes | Yes | Yes | Yes | beta | |
|
| Search results content blocks | Yes | Yes | Yes | Yes | Yes | |
|
||||||
| Fine-grained tool streaming | Yes | Yes | Yes | Yes | Yes | |
|
| Fine-grained tool streaming | Yes | Yes | Yes | Yes | Yes | Bedrock: `eager_input_streaming` on the newer serving stack only (Opus 4.7/4.8/5, Fable 5, Sonnet 4.6/5); older deployments (Opus 4.5/4.6, Sonnet 4.0/4.5, Haiku 4.5) 400 on the field |
|
||||||
| Compaction | beta | beta | beta | beta | beta | |
|
| Compaction | beta | beta | beta | beta | beta | |
|
||||||
| Context editing | beta | beta | beta | beta | beta | |
|
| Context editing | beta | beta | beta | beta | beta | |
|
||||||
| Context windows (1M) | Yes | Yes | Yes | Yes | beta | |
|
| Context windows (1M) | Yes | Yes | Yes | Yes | Yes | |
|
||||||
| `inference_geo` (data residency) | Yes | Yes | No | No | No | |
|
| `inference_geo` (data residency) | Yes | Yes | No | No | No | |
|
||||||
| **Server-side tools** | | | | | | |
|
| **Server-side tools** | | | | | | |
|
||||||
| Web search | Yes | Yes | No | Yes | beta | Vertex: basic `web_search_20250305` only (no `_20260209` dynamic filtering) |
|
| Web search | Yes | Yes | No | Yes | Yes | Vertex: basic `web_search_20250305` only (no `_20260209` dynamic filtering). Foundry Hosted on Azure: basic `web_search_20250305` only |
|
||||||
| Web fetch | Yes | Yes | No | No | beta | |
|
| Web fetch | Yes | Yes | No | No | Yes | Foundry Hosted on Azure: basic `web_fetch_20250910` only |
|
||||||
| Code execution | Yes | Yes | No | No | beta | |
|
| Code execution | Yes | Yes | No | No | Yes | Foundry: Hosted on Anthropic deployments only - Hosted on Azure returns a 400 |
|
||||||
| Tool search | Yes | Yes | Yes | Yes | beta | Bedrock: InvokeModel API only, not Converse |
|
| Tool search | Yes | Yes | Yes | Yes | Yes | Bedrock: InvokeModel API only, not Converse |
|
||||||
| Advisor tool | beta | beta | No | No | No | |
|
| Advisor tool | beta | beta | No | No | No | |
|
||||||
| **Client-implemented tools** | | | | | | |
|
| **Client-implemented tools** | | | | | | |
|
||||||
| Bash, text editor, memory | Yes | Yes | Yes | Yes | beta | |
|
| Bash, text editor, memory | Yes | Yes | Yes | Yes | Yes | |
|
||||||
| Computer use | beta | beta | beta | beta | beta | |
|
| Computer use | beta | beta | beta | beta | beta | `computer_20251124` and older versions: beta on all five platforms. Claude Opus 5.5 accepts only `computer_toolset_20260801`: GA on the Claude API and Google Cloud with no beta header, not offered on the other platforms - toolset availability is not final, confirm at launch (`shared/model-migration.md` -> Migrating to Claude Opus 5.5, breaking change 4) |
|
||||||
| **Agentic / orchestration** | | | | | | |
|
| **Agentic / orchestration** | | | | | | |
|
||||||
| Agent Skills (Messages API) | Yes | Yes | No | No | beta | |
|
| Agent Skills (Messages API) | Yes | Yes | No | No | beta | Foundry: Hosted on Anthropic deployments only - Hosted on Azure returns a 400 |
|
||||||
| Programmatic tool calling | Yes | Yes | No | No | beta | |
|
| Programmatic tool calling | Yes | Yes | No | No | Yes | Foundry: Hosted on Anthropic deployments only - Hosted on Azure returns a 400 |
|
||||||
| MCP connector | beta | beta | No | No | beta | |
|
| MCP connector | beta | beta | No | No | beta | |
|
||||||
| Managed Agents | beta | beta | No | No | No | Foundry: No (inferred; not in Foundry docs either way) |
|
| Managed Agents | beta | beta | No | No | No | Foundry: No (inferred; not in Foundry docs either way) |
|
||||||
| Self-hosted sandboxes | beta | beta | No | No | No | P-AWS: worker authenticates with IAM/SigV4 or an AWS-Console API key + `AnthropicSelfHostedEnvironmentAccess` (Console environment keys don't work there); sessions on self-hosted environments cannot attach memory stores; `GET /v1/environments/{id}/work` list endpoint not supported, other work endpoints OK |
|
| Self-hosted sandboxes | beta | beta | No | No | No | P-AWS: worker authenticates with IAM/SigV4 or an AWS-Console API key + `AnthropicSelfHostedEnvironmentAccess` (Console environment keys don't work there); sessions on self-hosted environments cannot attach memory stores; `GET /v1/environments/{id}/work` list endpoint not supported, other work endpoints OK |
|
||||||
| **API endpoints** | | | | | | |
|
| **API endpoints** | | | | | | |
|
||||||
| Message Batches | Yes | Yes | No | No | No | |
|
| Message Batches | Yes | Yes | No | No | No | |
|
||||||
| Files API | Yes | Yes | No | No | beta | |
|
| Files API | Yes | Yes | No | No | beta | Foundry: Hosted on Anthropic deployments only - Hosted on Azure returns a 400 |
|
||||||
| Models API | Yes | Yes | No | No | No | |
|
| Models API | Yes | Yes | No | No | No | |
|
||||||
| **Other** | | | | | | |
|
| **Other** | | | | | | |
|
||||||
| Mid-conversation system messages | Yes | Yes | Yes | Yes | No | Claude Opus 5, Claude Opus 4.8, Claude Fable 5, Claude Fable 5.1, Claude Mythos 5, Claude Mythos 5.1; not Claude Sonnet 5. Bedrock: InvokeModel passthrough, not ARN-versioned models |
|
| Mid-conversation system messages | Yes | Yes | Yes | Yes | No | Claude Opus 5, Claude Opus 5.5, Claude Opus 4.8, Claude Fable 5, Claude Fable 5.1, Claude Mythos 5, Claude Mythos 5.1; not Claude Sonnet 5. Bedrock: InvokeModel passthrough, not ARN-versioned models |
|
||||||
|
| Mid-conversation tool changes | beta | beta | beta | beta | No | Same models as mid-conversation system messages; beta `mid-conversation-tool-changes-2026-07-01` |
|
||||||
| Turn-scoped (`clear_at`) system messages | beta | beta | beta | beta | No | Same models as mid-conversation system messages; beta `mid-conversation-system-clear-at-2026-08-21` (on Bedrock/Vertex pass the value as a beta) |
|
| Turn-scoped (`clear_at`) system messages | beta | beta | beta | beta | No | Same models as mid-conversation system messages; beta `mid-conversation-system-clear-at-2026-08-21` (on Bedrock/Vertex pass the value as a beta) |
|
||||||
| Per-message `effort` (system message `output_config`) | beta | No | No | No | No | Claude Fable 5.1, Claude Mythos 5.1, Claude Opus 5; beta `mid-conversation-output-config-2026-07-01`; Claude API at launch (Bedrock/Vertex/Foundry unconfirmed; Claude Opus 5 excluded on Bedrock) |
|
| Per-message `effort` (system message `output_config`) | beta | No | No | No | No | Claude Fable 5.1, Claude Mythos 5.1, Claude Opus 5, Claude Opus 5.5; beta `mid-conversation-output-config-2026-07-01`; Claude API at launch (Bedrock/Vertex/Foundry unconfirmed; Claude Opus 5 excluded on Bedrock) |
|
||||||
| `thinking.display: "updates"` | beta | beta | beta | beta | beta | Claude Fable 5.1, Claude Mythos 5.1, Claude Fable 5; beta `thinking-display-updates-2026-08-18` (pass the beta value per platform); without it `"updates"` is rejected as an unknown `display` value |
|
| `thinking.display: "updates"` | beta | beta | beta | beta | beta | Claude Fable 5.1, Claude Mythos 5.1, Claude Fable 5, Claude Opus 5.5; beta `thinking-display-updates-2026-08-18` (pass the beta value per platform); without it `"updates"` is rejected as an unknown `display` value |
|
||||||
| Thinking block-binding controls | beta | beta | per model | per model | No | `thinking.block_binding` + `input_transformations`; beta `thinking-binding-controls-2026-08-01` (on Bedrock via the `anthropic_beta` body field); the controls beta arrives per model on Bedrock/Vertex - until then the header is rejected; the history-editing enforcement itself follows the account-age rule in `shared/model-migration.md` -> Migrating to Claude Fable 5.1 from Claude Fable 5 |
|
| Thinking block-binding controls | beta | beta | per model | per model | No | `thinking.block_binding` + `input_transformations`; beta `thinking-binding-controls-2026-08-01` (on Bedrock via the `anthropic_beta` body field); the controls beta arrives per model on Bedrock/Vertex - until then the header is rejected; the history-editing enforcement itself follows the account-age rule in `shared/model-migration.md` -> Migrating to Claude Fable 5.1 from Claude Fable 5 |
|
||||||
| Server-side `fallbacks` | beta | beta | No | No | No | `"default"` -> beta `server-side-fallback-2026-07-01`; array form -> beta `server-side-fallback-2026-06-01` |
|
| Server-side `fallbacks` | beta | beta | No | No | No | `"default"` -> beta `server-side-fallback-2026-07-01`; array form -> beta `server-side-fallback-2026-06-01` |
|
||||||
| Fast mode | beta | No | No | No | No | Research preview, beta `fast-mode-2026-02-01`, first-party API only |
|
| Fast mode | beta | No | No | No | No | Research preview, beta `fast-mode-2026-02-01`, first-party API only (Claude Opus 5 / Opus 4.8 at $10 / $50; Claude Opus 5.5 at $8 / $40 - its fast-mode docs flip after the model launch, confirm before quoting) |
|
||||||
| Cache diagnostics | beta | No | No | No | No | First-party API only |
|
| Cache diagnostics | beta | No | No | No | No | First-party API only |
|
||||||
| Task budgets | beta | beta | No | No | No | Beta header `task-budgets-2026-03-13`; 3P availability not documented - assume unsupported |
|
| Task budgets | beta | beta | No | No | No | Beta header `task-budgets-2026-03-13`; 3P availability not documented - assume unsupported |
|
||||||
|
|
||||||
|
|||||||
@@ -78,14 +78,15 @@ These aren't tuned down; they're swapped for the feature that replaced them. For
|
|||||||
|---|---|
|
|---|---|
|
||||||
| "Think step by step", `<scratchpad>`/`<thinking>` tag instructions | Adaptive thinking (`thinking: {type: "adaptive"}`) + `effort`. On thinking models the incantation is redundant at best; control depth via configuration, not prose. |
|
| "Think step by step", `<scratchpad>`/`<thinking>` tag instructions | Adaptive thinking (`thinking: {type: "adaptive"}`) + `effort`. On thinking models the incantation is redundant at best; control depth via configuration, not prose. |
|
||||||
| "Use the think tool to plan" / "plan before acting" | Delete - current models plan without being told, and these cause over-planning. If behavior is still too aggressive after cleanup, lower `effort` rather than adding prose. |
|
| "Use the think tool to plan" / "plan before acting" | Delete - current models plan without being told, and these cause over-planning. If behavior is still too aggressive after cleanup, lower `effort` rather than adding prose. |
|
||||||
| "Show your thinking" / required reasoning sections in the output | Read thinking blocks via the API. On Claude Fable 5.1, instructing reasoning reproduction can trigger a `refusal` (reasoning extraction) - this is an explicit audit item when migrating. |
|
| Prose that steers thinking depth ("think harder", "think less", "don't overthink", "answer without deliberating"), and any rule telling the model not to think | `effort`. Where thinking is always on (Claude Fable 5.1, Claude Opus 5.5) effort is the only thinking control, and lowering it cuts thinking, cost, and latency more reliably than prose; a "don't think" rule can't be followed there. Keep a "reply directly" line only where a measurement on a latency-sensitive route shows it helps. |
|
||||||
|
| "Show your thinking" / required reasoning sections in the output | Read thinking blocks via the API. On Claude Fable 5.1 and Claude Opus 5.5, instructing reasoning reproduction can trigger a `refusal` (reasoning extraction, not retried on a fallback) - this is an explicit audit item when migrating. |
|
||||||
| Assistant-turn prefill (`{"role": "assistant", "content": "{"`) and the JSON-forcing stack around it: stop-sequences, regex extraction, retry-on-parse loops, "output ONLY valid JSON" | Structured outputs (`output_config.format`). Prefill 400s on 4.6-and-later Opus- and Sonnet-tier models and Claude Fable 5.1 - confirm in the per-target section of `shared/model-migration.md` before claiming the error. Where it applies, the *surrounding code* is cruft too - audit the request builder, not just the prompt string. Only a **trailing** assistant turn is a prefill - partial or complete-looking (a few-shot block ending on the assistant side still counts): assistant turns mid-array are ordinary conversation history and must stay. |
|
| Assistant-turn prefill (`{"role": "assistant", "content": "{"`) and the JSON-forcing stack around it: stop-sequences, regex extraction, retry-on-parse loops, "output ONLY valid JSON" | Structured outputs (`output_config.format`). Prefill 400s on 4.6-and-later Opus- and Sonnet-tier models and Claude Fable 5.1 - confirm in the per-target section of `shared/model-migration.md` before claiming the error. Where it applies, the *surrounding code* is cruft too - audit the request builder, not just the prompt string. Only a **trailing** assistant turn is a prefill - partial or complete-looking (a few-shot block ending on the assistant side still counts): assistant turns mid-array are ordinary conversation history and must stay. |
|
||||||
| "Summarize progress every N tool calls" choreography; hard word caps (`at most N words`) | Delete and re-baseline: current models narrate appropriately, and output caps starve reasoning on hard problems. Prefer qualitative length guidance ("be concise") over numeric caps tuned against an older model's verbosity. |
|
| "Summarize progress every N tool calls" choreography; hard word caps (`at most N words`) | Delete and re-baseline: current models narrate appropriately, and output caps starve reasoning on hard problems. Prefer qualitative length guidance ("be concise") over numeric caps tuned against an older model's verbosity. |
|
||||||
| Inline lookup tables, point systems, arithmetic rubrics the model must compute | Data in files or tool results; arithmetic in code. Leave the model the judgment layer. |
|
| Inline lookup tables, point systems, arithmetic rubrics the model must compute | Data in files or tool results; arithmetic in code. Leave the model the judgment layer. |
|
||||||
| `budget_tokens`, non-default `temperature`/`top_p`/`top_k`, stale beta headers, dead 400-retry paths | See `shared/model-migration.md` - whether each one hard-errors or is merely deprecated depends on the target model, so take the error claim from the per-target section there, not from memory. Where it does error, the retry/workaround code around it is removable too. |
|
| `budget_tokens`, non-default `temperature`/`top_p`/`top_k`, stale beta headers, dead 400-retry paths | See `shared/model-migration.md` - whether each one hard-errors or is merely deprecated depends on the target model, so take the error claim from the per-target section there, not from memory. Where it does error, the retry/workaround code around it is removable too. |
|
||||||
| Forced tool use - `tool_choice: {type: "any"}` / `{type: "tool", name: ...}` - and the JSON-via-forced-tool pattern | Prompt instruction naming the tool under `tool_choice: auto` (steering), or structured outputs (extraction). Returns a 400 on Claude Fable 5.1 / Claude Mythos 5.1 (and Mythos Preview); elsewhere it works but is usually a prompt-instruction in disguise - `strict: true` keeps the schema guarantee under `auto`. Audit the retry-on-missing-tool loop around it as well. |
|
| Forced tool use - `tool_choice: {type: "any"}` / `{type: "tool", name: ...}` - and the JSON-via-forced-tool pattern | Prompt instruction naming the tool under `tool_choice: auto` (steering), or structured outputs (extraction). Returns a 400 on Claude Fable 5.1 / Claude Mythos 5.1 / Claude Opus 5.5 (and Mythos Preview); elsewhere it works but is usually a prompt-instruction in disguise - `strict: true` keeps the schema guarantee under `auto`. Audit the retry-on-missing-tool loop around it as well. |
|
||||||
|
|
||||||
**Signals:** `think step by step|take a deep breath`; `<scratchpad>|<thinking>` in instructions; `stop_sequences` guarding JSON; `json.loads` inside retry loops; `budget_tokens|temperature|top_p` in request code; `every \d+ (tool calls|messages)`; `at most \d+ (words|sentences)`.
|
**Signals:** `think step by step|take a deep breath`; `think (harder|less)|don'?t overthink|do not think`; `<scratchpad>|<thinking>` in instructions; `stop_sequences` guarding JSON; `json.loads` inside retry loops; `budget_tokens|temperature|top_p` in request code; `every \d+ (tool calls|messages)`; `at most \d+ (words|sentences)`.
|
||||||
|
|
||||||
#### 1c. Over-specification - describe the goal, not the method
|
#### 1c. Over-specification - describe the goal, not the method
|
||||||
|
|
||||||
@@ -105,21 +106,25 @@ These aren't tuned down; they're swapped for the feature that replaced them. For
|
|||||||
|
|
||||||
| Pattern | Why it's cruft now | Fix |
|
| Pattern | Why it's cruft now | Fix |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| Model-version workarounds: formatting fixes, over-refusal softeners, retry hints, "known issue with [model]" comments, date-conditional guidance | Nobody owns the removal, so prompts accumulate the union of every generation's mitigations | Each mitigation names (or gets traced to) the model it patched; if that model is retired, remove and re-test |
|
| Model-version workarounds: formatting fixes, over-refusal softeners, retry hints, "known issue with [model]" comments, date-conditional guidance | Nobody owns the removal, so prompts accumulate the union of every generation's mitigations | Each mitigation names (or gets traced to) the model it patched; if that model is retired, remove and re-test. Targeting Claude Opus 5.5, the verbosity, over-verification, and scope instructions written for Claude Opus 5 (`shared/model-migration.md` -> Migrating to Claude Opus 5 -> Behavioral shifts) are the named re-test candidates: keep them as the starting point and test each removal on your own evals |
|
||||||
|
| Thinking-disabled mitigations: the combined "say a sentence before a tool call / say so if no tool fits / no internal XML tags" instruction, and reasoning-in-the-response substitutes for thinking | Written for Claude Opus 5 running with thinking off, where those artifacts appear; on Claude Opus 5.5 thinking is always on and the instruction may be dead weight (the reasoning-substitute half can also be declined as `reasoning_extraction`) | Re-test and remove what no longer reproduces; read reasoning from `display: "summarized"` blocks (see `shared/model-migration.md` -> Migrating to Claude Opus 5.5 -> Prompts written for thinking disabled) |
|
||||||
|
| Visual-input scaffolding: step-by-step chart-reading instructions, OCR or table-extraction pre-passes, mandatory crop or zoom steps | Built for weaker vision; Claude Opus 5.5 reads charts, diagrams, and screenshots considerably more precisely without tools | Remove one piece at a time and re-test on your own images. Keep image-processing tools (crop, zoom, measure in a container) and higher-resolution inputs for the densest material - they still add accuracy, most of all on technical drawings - so this is a finding about prompt text and pre-passes, not about tools |
|
||||||
| Migration-relative phrasing: "X now works differently", "also counts", "no longer" | The text is a diff against a previous prompt version the model never saw; relative phrasing implies phantom alternatives | Write as if current rules are the only rules that ever existed |
|
| Migration-relative phrasing: "X now works differently", "also counts", "no longer" | The text is a diff against a previous prompt version the model never saw; relative phrasing implies phantom alternatives | Write as if current rules are the only rules that ever existed |
|
||||||
| Patch accretion: many narrow conditionals, each traceable to one incident | The model navigates a maze of special cases instead of a coherent principle, and fails unpredictably between them; an eval win for adding a line on top of the stack is not evidence the stack should exist | Generalize the principle or fix the underlying context; test removals, not just additions |
|
| Patch accretion: many narrow conditionals, each traceable to one incident | The model navigates a maze of special cases instead of a coherent principle, and fails unpredictably between them; an eval win for adding a line on top of the stack is not evidence the stack should exist | Generalize the principle or fix the underlying context; test removals, not just additions |
|
||||||
| Unenforced instructions: rules no code path, eval, or reviewer checks - visibly violated in the app's own transcripts | If nothing checks it and nobody noticed, it carries no signal - and behavioral rules that could be hooks, allowlists, or schema validators are less reliable as prose | Enforce in code what can be enforced in code; delete what nothing enforces and nobody misses |
|
| Unenforced instructions: rules no code path, eval, or reviewer checks - visibly violated in the app's own transcripts | If nothing checks it and nobody noticed, it carries no signal - and behavioral rules that could be hooks, allowlists, or schema validators are less reliable as prose | Enforce in code what can be enforced in code; delete what nothing enforces and nobody misses |
|
||||||
| Identity stubs standing in for context ("You are a helpful assistant") | A role line is fine as a one-sentence focus-setter; the defect is an identity statement *substituting* for audience, product, and quality bar | Don't flag a short role line; flag when it's the only context the prompt gives |
|
| Identity stubs standing in for context ("You are a helpful assistant") | A role line is fine as a one-sentence focus-setter; the defect is an identity statement *substituting* for audience, product, and quality bar | Don't flag a short role line; flag when it's the only context the prompt gives |
|
||||||
| Update suppressors written for chatty models: "hold all findings for the final response", "don't narrate", "no interim updates" | Tuned against models that over-narrated; current models (Claude Fable 5.1 especially) under-narrate with these present, and the harness may not be requesting the model's between-tool progress notes at all (`thinking.display: "updates"`) | Remove first and re-test; if more narration is still wanted, replace with a specific line saying *when* user-facing text is wanted (see `shared/model-migration.md` -> Migrating to Claude Fable 5.1 from Claude Fable 5 -> User-facing progress updates) |
|
| Update suppressors written for chatty models: "hold all findings for the final response", "don't narrate", "no interim updates" | Tuned against models that over-narrated; current models (Claude Fable 5.1 and Claude Opus 5.5 especially) under-narrate with these present, and the harness may not be requesting the model's between-tool progress notes at all - on both they come back as `thinking` blocks (`thinking.display: "updates"`), so a client that renders only `text` blocks looks silent | Remove first and re-test; if more narration is still wanted, replace with a specific line saying *when* user-facing text is wanted (see `shared/model-migration.md` -> Migrating to Claude Fable 5.1 from Claude Fable 5 -> User-facing progress updates, and Migrating to Claude Opus 5.5 -> Text between tool calls comes back in thinking blocks) |
|
||||||
| Anti-formatting rules: "never use bullets", "no headers", "no bold" | Written against models that over-formatted; Claude Fable 5.1 already under-formats, so the rule now strips formatting the reader wanted | Remove, or replace with a rule that says when formatting is appropriate (the conditional-formatting snippet in the Claude Fable 5.1 migration section) |
|
| Anti-formatting rules: "never use bullets", "no headers", "no bold" | Written against models that over-formatted; Claude Fable 5.1 already under-formats, so the rule now strips formatting the reader wanted | Remove, or replace with a rule that says when formatting is appropriate (the conditional-formatting snippet in the Claude Fable 5.1 migration section) |
|
||||||
| Instruction re-insertion every few turns ("reminder: ..." repeated on a cadence in the harness) | A retention crutch for models that lost instructions over long sessions; current models retain a once-stated instruction, and each repeat costs tokens and, under preserved thinking's history-editing check, is a history edit if it is later removed | Remove the repetition and re-test; where a genuinely per-turn reminder remains, send it as a turn-scoped (`clear_at`) system message - or a text block after the tool results - and never delete earlier copies |
|
| Instruction re-insertion every few turns ("reminder: ..." repeated on a cadence in the harness) | A retention crutch for models that lost instructions over long sessions; current models retain a once-stated instruction, and each repeat costs tokens and, under preserved thinking's history-editing check, is a history edit if it is later removed | Remove the repetition and re-test; where a genuinely per-turn reminder remains, send it as a turn-scoped (`clear_at`) system message - or a text block after the tool results - and never delete earlier copies |
|
||||||
|
|
||||||
**Signals:** retired model names in prompts or comments (`claude-2|claude-3|claude-instant|3\.5|3\.7`); `hold (all )?(findings|results)|don't narrate|no interim`; `never use (bullets|headers|bold)|no (bullet|header)`; `reminder:` on a turn cadence; `before|after [date]` conditionals; `now|no longer|instead of` attached to behavioral rules; rules whose reason nobody remembers; `^You are (a|an) (helpful|expert)` with nothing task-specific following.
|
**Signals:** retired model names in prompts or comments (`claude-2|claude-3|claude-instant|3\.5|3\.7`); `hold (all )?(findings|results)|don't narrate|no interim`; `internal (XML )?tags|before (each|a) tool call` mitigations; `OCR|crop|zoom|axis labels` in image-reading prompts; `never use (bullets|headers|bold)|no (bullet|header)`; `reminder:` on a turn cadence; `before|after [date]` conditionals; `now|no longer|instead of` attached to behavioral rules; rules whose reason nobody remembers; `^You are (a|an) (helpful|expert)` with nothing task-specific following.
|
||||||
|
|
||||||
#### 1e. Prohibition clusters - judge by provenance, not by whether the model "needs it"
|
#### 1e. Prohibition clusters - judge by provenance, not by whether the model "needs it"
|
||||||
|
|
||||||
A run of unconditional "never / don't / must not" lines is audited by asking, for each, **does it carry a stated reason or encode a real business/policy constraint?** - not "does the target model still need this guardrail?" (the latter question keeps everything, because nothing is *harmful* to say). Prohibitions that encode observable constraints (refund caps, data rules, compliance language, promises the business must not make) stay, ideally with their reason beside them. Prohibitions that merely describe an undesirable *output style* with no provenance - banned phrases, tic lists, "don't start with 'Certainly'" written against an older model's habits - are cruft: restate the desired style positively in one line, or attach the real reason if there is one. A surrounding cluster of legitimate reasoned prohibitions does not launder the no-provenance ones mixed into it; classify each line separately.
|
A run of unconditional "never / don't / must not" lines is audited by asking, for each, **does it carry a stated reason or encode a real business/policy constraint?** - not "does the target model still need this guardrail?" (the latter question keeps everything, because nothing is *harmful* to say). Prohibitions that encode observable constraints (refund caps, data rules, compliance language, promises the business must not make) stay, ideally with their reason beside them. Prohibitions that merely describe an undesirable *output style* with no provenance - banned phrases, tic lists, "don't start with 'Certainly'" written against an older model's habits - are cruft: restate the desired style positively in one line, or attach the real reason if there is one. A surrounding cluster of legitimate reasoned prohibitions does not launder the no-provenance ones mixed into it; classify each line separately.
|
||||||
|
|
||||||
|
**One exception to "restate positively": frontend design direction on Claude Opus 5.5.** Asked for frontend work without direction, it falls back on a few default styles, and a general "avoid a generic AI look" mostly swaps one default for another - that vague line is the finding. A list that names the specific defaults to avoid (a cream background, italic accent words in headlines, numbered "01/02/03" section labels, monospace labels, pill-shaped buttons) is the form that works: keep it, and extend it from the styles the first result used instead. Propose rewriting the vague line into named patterns, never deleting the list.
|
||||||
|
|
||||||
#### 1f. Output-shaping choreography - one pattern, remove every limb
|
#### 1f. Output-shaping choreography - one pattern, remove every limb
|
||||||
|
|
||||||
Fixed interim-update cadences ("after every third tool call, post a progress note"), numeric output ceilings ("under 120 words", "at most five bullets"), and cut-the-detail instructions are manifestations of the **same** over-constraint pattern, written for models that padded or rambled. They are removed *together*: a stated operational reason ("queue throughput", "supervisors skim") does not convert a numeric clamp into a keeper - re-express the goal as audience/outcome framing without the number ("replies are scan-able and answer only what was asked"), and keep any genuinely format-sensitive requirement as a format instruction, not a word count. Removing the cadence while keeping the ceilings leaves the pattern in place.
|
Fixed interim-update cadences ("after every third tool call, post a progress note"), numeric output ceilings ("under 120 words", "at most five bullets"), and cut-the-detail instructions are manifestations of the **same** over-constraint pattern, written for models that padded or rambled. They are removed *together*: a stated operational reason ("queue throughput", "supervisors skim") does not convert a numeric clamp into a keeper - re-express the goal as audience/outcome framing without the number ("replies are scan-able and answer only what was asked"), and keep any genuinely format-sensitive requirement as a format instruction, not a word count. Removing the cadence while keeping the ceilings leaves the pattern in place.
|
||||||
@@ -162,6 +167,8 @@ Skill files (`SKILL.md`, `CLAUDE.md`, rule files) inherit everything in Group 1,
|
|||||||
The same audit keeps surfacing these next to prompt cruft; report them even though they're not prompt text.
|
The same audit keeps surfacing these next to prompt cruft; report them even though they're not prompt text.
|
||||||
|
|
||||||
- **API fossils**: parameters and headers that error or are deprecated on the target model - the per-model lists live in `shared/model-migration.md`; treat each migration checklist as a removal checklist.
|
- **API fossils**: parameters and headers that error or are deprecated on the target model - the per-model lists live in `shared/model-migration.md`; treat each migration checklist as a removal checklist.
|
||||||
|
- **Thinking config and `max_tokens` sized for the wrong model**: `thinking: {type: "disabled"}` and `budget_tokens` 400 on Claude Opus 5.5 (thinking is always on - remove the field and set `effort`, default `medium`), and a `max_tokens` sized for a thinking-off route cuts replies off, because thinking counts toward it even when its text isn't returned (64K is a reasonable start for long agentic coding turns).
|
||||||
|
- **History-editing harness**: request-building code that rewrites the `system` prompt, the `tools` array, or earlier messages mid-session - including deleting a per-turn reminder, or adding a tool late (declare any tool the session may need, such as a send-the-user-a-message tool, from the first request) - invalidates preserved-thinking blocks on Claude Fable 5.1 and Claude Opus 5.5. Report each edit site with its append-only replacement from `shared/model-migration.md` -> Migrating to Claude Fable 5.1 from Claude Fable 5.
|
||||||
- **Cache-hostile ordering**: timestamps, UUIDs, per-user content interpolated above stable content. Read `shared/prompt-caching.md` -> Silent invalidators, and run its greps during this audit.
|
- **Cache-hostile ordering**: timestamps, UUIDs, per-user content interpolated above stable content. Read `shared/prompt-caching.md` -> Silent invalidators, and run its greps during this audit.
|
||||||
- **Budget countdowns rendered into context**: surfacing remaining-token counts to the model can cause premature wrap-up behavior; avoid showing them where possible.
|
- **Budget countdowns rendered into context**: surfacing remaining-token counts to the model can cause premature wrap-up behavior; avoid showing them where possible.
|
||||||
- **An LLM executor for a deterministic plan**: agent sessions whose transcript is the same loop body N times; calls whose inputs fully determine outputs. **Run this check, don't wait to notice it**: in every pipeline, batch job, or agent loop, *count the model-call sites* and ask of each whether its inputs fully determine its output. Routing, tallying, normalizing, filtering, and formatting steps go back into plain code; keep exactly one model call where the work is genuinely adaptive (classifying the ambiguous remainder, writing the judgment summary). Zero model calls is an over-fix when a judgment step exists - name the one call that stays.
|
- **An LLM executor for a deterministic plan**: agent sessions whose transcript is the same loop body N times; calls whose inputs fully determine outputs. **Run this check, don't wait to notice it**: in every pipeline, batch job, or agent loop, *count the model-call sites* and ask of each whether its inputs fully determine its output. Routing, tallying, normalizing, filtering, and formatting steps go back into plain code; keep exactly one model call where the work is genuinely adaptive (classifying the ambiguous remainder, writing the judgment summary). Zero model calls is an over-fix when a judgment step exists - name the one call that stays.
|
||||||
|
|||||||
@@ -173,7 +173,7 @@ Automatic is the right default for multi-turn conversations - the multi-turn pla
|
|||||||
| A single turn appends more than 20 positions (consecutive tool_use runs, and tool_result runs, each collapse to one position) | The lookback can miss the previous entry - § 20-block lookback window. |
|
| A single turn appends more than 20 positions (consecutive tool_use runs, and tool_result runs, each collapse to one position) | The lookback can miss the previous entry - § 20-block lookback window. |
|
||||||
| A platform or integration without automatic caching (check `shared/platform-availability.md`) | The top-level field is rejected there - use explicit markers only. |
|
| A platform or integration without automatic caching (check `shared/platform-availability.md`) | The top-level field is rejected there - use explicit markers only. |
|
||||||
|
|
||||||
**The robust combination for agent loops:** one explicit breakpoint on the last block of the static system prefix - the expensive shared part gets a guaranteed read point that survives whatever happens later in `messages` - plus top-level automatic caching for the growing conversation tail (where automatic caching is available - `shared/platform-availability.md`).
|
**The robust combination for agent loops:** one explicit breakpoint on the last block of the static system prefix - the expensive shared part gets a guaranteed read point that survives whatever happens later in `messages` - plus top-level automatic caching for the growing conversation tail (where automatic caching is available - `shared/platform-availability.md`). If § Choosing the TTL puts you on the 1-hour TTL, set `ttl: "1h"` on the explicit marker as well as on the top-level field. Both default to 5 minutes, and a 1-hour automatic entry after a 5-minute marker breaks the ordering rule above: longer TTLs must come first. The reverse, a 1-hour marker with a 5-minute tail, is allowed.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -229,15 +229,15 @@ Implication: you can change `tool_choice` per-request without losing the tools+s
|
|||||||
|
|
||||||
| Top-level change that invalidates | Cache-preserving form | Available on |
|
| Top-level change that invalidates | Cache-preserving form | Available on |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| Tool definitions (add/remove) | `tool_addition` / `tool_removal` blocks - see `shared/tool-use-concepts.md` § Mid-conversation tool changes | Claude Opus 5 onward, behind `mid-conversation-tool-changes-2026-07-01` |
|
| Tool definitions (add/remove) | `tool_addition` / `tool_removal` blocks - see `shared/tool-use-concepts.md` § Mid-conversation tool changes | Claude Opus 5, Claude Opus 4.8, Claude Fable 5, Claude Fable 5.1, Claude Mythos 5, Claude Mythos 5.1 (not Claude Sonnet 5), behind `mid-conversation-tool-changes-2026-07-01` |
|
||||||
| System prompt content | A `{"role": "system", "content": "..."}` message - see § Mid-conversation system messages above | Claude Opus 5, Claude Opus 4.8, Claude Fable 5, Claude Fable 5.1, Claude Mythos 5, Claude Mythos 5.1 - **already available today**, no beta header |
|
| System prompt content | A `{"role": "system", "content": "..."}` message - see § Mid-conversation system messages above | Claude Opus 5, Claude Opus 4.8, Claude Fable 5, Claude Fable 5.1, Claude Mythos 5, Claude Mythos 5.1 - **already available today**, no beta header |
|
||||||
| Per-turn reminder (inject, then delete next request) | A turn-scoped `clear_at: "next_user_message"` system message, left in the transcript - see § Mid-conversation system messages above (without the beta: a text block after the `tool_result` blocks, earlier copies kept) | Same models as mid-conversation system messages, behind `mid-conversation-system-clear-at-2026-08-21` |
|
| Per-turn reminder (inject, then delete next request) | A turn-scoped `clear_at: "next_user_message"` system message, left in the transcript - see § Mid-conversation system messages above (without the beta: a text block after the `tool_result` blocks, earlier copies kept) | Same models as mid-conversation system messages, behind `mid-conversation-system-clear-at-2026-08-21` |
|
||||||
| `effort` change | A `{"role": "system", "content": [], "output_config": {"effort": ...}}` message - see `shared/model-migration.md` -> Migrating to Claude Fable 5.1 from Claude Fable 5 | Claude Fable 5.1, Claude Mythos 5.1, Claude Opus 5, behind `mid-conversation-output-config-2026-07-01` |
|
| `effort` change | A `{"role": "system", "content": [], "output_config": {"effort": ...}}` message - see `shared/model-migration.md` -> Migrating to Claude Fable 5.1 from Claude Fable 5 | Claude Fable 5.1, Claude Mythos 5.1, Claude Opus 5, behind `mid-conversation-output-config-2026-07-01` |
|
||||||
| Dropped thinking blocks (a Claude Fable 5.1 / Claude Mythos 5.1 block replayed to a model that can't read it, or a history-editing-check `drop_block`) | None - the API drops the block on that request and the messages cache changes from its position onward; tools and system caches are intact. Blocks the receiving model can read, passed back unchanged, keep the cache intact | - |
|
| Dropped thinking blocks (a Claude Fable 5.1 / Claude Mythos 5.1 / Claude Opus 5.5 block replayed to a model that can't read it - only Claude Fable 5.1 / Claude Mythos 5.1 on the Claude API read Claude Opus 5.5's - or a history-editing-check `drop_block`) | None - the API drops the block on that request and the messages cache changes from its position onward; tools and system caches are intact. Blocks the receiving model can read, passed back unchanged, keep the cache intact | - |
|
||||||
|
|
||||||
Model switch has no escape hatch: caches are model-scoped. Keep the main loop on one model and spawn a subagent for cheaper sub-tasks (see `agent-design.md` § Caching for Agents).
|
Model switch has no escape hatch: caches are model-scoped. Keep the main loop on one model and spawn a subagent for cheaper sub-tasks (see `agent-design.md` § Caching for Agents).
|
||||||
|
|
||||||
**Thinking blocks and the messages cache (model-specific).** On Claude Fable 5, Claude Fable 5.1, Claude Mythos 5, Claude Mythos 5.1, Mythos Preview, Opus 4.5 and later, and Sonnet 4.6 and later, previous-turn thinking blocks are preserved by default, so passing a regular (non-tool-result) user message with thinking enabled leaves the messages cache valid. On earlier Opus and Sonnet models and all Haiku models through Haiku 4.5, that same request strips previously-cached thinking blocks from context, and every message after the first stripped block falls out of cache - in an agent loop this shows up as a `cache_creation_input_tokens` spike on turns where a plain user message follows tool use. (Toggling thinking on/off between requests is a separate, all-models invalidator of the messages cache - see the hierarchy table above. Changing `output_config.effort` behaves the same as changing thinking parameters; setting the model's default effort explicitly is equivalent to omitting it, so pinning the default costs nothing.)
|
**Thinking blocks and the messages cache (model-specific).** On Claude Fable 5, Claude Fable 5.1, Claude Mythos 5, Claude Mythos 5.1, Mythos Preview, Opus 4.5 and later (Claude Opus 5.5 included), and Sonnet 4.6 and later, previous-turn thinking blocks are preserved by default, so passing a regular (non-tool-result) user message with thinking enabled leaves the messages cache valid. On earlier Opus and Sonnet models and all Haiku models through Haiku 4.5, that same request strips previously-cached thinking blocks from context, and every message after the first stripped block falls out of cache - in an agent loop this shows up as a `cache_creation_input_tokens` spike on turns where a plain user message follows tool use. (Toggling thinking on/off between requests is a separate, all-models invalidator of the messages cache - see the hierarchy table above. Changing `output_config.effort` behaves the same as changing thinking parameters; setting the model's default effort explicitly is equivalent to omitting it, so pinning the default costs nothing.)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -276,6 +276,9 @@ To eliminate the cache-miss latency on the *first* real request, send a **`max_t
|
|||||||
client.messages.create(
|
client.messages.create(
|
||||||
model="claude-opus-5",
|
model="claude-opus-5",
|
||||||
max_tokens=0,
|
max_tokens=0,
|
||||||
|
# Example values - send the same thinking and effort settings as your real traffic (see below)
|
||||||
|
thinking={"type": "adaptive"},
|
||||||
|
output_config={"effort": "high"},
|
||||||
system=[{
|
system=[{
|
||||||
"type": "text",
|
"type": "text",
|
||||||
"text": SYSTEM_PROMPT,
|
"text": SYSTEM_PROMPT,
|
||||||
@@ -287,6 +290,8 @@ client.messages.create(
|
|||||||
|
|
||||||
**Breakpoint placement:** put `cache_control` on the **last block shared with the real request** (the system prompt or tool definitions) - **not** on the placeholder user message, and **not** via top-level automatic caching (which would key the cache to the placeholder). The placeholder can be any non-whitespace string; it's read during prefill but never answered.
|
**Breakpoint placement:** put `cache_control` on the **last block shared with the real request** (the system prompt or tool definitions) - **not** on the placeholder user message, and **not** via top-level automatic caching (which would key the cache to the placeholder). The placeholder can be any non-whitespace string; it's read during prefill but never answered.
|
||||||
|
|
||||||
|
**Match the real traffic's thinking and effort settings.** Both are rendered into the prompt (see § Invalidation hierarchy), so a pre-warm with different settings can write a cache entry your real traffic never hits. For adaptive-thinking traffic, send the same `thinking` and `effort` values in the pre-warm. Traffic that uses extended thinking (`thinking.type: "enabled"`, accepted only on Claude 4.6 and earlier models and on Claude Mythos Preview) can't be matched, because `max_tokens: 0` rejects that setting (see Rejected combinations below). Whether a pre-warm still helps that traffic depends on where the model renders the thinking configuration, which the docs don't state per model - check `cache_read_input_tokens` on the first real request.
|
||||||
|
|
||||||
**Rejected combinations:** `max_tokens: 0` is an `invalid_request_error` with `stream: true`, `thinking.type: "enabled"`, `output_config.format`, `tool_choice` of `{"type":"tool"}` or `{"type":"any"}`, or inside a Message Batches request.
|
**Rejected combinations:** `max_tokens: 0` is an `invalid_request_error` with `stream: true`, `thinking.type: "enabled"`, `output_config.format`, `tool_choice` of `{"type":"tool"}` or `{"type":"any"}`, or inside a Message Batches request.
|
||||||
|
|
||||||
**TTL still applies** - re-warm at least every 5 minutes for the default cache, or use the 1-hour TTL. This replaces the older `max_tokens: 1` workaround (no single-token reply to discard, no output tokens billed, intent is unambiguous).
|
**TTL still applies** - re-warm at least every 5 minutes for the default cache, or use the 1-hour TTL. This replaces the older `max_tokens: 1` workaround (no single-token reply to discard, no output tokens billed, intent is unambiguous).
|
||||||
|
|||||||
@@ -42,6 +42,54 @@ Each tool requires a name, description, and JSON Schema for its inputs:
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
### Eager input streaming (default for streaming requests with client tools)
|
||||||
|
|
||||||
|
By default the API **buffers and validates each tool-input parameter** before it emits any `input_json_delta` for it. For a small `{"location": "Paris"}` that is invisible; for a tool that takes a file body, a code block, or a document, nothing arrives until the whole parameter is generated (a 20K-token parameter is a multi-minute silent gap on the stream). Setting `eager_input_streaming: true` on the tool turns off that buffering for that tool: fragments stream as they are generated, the first fragment arrives immediately, and the fragments are longer. The events are the same (`content_block_start` -> `input_json_delta` × N -> `content_block_stop`) - only the timing and the validation guarantee change.
|
||||||
|
|
||||||
|
**Default rule:** when a request is streamed (`client.messages.stream(...)`, `stream=True`, tool runner with streaming on) and defines user-defined tools, set `eager_input_streaming: true` on each of those tools. Do not set it on non-streaming requests (it is ignored), on server tools (`web_search`, `code_execution`, `mcp_toolset`, etc. - it is not a valid field there), or when the client has no way to handle invalid JSON.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"name": "write_file",
|
||||||
|
"description": "Write text to a file",
|
||||||
|
"eager_input_streaming": true,
|
||||||
|
"input_schema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"path": {"type": "string"},
|
||||||
|
"contents": {"type": "string", "description": "Full file contents"}
|
||||||
|
},
|
||||||
|
"required": ["path", "contents"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Tool runner: Python `@beta_tool(eager_input_streaming=True)` passes it through. TypeScript `betaZodTool()` has no option for it - spread the field onto the returned tool: `{ ...betaZodTool({ name, description, inputSchema, run }), eager_input_streaming: true }`. Go/Java/Ruby/C#/PHP: the field is on the tool param type (`EagerInputStreaming`, `.eagerInputStreaming(true)`, `eager_input_streaming:`).
|
||||||
|
|
||||||
|
**What you give up, and how to handle it.** Without buffering the API does not validate or coerce the parameter, so the accumulated `partial_json` can be (a) cut off at `max_tokens` mid-parameter or (b) invalid JSON the model emitted. Both SDKs accumulate it with a *tolerant* partial-JSON parser, so malformed input often comes back as a silently truncated object (an unescaped inner quote ends the string early; trailing garbage is dropped) rather than an exception. Do not rely on an exception. Always:
|
||||||
|
|
||||||
|
1. **Validate the parsed input against the tool's schema before running the tool.** The typed runner helpers do this for you and never call `run` on input that fails: TS `betaZodTool` (Zod), Python `@beta_tool` on a function with typed parameters, Java's annotated classes, Go's struct tags, Ruby's `BaseTool`. The raw JSON-Schema helpers do **not** validate at runtime - TS `betaTool()` and PHP's `BetaRunnableTool` hand `run` whatever was parsed - so with those, validate inside `run` (or leave `eager_input_streaming` off for that tool). In a manual loop, validate yourself (`schema.safeParse(block.input)` in TS, a pydantic model or explicit type checks in Python) and treat a failure exactly like invalid JSON. A raw SSE / cURL client should `JSON.parse` the accumulated fragments strictly and then validate.
|
||||||
|
2. Check `stop_reason == "max_tokens"` when a `tool_use` block is present: a truncated input usually parses as a valid partial object, so this is what catches it; retry with a higher `max_tokens` rather than running the tool. Also stop on `stop_reason == "refusal"` - a refusal can cut a `tool_use` off mid-input, so never execute that turn's tools.
|
||||||
|
3. Still guard the exceptions the SDKs do raise for JSON they cannot parse at all: **Python** raises `ValueError` from the stream iterator (wrap the `with client.messages.stream(...)` block); **TypeScript** materializes the input at `content_block_stop`, so the error rejects whatever you are awaiting at that moment - the `for await (const event of stream)` loop if you iterate events, otherwise `await stream.finalMessage()` - so wrap the whole consumption of the stream (iteration and final read together), as the Python guidance wraps the whole `with` block; the **tool runners** surface the same error from their iteration (wrap the loop). Catch only that error - rethrow the SDK's typed API errors (`RateLimitError`, `AuthenticationError`, ...) so an auth or rate-limit failure is not mistaken for bad JSON - and cap retries.
|
||||||
|
4. When validation fails and you still hold the `tool_use` block (manual loop after `finalMessage()` / `get_final_message()`, raw SSE), do not run the tool; return the raw text to Claude as an error result so it can retry:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "tool_result",
|
||||||
|
"tool_use_id": "toolu_01...",
|
||||||
|
"is_error": true,
|
||||||
|
"content": "{\"INVALID_JSON\": \"<the unparseable input you received>\"}"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
When the SDK raised before the block completed (Python stream, either tool runner), there is no `tool_use_id` to answer, so re-issue the request instead.
|
||||||
|
|
||||||
|
Build that wrapper with the JSON library (not string concatenation) so quotes in the bad input are escaped. With the buffered default the server would have delivered the same broken parameter as a single string value instead; eager mode moves that failure to the client, it does not create it.
|
||||||
|
|
||||||
|
**Availability:** Claude API, Claude Platform on AWS, Vertex AI, and Microsoft Foundry for all current models (`shared/platform-availability.md`). On Amazon Bedrock only the newer serving stack accepts the field (Opus 4.7 / 4.8 / 5, Fable 5, Sonnet 4.6 / 5); older Bedrock deployments (Opus 4.5 / 4.6, Sonnet 4.0 / 4.5, Haiku 4.5) return 400 on the unknown field - drop it there. `shared/platform-availability.md` is the source of truth for this list. Any proxy or gateway in front of the API may likewise reject it; if the user's code points at a custom `base_url`, leave it off unless they confirm the upstream is the real API.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
### Tool Choice Options
|
### Tool Choice Options
|
||||||
|
|
||||||
Control when Claude uses tools:
|
Control when Claude uses tools:
|
||||||
@@ -55,7 +103,7 @@ Control when Claude uses tools:
|
|||||||
|
|
||||||
Any `tool_choice` value can also include `"disable_parallel_tool_use": true` to force Claude to use at most one tool per response. By default, Claude may request multiple tool calls in a single response.
|
Any `tool_choice` value can also include `"disable_parallel_tool_use": true` to force Claude to use at most one tool per response. By default, Claude may request multiple tool calls in a single response.
|
||||||
|
|
||||||
**Claude Fable 5.1, Claude Mythos 5.1, and Mythos Preview reject forced tool use:** `{"type": "any"}` and `{"type": "tool", "name": ...}` return a 400 there (`tool_choice: type "tool" and "any" are not supported for this model.` - on `count_tokens` and Batches too). It is a model-specific restriction (Claude Fable 5 and Claude Opus 5 accept them). Use `{"type": "auto"}` and state the expectation in the prompt ("Use the get_weather tool to answer") - `strict: true` on the tool keeps the schema-valid-arguments guarantee `any` gave you - or structured outputs (`output_config.format`) when the forced call only existed to extract JSON. `auto` and `none` are unaffected; `disable_parallel_tool_use` with `auto` still means at most one call (the "exactly one" combination with `any`/`tool` is gone). Combining `tool_choice` `any` with `strict: true` applies only on models that support forced tool use. See `shared/model-migration.md` -> Migrating to Claude Fable 5.1 from Claude Fable 5.
|
**Claude Fable 5.1, Claude Mythos 5.1, Claude Opus 5.5, and Mythos Preview reject forced tool use:** `{"type": "any"}` and `{"type": "tool", "name": ...}` return a 400 there (`tool_choice: type "tool" and "any" are not supported for this model.` - on `count_tokens` and Batches too). It is a model-specific restriction (Claude Fable 5 and Claude Opus 5 accept them). Because `auto` does not guarantee a call, check that one was made and retry if it wasn't. Use `{"type": "auto"}` and state the expectation in the prompt ("Use the get_weather tool to answer") - `strict: true` on the tool keeps the schema-valid-arguments guarantee `any` gave you - or structured outputs (`output_config.format`) when the forced call only existed to extract JSON. `auto` and `none` are unaffected; `disable_parallel_tool_use` with `auto` still means at most one call (the "exactly one" combination with `any`/`tool` is gone). Combining `tool_choice` `any` with `strict: true` applies only on models that support forced tool use. See `shared/model-migration.md` -> Migrating to Claude Fable 5.1 from Claude Fable 5.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -234,7 +282,7 @@ For full documentation, use WebFetch:
|
|||||||
|
|
||||||
## Mid-conversation tool changes (Beta)
|
## Mid-conversation tool changes (Beta)
|
||||||
|
|
||||||
**Beta header `mid-conversation-tool-changes-2026-07-01`; Claude Opus 5 onward.** Normally `tools` is fixed for a conversation's lifetime - editing it changes the very front of the prompt prefix and invalidates the entire cache (see `prompt-caching.md` § Invalidation hierarchy). This feature lets you add and remove tools between turns while the cached prefix survives.
|
**Beta header `mid-conversation-tool-changes-2026-07-01`; Claude Opus 5, Claude Opus 4.8, Claude Fable 5, Claude Fable 5.1, Claude Mythos 5, and Claude Mythos 5.1 - not Claude Sonnet 5; not available on Microsoft Foundry (availability: `shared/platform-availability.md`).** Normally `tools` is fixed for a conversation's lifetime - editing it changes the very front of the prompt prefix and invalidates the entire cache (see `prompt-caching.md` § Invalidation hierarchy). This feature lets you add and remove tools between turns while the cached prefix survives.
|
||||||
|
|
||||||
Both operations are content blocks on a `{"role": "system", ...}` message appended to `messages[]`, and both reference a tool by name via a `tool_reference`:
|
Both operations are content blocks on a `{"role": "system", ...}` message appended to `messages[]`, and both reference a tool by name via a `tool_reference`:
|
||||||
|
|
||||||
@@ -339,7 +387,9 @@ For full documentation, use WebFetch:
|
|||||||
|
|
||||||
Computer use lets Claude interact with a desktop environment (screenshots, mouse, keyboard). It is a client-side tool - your application provides the environment and executes the actions Claude requests; Anthropic processes the screenshots and action requests in real time but does not host the environment or retain the data.
|
Computer use lets Claude interact with a desktop environment (screenshots, mouse, keyboard). It is a client-side tool - your application provides the environment and executes the actions Claude requests; Anthropic processes the screenshots and action requests in real time but does not host the environment or retain the data.
|
||||||
|
|
||||||
For full documentation, use WebFetch:
|
**Two request shapes.** The current one is the **computer toolset** - GA on the Claude API and Google Cloud, no beta header: one `tools` entry `{"type": "computer_toolset_20260801"}` with **no `name`** and no display dimensions, plus an optional `configs` map to turn member tools off (`{"zoom": {"enabled": false}}`; all 17 members, `zoom` included, are on by default). Claude's calls are `tool_use` blocks whose `name` is the member (`screenshot`, `left_click`, `type`, `zoom`, ...) carrying `"toolset_name": "computer"`, often several per turn; return one `tool_result` per call in the next `user` message, **each echoing `"toolset_name": "computer"`** (only `screenshot` / `zoom` need an image; `OK` suffices for the rest). Coordinates are in the pixel space of the full screenshots you return, also after a `zoom`, and screenshots must already fit the model's image limits. The earlier `computer_20251124` tool (beta `computer-use-2025-11-24`, a `name: "computer"` entry with `display_width_px` / `display_height_px`, actions in `input.action`) keeps working on the models and platforms that offer it - Bedrock, Claude Platform on AWS, and Foundry offer only the earlier beta versions today - and the two forms can't share a request. **Claude Opus 5.5 accepts only the toolset**: `computer_20251124` returns a 400 there (`shared/model-migration.md` -> Migrating to Claude Opus 5.5 -> Breaking change 4 has the request and agent-loop changes; test them on Claude Opus 5, which accepts both).
|
||||||
|
|
||||||
|
For full documentation (member reference, batch actions, scaling, the `computer_20251124` migration steps), use WebFetch:
|
||||||
|
|
||||||
- URL: `https://platform.claude.com/docs/en/agents-and-tools/computer-use/overview`
|
- URL: `https://platform.claude.com/docs/en/agents-and-tools/computer-use/overview`
|
||||||
|
|
||||||
|
|||||||
@@ -205,7 +205,7 @@ If `cache_read_input_tokens` is zero across repeated identical-prefix requests,
|
|||||||
const response = await client.messages.create({
|
const response = await client.messages.create({
|
||||||
model: "claude-opus-5",
|
model: "claude-opus-5",
|
||||||
max_tokens: 16000,
|
max_tokens: 16000,
|
||||||
thinking: { type: "adaptive", display: "summarized" }, // display opt-in: default is omitted (empty thinking text) on Fable 5 / Mythos 5 / Claude Opus 5 / Opus 4.8 / 4.7
|
thinking: { type: "adaptive", display: "summarized" }, // display opt-in: default is omitted (empty thinking text) on Fable 5/5.1, Mythos 5/5.1, Claude Opus 5, Opus 4.8/4.7, and Claude Sonnet 5
|
||||||
output_config: { effort: "high" }, // low | medium | high | xhigh | max
|
output_config: { effort: "high" }, // low | medium | high | xhigh | max
|
||||||
messages: [
|
messages: [
|
||||||
{ role: "user", content: "Solve this math problem step by step..." },
|
{ role: "user", content: "Solve this math problem step by step..." },
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ for await (const event of stream) {
|
|||||||
const stream = client.messages.stream({
|
const stream = client.messages.stream({
|
||||||
model: "claude-opus-5",
|
model: "claude-opus-5",
|
||||||
max_tokens: 64000,
|
max_tokens: 64000,
|
||||||
thinking: { type: "adaptive", display: "summarized" }, // display opt-in: default is omitted (empty thinking text) on Fable 5 / Mythos 5 / Claude Opus 5 / Opus 4.8 / 4.7
|
thinking: { type: "adaptive", display: "summarized" }, // display opt-in: default is omitted (empty thinking text) on Fable 5/5.1, Mythos 5/5.1, Claude Opus 5, Opus 4.8/4.7, and Claude Sonnet 5
|
||||||
messages: [{ role: "user", content: "Analyze this problem" }],
|
messages: [{ role: "user", content: "Analyze this problem" }],
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -63,7 +63,7 @@ for await (const event of stream) {
|
|||||||
|
|
||||||
## Streaming with Tool Use (Tool Runner)
|
## Streaming with Tool Use (Tool Runner)
|
||||||
|
|
||||||
Use the tool runner with `stream: true`. The outer loop iterates over tool runner iterations (messages), the inner loop processes stream events:
|
Use the tool runner with `stream: true`. The outer loop iterates over tool runner iterations (messages), the inner loop processes stream events. `betaZodTool()` has no option for `eager_input_streaming`, so spread it onto the returned tool - without it the API buffers each tool-input parameter and `input_json_delta` arrives in one burst at the end (default rule: `shared/tool-use-concepts.md` -> Eager input streaming):
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import Anthropic from "@anthropic-ai/sdk";
|
import Anthropic from "@anthropic-ai/sdk";
|
||||||
@@ -72,16 +72,19 @@ import { z } from "zod";
|
|||||||
|
|
||||||
const client = new Anthropic();
|
const client = new Anthropic();
|
||||||
|
|
||||||
const getWeather = betaZodTool({
|
const getWeather = {
|
||||||
name: "get_weather",
|
...betaZodTool({
|
||||||
description: "Get current weather for a location",
|
name: "get_weather",
|
||||||
inputSchema: z.object({
|
description: "Get current weather for a location",
|
||||||
location: z.string().describe("City and state, e.g., San Francisco, CA"),
|
inputSchema: z.object({
|
||||||
|
location: z.string().describe("City and state, e.g., San Francisco, CA"),
|
||||||
|
}),
|
||||||
|
run: async ({ location }) => `72°F and sunny in ${location}`,
|
||||||
}),
|
}),
|
||||||
run: async ({ location }) => `72°F and sunny in ${location}`,
|
eager_input_streaming: true, // stream tool input as it is generated
|
||||||
});
|
};
|
||||||
|
|
||||||
const runner = client.beta.messages.toolRunner({
|
let runner = client.beta.messages.toolRunner({
|
||||||
model: "claude-opus-5",
|
model: "claude-opus-5",
|
||||||
max_tokens: 64000,
|
max_tokens: 64000,
|
||||||
tools: [getWeather],
|
tools: [getWeather],
|
||||||
@@ -91,26 +94,66 @@ const runner = client.beta.messages.toolRunner({
|
|||||||
stream: true,
|
stream: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Outer loop: each tool runner iteration
|
// With eager input streaming the SDK parses each tool input when its block
|
||||||
for await (const messageStream of runner) {
|
// closes. The runner validates it against the Zod schema and never calls
|
||||||
// Inner loop: stream events for this iteration
|
// run() on input that fails; JSON it cannot parse at all rejects the
|
||||||
for await (const event of messageStream) {
|
// iteration. Re-issue only for that case - API errors are rethrown - with a
|
||||||
switch (event.type) {
|
// cap on consecutive failures. A consumed runner cannot be iterated again,
|
||||||
case "content_block_delta":
|
// so the retry builds a new one from runner.params, which holds the
|
||||||
switch (event.delta.type) {
|
// conversation so far (the failed turn was never appended), so completed
|
||||||
case "text_delta":
|
// tool calls are not re-run.
|
||||||
process.stdout.write(event.delta.text);
|
//
|
||||||
break;
|
// The runner does not apply the stop-reason rules for you: check
|
||||||
case "input_json_delta":
|
// stop_reason after each turn before the runner runs that turn's tools.
|
||||||
// Tool input being streamed
|
class TruncatedToolInput extends Error {}
|
||||||
|
|
||||||
|
for (let attempt = 0; ; attempt++) {
|
||||||
|
try {
|
||||||
|
// Outer loop: each tool runner iteration
|
||||||
|
for await (const messageStream of runner) {
|
||||||
|
// Inner loop: stream events for this iteration
|
||||||
|
for await (const event of messageStream) {
|
||||||
|
switch (event.type) {
|
||||||
|
case "content_block_delta":
|
||||||
|
switch (event.delta.type) {
|
||||||
|
case "text_delta":
|
||||||
|
process.stdout.write(event.delta.text);
|
||||||
|
break;
|
||||||
|
case "input_json_delta":
|
||||||
|
// Tool input fragment - arrives immediately with eager streaming
|
||||||
|
process.stdout.write(event.delta.partial_json);
|
||||||
|
break;
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
break;
|
}
|
||||||
|
const message = await messageStream.finalMessage();
|
||||||
|
attempt = 0; // the turn completed; the cap is on consecutive failures
|
||||||
|
// A truncated tool input can still pass schema validation, so stop
|
||||||
|
// before the runner executes it; a refusal can cut a tool_use off
|
||||||
|
// mid-input, so never run that turn's tools. pause_turn is not
|
||||||
|
// auto-resumed by the runner: see tool-use.md -> Server tools.
|
||||||
|
const hasToolUse = message.content.some((b) => b.type === "tool_use");
|
||||||
|
if (message.stop_reason === "max_tokens" && hasToolUse) {
|
||||||
|
throw new TruncatedToolInput("tool input truncated; retry with a higher max_tokens");
|
||||||
|
}
|
||||||
|
if (message.stop_reason === "refusal") break;
|
||||||
|
// max_tokens on a plain text answer just ends the loop with the
|
||||||
|
// truncated text; the runner returns it as the final message.
|
||||||
}
|
}
|
||||||
|
break;
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof Anthropic.APIError || err instanceof TruncatedToolInput || attempt >= 2) {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
console.error("tool input was not parseable JSON, re-issuing the turn");
|
||||||
|
runner = client.beta.messages.toolRunner({ ...runner.params });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
With `betaZodTool` the runner validates each tool input against the Zod schema before calling `run` (a `betaTool()` JSON-Schema tool is not validated at runtime - validate inside `run`), which catches malformed input (missing or mistyped fields) the tolerant parser let through; JSON it cannot parse at all rejects the `for await` loop, so wrap it, rethrow API errors, and re-issue with a new runner built from `runner.params` and a cap on consecutive failures - the `tool_use` block never completed, so there is no `tool_use_id` to answer with an `is_error` result. The stop-reason rules are yours to apply, not the runner's: check each turn's `stop_reason` after `finalMessage()` - stop on `max_tokens` when the turn carries a `tool_use` (a truncated input can pass schema validation; a truncated text answer is just returned), stop on `refusal`, and resume `pause_turn` yourself (the runner does not; see `tool-use.md` -> Server tools with the tool runner and `shared/tool-use-concepts.md` -> Eager input streaming).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Getting the Final Message
|
## Getting the Final Message
|
||||||
|
|||||||
@@ -138,14 +138,30 @@ while (true) {
|
|||||||
|
|
||||||
### Streaming Manual Loop
|
### Streaming Manual Loop
|
||||||
|
|
||||||
Use `client.messages.stream()` + `finalMessage()` instead of `.create()` when you need streaming within a manual loop. Text deltas are streamed on each iteration; `finalMessage()` collects the complete `Message` so you can inspect `stop_reason` and extract tool-use blocks:
|
Use `client.messages.stream()` + `finalMessage()` instead of `.create()` when you need streaming within a manual loop. Text deltas are streamed on each iteration; `finalMessage()` collects the complete `Message` so you can inspect `stop_reason` and extract tool-use blocks. Set `eager_input_streaming: true` on each tool so large inputs stream as generated; the server then no longer validates them, so validate each parsed input against the tool's schema before running it, stop on `max_tokens` / `refusal`, and catch only the SDK's JSON error (`shared/tool-use-concepts.md` -> Eager input streaming). Schema validation is not path validation: the model-supplied `path` is untrusted output, so confine it to a project root before writing (the text-editor security note in the same file):
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import Anthropic from "@anthropic-ai/sdk";
|
import Anthropic from "@anthropic-ai/sdk";
|
||||||
|
import nodePath from "path";
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
const client = new Anthropic();
|
const client = new Anthropic();
|
||||||
const tools: Anthropic.Tool[] = [...];
|
const ROOT = nodePath.resolve(process.cwd());
|
||||||
|
const WriteFileInput = z.object({ path: z.string(), contents: z.string() });
|
||||||
|
const tools: Anthropic.Tool[] = [
|
||||||
|
{
|
||||||
|
name: "write_file",
|
||||||
|
description: "Write text to a file at the given path",
|
||||||
|
eager_input_streaming: true, // stream large inputs as generated
|
||||||
|
input_schema: {
|
||||||
|
type: "object",
|
||||||
|
properties: { path: { type: "string" }, contents: { type: "string" } },
|
||||||
|
required: ["path", "contents"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
let messages: Anthropic.MessageParam[] = [{ role: "user", content: userInput }];
|
let messages: Anthropic.MessageParam[] = [{ role: "user", content: userInput }];
|
||||||
|
let jsonRetries = 0;
|
||||||
|
|
||||||
while (true) {
|
while (true) {
|
||||||
const stream = client.messages.stream({
|
const stream = client.messages.stream({
|
||||||
@@ -161,10 +177,22 @@ while (true) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// finalMessage() resolves with the complete Message - no need to
|
// finalMessage() resolves with the complete Message - no need to
|
||||||
// manually wire up .on("message") / .on("error") / .on("abort")
|
// manually wire up .on("message") / .on("error") / .on("abort").
|
||||||
const message = await stream.finalMessage();
|
// With eager input streaming it rejects if a tool input could not be
|
||||||
|
// parsed at all. Only that case is retried; API errors are rethrown.
|
||||||
|
let message: Anthropic.Message;
|
||||||
|
try {
|
||||||
|
message = await stream.finalMessage();
|
||||||
|
jsonRetries = 0; // the cap is on consecutive failures of one turn
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof Anthropic.APIError || jsonRetries++ >= 2) throw err;
|
||||||
|
console.error("tool input was not parseable JSON, re-issuing the turn");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
if (message.stop_reason === "end_turn") break;
|
if (message.stop_reason === "end_turn") break;
|
||||||
|
// A refusal can cut a tool_use off mid-input; never run that turn's tools.
|
||||||
|
if (message.stop_reason === "refusal") break;
|
||||||
|
|
||||||
// Server-side tool hit iteration limit; append assistant turn and re-send to continue
|
// Server-side tool hit iteration limit; append assistant turn and re-send to continue
|
||||||
if (message.stop_reason === "pause_turn") {
|
if (message.stop_reason === "pause_turn") {
|
||||||
@@ -175,16 +203,51 @@ while (true) {
|
|||||||
const toolUseBlocks = message.content.filter(
|
const toolUseBlocks = message.content.filter(
|
||||||
(b): b is Anthropic.ToolUseBlock => b.type === "tool_use",
|
(b): b is Anthropic.ToolUseBlock => b.type === "tool_use",
|
||||||
);
|
);
|
||||||
|
if (toolUseBlocks.length === 0) break; // other terminal stop
|
||||||
|
|
||||||
|
// A tool input cut off at max_tokens usually parses as a valid partial
|
||||||
|
// object; check the stop reason and retry with a higher max_tokens
|
||||||
|
// instead of running the tool on truncated input.
|
||||||
|
if (message.stop_reason === "max_tokens") {
|
||||||
|
throw new Error("tool input truncated (max_tokens); retry with a higher max_tokens");
|
||||||
|
}
|
||||||
|
|
||||||
messages.push({ role: "assistant", content: message.content });
|
messages.push({ role: "assistant", content: message.content });
|
||||||
|
|
||||||
const toolResults: Anthropic.ToolResultBlockParam[] = [];
|
const toolResults: Anthropic.ToolResultBlockParam[] = [];
|
||||||
for (const tool of toolUseBlocks) {
|
for (const tool of toolUseBlocks) {
|
||||||
const result = await executeTool(tool.name, tool.input);
|
// The SDK's tolerant parser can return a silently truncated input (for
|
||||||
|
// example at an unescaped inner quote), so validate before running.
|
||||||
|
const parsed = WriteFileInput.safeParse(tool.input);
|
||||||
|
if (!parsed.success) {
|
||||||
|
toolResults.push({
|
||||||
|
type: "tool_result",
|
||||||
|
tool_use_id: tool.id,
|
||||||
|
is_error: true,
|
||||||
|
content: JSON.stringify({ INVALID_JSON: JSON.stringify(tool.input) }),
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// `path` is untrusted model output: resolve it and reject anything that
|
||||||
|
// escapes the project root (`..`, absolute paths) before the write -
|
||||||
|
// schema validation alone does not check this. This check is lexical; if
|
||||||
|
// the root contains symlinked directories, canonicalize with fs.realpath
|
||||||
|
// too (shared/tool-use-concepts.md -> the text-editor security note).
|
||||||
|
const target = nodePath.resolve(ROOT, parsed.data.path);
|
||||||
|
const relative = nodePath.relative(ROOT, target);
|
||||||
|
if (relative === ".." || relative.startsWith(".." + nodePath.sep) || nodePath.isAbsolute(relative)) {
|
||||||
|
toolResults.push({
|
||||||
|
type: "tool_result",
|
||||||
|
tool_use_id: tool.id,
|
||||||
|
is_error: true,
|
||||||
|
content: "path escapes the project root",
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
toolResults.push({
|
toolResults.push({
|
||||||
type: "tool_result",
|
type: "tool_result",
|
||||||
tool_use_id: tool.id,
|
tool_use_id: tool.id,
|
||||||
content: result,
|
content: await executeTool(tool.name, { ...parsed.data, path: target }),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -136,6 +136,36 @@ await client.beta.sessions.events.send(
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Define an Outcome (default kickoff for deliverables)
|
||||||
|
|
||||||
|
When the session's job is to produce something checkable - an artifact, a report, a PR - kick off with `user.define_outcome` instead of `user.message`: the harness grades each iteration against your rubric and the agent revises until it passes. Send one or the other, never both. See [Outcomes](../../shared/managed-agents-outcomes.md) for the event reference and rubric-writing guidance.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const STARTER_RUBRIC = `# Report rubric - starter, tune the criteria
|
||||||
|
- Output is a single \`report.md\` in /mnt/session/outputs/
|
||||||
|
- Every claim cites a source URL
|
||||||
|
- Includes a summary table with one row per competitor
|
||||||
|
- Prices are current as of the run date and each row says where it was read from
|
||||||
|
- No placeholder text, TODOs, or empty sections remain
|
||||||
|
`;
|
||||||
|
|
||||||
|
await client.beta.sessions.events.send(
|
||||||
|
session.id,
|
||||||
|
{
|
||||||
|
events: [
|
||||||
|
{
|
||||||
|
type: "user.define_outcome",
|
||||||
|
description: "Write a competitor-pricing report as report.md",
|
||||||
|
rubric: { type: "text", content: STARTER_RUBRIC },
|
||||||
|
max_iterations: 5, // optional; default 3, max 20
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Stream Events (SSE)
|
## Stream Events (SSE)
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
|
|||||||
Reference in New Issue
Block a user