mirror of
https://github.com/anthropics/skills
synced 2026-12-03 12:40:47 +00:00
Update claude-api skill: harness audit, image coordinates, and SDK examples
Add guides for auditing agent harnesses and working with image coordinates, and expand the SDK examples. Update API guidance to match current behavior, including tool approvals, thinking-block checks, and platform support. Co-authored-by: lance <lance@anthropic.com>
This commit is contained in:
@@ -13,7 +13,7 @@ This skill helps you build LLM-powered applications with Claude. Choose the righ
|
||||
|
||||
## Before You Start
|
||||
|
||||
Scan the target file (or, if no target file, the prompt and project) for non-Anthropic provider markers - `import openai`, `from openai`, `langchain_openai`, `OpenAI(`, `gpt-4`, `gpt-5`, file names like `agent-openai.py` or `*-generic.py`, or any explicit instruction to keep the code provider-neutral. If you find any, stop and tell the user that this skill produces Claude/Anthropic SDK code; ask whether they want to switch the file to Claude or want a non-Claude implementation. Do not edit a non-Anthropic file with Anthropic SDK calls. (Exception: the `prompt-audit` subcommand is non-interactive and does not stop here - it records non-Anthropic provider markers in its report's stated assumptions and never proposes switching a non-Anthropic file to the Anthropic SDK.)
|
||||
Scan the target file (or, if no target file, the prompt and project) for non-Anthropic provider markers - `import openai`, `from openai`, `langchain_openai`, `OpenAI(`, `gpt-4`, `gpt-5`, file names like `agent-openai.py` or `*-generic.py`, or any explicit instruction to keep the code provider-neutral. If you find any, stop and tell the user that this skill produces Claude/Anthropic SDK code; ask whether they want to switch the file to Claude or want a non-Claude implementation. Do not edit a non-Anthropic file with Anthropic SDK calls. (Exception: the `prompt-audit` and `harness-audit` subcommands are non-interactive and do not stop here - they record non-Anthropic provider markers in the report's stated assumptions and never propose switching a non-Anthropic file to the Anthropic SDK. `harness-audit` leaves this scan to Step 0 of its guide, whose rules decide what it may read.)
|
||||
|
||||
## Output Requirement
|
||||
|
||||
@@ -43,7 +43,7 @@ Several common Claude API shapes changed in 2025-2026. If you recall a pattern f
|
||||
| Area | Stale prior | Current API |
|
||||
|---|---|---|
|
||||
| Extended thinking | `thinking: {type: "enabled", budget_tokens: N}` | On Claude 4.6+ models: `thinking: {type: "adaptive"}`. `budget_tokens` is deprecated on Opus 4.6 / Sonnet 4.6 and **rejected with a 400** on Fable 5/5.1/5.2 / Sonnet 5.5 / Sonnet 5 / Opus 5.5 / 5 / 4.8 / 4.7. Pre-4.6 models still use `budget_tokens`. |
|
||||
| Web search / web fetch tool type | `web_search_20250305`, `web_fetch_20250910` | `web_search_20260209`, `web_fetch_20260209` (dynamic filtering) on Fable and Mythos models, Opus 5.5/5/4.8/4.7/4.6, Sonnet 5.5, Sonnet 5, and Sonnet 4.6. Older models keep the basic variants; on Vertex AI only basic `web_search_20250305` is available (web fetch is not on Vertex) - see the Server Tools QR below. |
|
||||
| Web search / web fetch tool type | `web_search_20250305`, `web_fetch_20250910` | `web_search_20260318`, `web_fetch_20260318` (dynamic filtering) on Claude 4.6 and later. Older models keep the basic variants; on Vertex AI only basic `web_search_20250305` is available (web fetch is not on Vertex), and Foundry deployments hosted on Azure have only `web_search_20250305` and `web_fetch_20250910` - see the Server Tools QR below. |
|
||||
| PHP parameter names | snake_case wire names as named args (`max_tokens`) | Top-level named args are camelCase (`maxTokens`). Nested array keys vary by feature (e.g. `'taskBudget'`, `'skillID'`, `'mcp_server_name'`) - copy the exact key from the documented example; do not bulk-convert. |
|
||||
| Managed Agents credentials | Keep secrets host-side via custom tools (the only option before vaults shipped) | Vault `environment_variable` credentials - stored by Anthropic, substituted at egress, so the sandbox holds only a placeholder unless a service sends the secret back (`shared/managed-agents-tools.md` -> Vaults). Host-side custom tools remain the fallback for self-hosted sandboxes. |
|
||||
| Files API / Skills | `client.beta.files.*` / `client.beta.skills.*` with beta `files-api-2025-04-14` / `skills-2025-10-02` | Out of beta: `client.files.*` / `client.skills.*`, no beta header. In current SDKs `client.beta.files` / `client.beta.skills` have breaking shape changes from previous versions, matching the stable namespaces - migrate per `shared/live-sources.md` -> Files API / Skills Guide. |
|
||||
@@ -58,6 +58,7 @@ If the User Request at the bottom of this prompt is a bare subcommand string (no
|
||||
|---|---|
|
||||
| `migrate` | Migrate existing Claude API code to a newer model. **Read `shared/model-migration.md` immediately** and follow it in order: Step 0 (confirm scope - ask which files/directories before any edit), Step 1 (classify each file), then the per-target breaking-changes section. Do not summarize the guide - execute it. If the user did not name a target model, ask which model to migrate to in the same turn as the scope question. After the per-target changes are applied, audit the in-scope prompt text, tool descriptions, and request code against `shared/prompt-audit.md` - prompting written for the source model is part of every migration, and it does not announce itself. |
|
||||
| `prompt-audit` | Audit existing prompts, tool descriptions, skills, and agent configuration files (`CLAUDE.md`, rule files, commands, subagents) for dated patterns ("cruft"): text written for older models, and instructions the repository has outgrown or that contradict each other. **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, 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. |
|
||||
| `harness-audit` | Audit an agent harness (loop limits, tools and their results, context management, sub-agents, injected reminders, request settings) for code written for older models. **Read `shared/harness-audit.md` immediately** and follow it in order. Like `prompt-audit`, it states its assumptions instead of asking and produces the report and the proposed diff without pausing; it gives `effort`, `max_tokens` or a cap a new value only where the target rejects the old one, and applies 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. Trailing words may name the language and/or a scope (`upgrade python`, `upgrade python sdk src/`). Read the declared version first. Every SDK, Python 0.x included, and the `ant` CLI: follow the `api-version` row if the upgrade reaches or passes the release in its guide's "Set the version" table (an upgrade to the newest release does); if not, point the user at that SDK's CHANGELOG (repositories in `shared/live-sources.md`), except Python 0.x to 1.x, below. Don't improvise from the Python guide. Python 0.x to 1.x (the user's choice, or where `shared/api-version-migration.md` sends you): **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. This is not model migration - to move code to a newer Claude model, use `migrate`. |
|
||||
| `api-version` | Move code to a newer API version (`anthropic-version` header). **Read `shared/api-version-migration.md` immediately** and follow it in order. |
|
||||
| `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 Analytics API when the user has access, 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. |
|
||||
@@ -70,7 +71,7 @@ If the User Request at the bottom of this prompt is a bare subcommand string (no
|
||||
|
||||
## Language Detection
|
||||
|
||||
Before reading code examples, determine which language the user is working in (exception: for the `prompt-audit` subcommand, skip this section's ask steps - the audit is non-interactive and its inventory is language-agnostic; when no language is inferable, proceed without asking and state the assumption in the report):
|
||||
Before reading code examples, determine which language the user is working in (exception: for the `prompt-audit` and `harness-audit` subcommands, skip this section's ask steps - the audits are non-interactive and their inventories are language-agnostic; when no language is inferable, proceed without asking and state the assumption in the report):
|
||||
|
||||
1. **Look at project files** to infer the language:
|
||||
|
||||
@@ -135,8 +136,8 @@ There are four ways to build an agent. Two independent questions separate them:
|
||||
|
||||
| # | Approach | You write | Harness & deployment | Tools available | Use when |
|
||||
|---|---|---|---|---|---|
|
||||
| 1 | **Claude API - manual loop** | The `while stop_reason == "tool_use"` loop yourself | You build the harness; you host | Only tools you define | You want to own the *entire* loop - no beta dependency, or a control flow the Tool Runner's per-turn hooks don't fit |
|
||||
| 2 | **Claude API - Tool Runner** (`client.beta.messages.tool_runner` + `@beta_tool` / `betaZodTool`) | Just the tool functions | SDK supplies the loop (**harness only**); you host | Only tools you define | You host the agent and don't want to write the loop. Per-turn hooks still give you approval gates, error interception, result modification (e.g. `cache_control`), retries, streaming, and compaction |
|
||||
| 1 | **Claude API - manual loop** | The `while stop_reason == "tool_use"` loop yourself | You build the harness; you host | Only tools you define | You need human-in-the-loop approval, custom logging or conditional execution (the tool runner docs recommend the manual loop for these), or want to own the *entire* loop - no beta dependency, or a control flow the Tool Runner's per-turn hooks don't fit |
|
||||
| 2 | **Claude API - Tool Runner** (`client.beta.messages.tool_runner` + `@beta_tool` / `betaZodTool`) | Just the tool functions | SDK supplies the loop (**harness only**); you host | Only tools you define | You host the agent and don't want to write the loop. Per-turn hooks still give you error interception, result modification (e.g. `cache_control`), retries, streaming, and compaction |
|
||||
| 3 | **Managed Agents** (REST, beta) | Agent config + your tool results | Anthropic supplies the harness **and** hosts a per-session sandbox (**harness + deployment**) | Anthropic-hosted sandbox (bash, files, code exec) + Skills/MCP + your tools | Default: Anthropic runs the loop *and* hosts the per-session workspace; persisted/versioned configs; long-running sessions |
|
||||
| 4 | **Claude Agent SDK** - *separate product* (`claude-agent-sdk` / `@anthropic-ai/claude-agent-sdk`) | A prompt + options | SDK supplies the Claude Code harness + built-in tools (**harness only**); you host | Built-in Read/Write/Edit/Bash/Glob/Grep/WebSearch/WebFetch + MCP + subagents | You want a batteries-included coding/filesystem agent running on your own infra |
|
||||
|
||||
@@ -144,7 +145,7 @@ There are four ways to build an agent. Two independent questions separate them:
|
||||
> - **Tool Runner** is part of the regular Anthropic API SDK (`anthropic` / `@anthropic-ai/sdk`), reached via `client.beta.messages.tool_runner`. It automates the request -> execute -> loop cycle *for tools you define*. No built-in tools, no filesystem access, no sandbox - you supply every tool and host the compute. It is option 2 above, a thin helper over `POST /v1/messages`.
|
||||
> - **Claude Agent SDK** (`claude-agent-sdk` / `@anthropic-ai/claude-agent-sdk`) is Claude Code packaged as a library. It ships built-in tools (file read/write/edit, bash, grep, web search), the full agent loop, context management, hooks, subagents, permissions, and sessions. You call `query(prompt, options)` and it drives everything.
|
||||
>
|
||||
> Both are **harness-only - you host and deploy them.** The difference is scope of harness: the Tool Runner loops over tools *you* define (with per-turn hooks for approval, interception, result modification, and retries - but no built-in tools); the Agent SDK is the full Claude Code harness with built-in tools. Neither provides managed deployment - that's what **Managed Agents (CMA)** adds (Anthropic hosts the loop and a per-session sandbox).
|
||||
> Both are **harness-only - you host and deploy them.** The difference is scope of harness: the Tool Runner loops over tools *you* define (with per-turn hooks for interception, result modification, and retries - but no built-in tools); the Agent SDK is the full Claude Code harness with built-in tools. Neither provides managed deployment - that's what **Managed Agents (CMA)** adds (Anthropic hosts the loop and a per-session sandbox).
|
||||
>
|
||||
> **This skill covers the Claude API and Managed Agents (options 1-3); it does not generate Claude Agent SDK code.** If the user actually wants the Claude Agent SDK, point them to its docs (`code.claude.com/docs/en/agent-sdk`) - don't substitute the API Tool Runner for it, or vice-versa.
|
||||
|
||||
@@ -179,21 +180,21 @@ Everything goes through `POST /v1/messages`. Tools and output constraints are fe
|
||||
|
||||
| Model | Model ID | Context | Input $/1M | Output $/1M |
|
||||
|---|---|---|---|---|
|
||||
| Claude Fable 5.2 | `claude-fable-5-2` | 1M | $8.00 | $40.00 |
|
||||
| Claude Mythos 5.2 (verified organizations only) | `claude-mythos-5-2` | 1M | $8.00 | $40.00 |
|
||||
| Claude Fable 5.1 | `claude-fable-5-1` | 1M | $10.00 | $50.00 |
|
||||
| Claude Mythos 5.1 (verified organizations only) | `claude-mythos-5-1` | 1M | $10.00 | $50.00 |
|
||||
| Claude Fable 5 | `claude-fable-5` | 1M | $10.00 | $50.00 |
|
||||
| Claude Opus 5.5 | `claude-opus-5-5` | 1M | $4.00 | $20.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.7 | `claude-opus-4-7` | 1M | $5.00 | $25.00 |
|
||||
| Claude Opus 4.6 | `claude-opus-4-6` | 1M | $5.00 | $25.00 |
|
||||
| Claude Sonnet 5.5 | `claude-sonnet-5-5` | 1M | $2.00 | $10.00 |
|
||||
| Claude Sonnet 5 | `claude-sonnet-5` | 1M | $2.00 | $10.00 |
|
||||
| Claude Sonnet 4.6 | `claude-sonnet-4-6` | 1M | $3.00 | $15.00 |
|
||||
| Claude Haiku 5.5 | `claude-haiku-5-5` | 1M | $0.10 | $0.50 |
|
||||
| Claude Haiku 4.5 | `claude-haiku-4-5` | 200K | $1.00 | $5.00 |
|
||||
| Claude Fable 5.2 | `claude-fable-5-2` | 1M | \$8.00 | \$40.00 |
|
||||
| Claude Mythos 5.2 (verified organizations only) | `claude-mythos-5-2` | 1M | \$8.00 | \$40.00 |
|
||||
| Claude Fable 5.1 | `claude-fable-5-1` | 1M | \$10.00 | \$50.00 |
|
||||
| Claude Mythos 5.1 (verified organizations only) | `claude-mythos-5-1` | 1M | \$10.00 | \$50.00 |
|
||||
| Claude Fable 5 | `claude-fable-5` | 1M | \$10.00 | \$50.00 |
|
||||
| Claude Opus 5.5 | `claude-opus-5-5` | 1M | \$4.00 | \$20.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.7 | `claude-opus-4-7` | 1M | \$5.00 | \$25.00 |
|
||||
| Claude Opus 4.6 | `claude-opus-4-6` | 1M | \$5.00 | \$25.00 |
|
||||
| Claude Sonnet 5.5 | `claude-sonnet-5-5` | 1M | \$2.00 | \$10.00 |
|
||||
| Claude Sonnet 5 | `claude-sonnet-5` | 1M | \$2.00 | \$10.00 |
|
||||
| Claude Sonnet 4.6 | `claude-sonnet-4-6` | 1M | \$3.00 | \$15.00 |
|
||||
| Claude Haiku 5.5 | `claude-haiku-5-5` | 1M | \$0.10 | \$0.50 |
|
||||
| Claude Haiku 4.5 | `claude-haiku-4-5` | 200K | \$1.00 | \$5.00 |
|
||||
|
||||
**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 current prices, use the Pricing row in `shared/live-sources.md`.
|
||||
|
||||
@@ -206,23 +207,23 @@ Claude Fable 5.2 is Anthropic's most capable widely released model, for the most
|
||||
- **Thinking is always on** - omit the `thinking` parameter entirely (or send `{type: "adaptive"}`). Any other explicit configuration is rejected: `{type: "disabled"}` and `{type: "enabled", budget_tokens: N}` both return a 400. Control depth with `output_config.effort` (supports `low` through `xhigh` and `max`).
|
||||
- **The raw chain of thought is never returned** - responses carry regular `thinking` blocks (not `redacted_thinking`): `display: "summarized"` returns a readable summary, `"omitted"` (the default) leaves the `thinking` field as an empty string. Replay rules: pass thinking blocks back unchanged on the same model; other models drop them silently (unbilled - nothing to strip; Claude Mythos 5.2 instead reads them); details in `shared/model-migration.md`.
|
||||
- **Tokenizer** - same tokenizer as Opus 4.8 (introduced with Opus 4.7). Token counts are roughly unchanged when migrating from Opus 4.7/4.8; per-token pricing differs. Coming from Opus 4.6, Sonnet 4.6, Haiku 4.5, or older, re-baseline with `count_tokens` (the Opus 4.7 tokenizer uses ~1×-1.35× as many tokens).
|
||||
- **`refusal` stop reason - handle it, and opt into fallbacks by default** - safety classifiers may decline a request (HTTP 200, `stop_reason: "refusal"`, with a `stop_details` category); always check `stop_reason` before reading `content`. **When you write `claude-fable-5-2`, `claude-fable-5-1`, `claude-opus-5-5`, `claude-opus-5`, or `claude-sonnet-5-5` code, include the server-side `fallbacks` parameter by default** (for `claude-sonnet-5-5`, prefer the `"default"` form: the array form may name only `claude-sonnet-5`; on platforms without server-side `fallbacks` use the SDK middleware below, except when the request sends `between_tools`: only Claude Sonnet 5.5 accepts it and the middleware re-sends the same request body on the fallback model, so write the retry yourself and send it without `between_tools` - see `shared/model-migration.md` -> Migrating to Claude Sonnet 5.5 -> Safeguards and fallback). Simplest form: `betas: ["server-side-fallback-2026-07-01"]` + `fallbacks: "default"`, which routes by refusal category so you never maintain a model list. (With the array form you name the fallback model yourself: the same beta with `fallbacks: [{"model": "claude-opus-4-8"}]`, or `claude-sonnet-5` for `claude-sonnet-5-5`. On Bedrock, Vertex and Foundry, use the SDKs' client-side `BetaRefusalFallbackMiddleware` + `BetaFallbackState`.) Tell the user you've enabled it; drop it only if they decline. Full semantics (billing, mid-stream refusals, credit repricing) in `shared/model-migration.md` -> refusal section. **Per-language code examples in `{lang}/claude-api/README.md` § Refusal Fallbacks cover the array form only** - for the `"default"` mode, send the same request with `fallbacks: "default"` (Go: `anthropic.BetaFallbacksParamOfDefault()`; C#: `new Default()`); the header doesn't change.
|
||||
- **`refusal` stop reason - handle it, and opt into fallbacks by default** - safety classifiers may decline a request (HTTP 200, `stop_reason: "refusal"`, with a `stop_details` category); always check `stop_reason` before reading `content`. **When you write `claude-fable-5-2`, `claude-fable-5-1`, `claude-opus-5-5`, `claude-opus-5`, or `claude-sonnet-5-5` code, include the server-side `fallbacks` parameter by default** (for `claude-sonnet-5-5`, prefer the `"default"` form: the array form may name only `claude-sonnet-5`; on platforms without server-side `fallbacks` use the SDK middleware below, except when the request sends `between_tools`: only Claude Sonnet 5.5 accepts it and the middleware re-sends the same request body on the fallback model, so write the retry yourself and send it without `between_tools` - see `shared/model-migration.md` -> Migrating to Claude Sonnet 5.5 -> Safeguards and fallback). Simplest form: `betas: ["server-side-fallback-2026-07-01"]` + `fallbacks: "default"`, which routes by refusal category so you never maintain a model list. (With the array form you name the fallback model yourself: the same beta with `fallbacks: [{"model": "claude-opus-4-8"}]`, or `claude-sonnet-5` for `claude-sonnet-5-5`. On Claude Platform on AWS, Bedrock, Vertex and Foundry, use the SDKs' client-side `BetaRefusalFallbackMiddleware` + `BetaFallbackState`.) Tell the user you've enabled it; drop it only if they decline. Full semantics (billing, mid-stream refusals, credit repricing) in `shared/model-migration.md` -> refusal section. **Per-language code examples in `{lang}/claude-api/README.md` § Refusal Fallbacks cover the array form only, except C#'s and Java's** - for the `"default"` mode, send the same request with `fallbacks: "default"` (Go: `anthropic.BetaFallbacksParamOfDefault()`); the header doesn't change.
|
||||
- **No assistant prefill** - same as the rest of the 4.6+ family.
|
||||
- **30-day data retention required** - Claude Fable 5.2 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.2 -> Choosing an effort level and Behavioral shifts (prompt-tunable) for the recommended prompt snippets, and Migrating to Claude Fable 5.1 -> Behavioral shifts -> Longer turns by default for planning long turns.
|
||||
- **Successor to Claude Fable 5.1 (`claude-fable-5-1`, still served) at a lower price - $8 / $40 per MTok, cache reads $0.20.** Same surface (forced `tool_choice` `any` / `tool` 400s, preserved thinking and, in beta, per-message `effort`, turn-scoped `clear_at` system messages and `thinking.display: "updates"`) with four breaking changes: the history-editing check is enforced for **every** account, on Claude Mythos 5.2 too (make every harness append-only and run the three-step check); no model released earlier reads its thinking blocks, Claude Fable 5.1 included, and they work only in the account that produced them or one linked to it; `computer_20251124` 400s on every platform except Amazon Bedrock (use `computer_toolset_20260801`); and with the advisor tool a Claude Fable 5.2 executor accepts only `claude-fable-5-2` or `claude-mythos-5-2` as its advisor. No structured outputs in an organization using customer-managed encryption keys (CMEK). Covered Model - ZDR orgs get `400 invalid_request_error`; no Priority Tier; fast mode as in § Fast Mode; its own rate limit (Claude Mythos 5.2 shares one with the earlier Mythos models). See `shared/model-migration.md` -> Migrating to Claude Fable 5.2.
|
||||
- **Successor to Claude Fable 5.1 (`claude-fable-5-1`, still served) at a lower price - \$8 / \$40 per MTok, cache reads \$0.20.** Same surface (forced `tool_choice` `any` / `tool` 400s, preserved thinking and, in beta, per-message `effort`, turn-scoped `clear_at` system messages and `thinking.display: "updates"`) with four breaking changes: the history-editing check is enforced for **every** account, on Claude Mythos 5.2 too (make every harness append-only and run the three-step check); no model released earlier reads its thinking blocks, Claude Fable 5.1 included, and they work only in the account that produced them or one linked to it; `computer_20251124` 400s on every platform except Amazon Bedrock (use `computer_toolset_20260801`); and with the advisor tool a Claude Fable 5.2 executor accepts only `claude-fable-5-2` or `claude-mythos-5-2` as its advisor. No structured outputs in an organization using customer-managed encryption keys (CMEK). Covered Model - ZDR orgs get `400 invalid_request_error`; no Priority Tier; fast mode as in § Fast Mode; its own rate limit (Claude Mythos 5.2 shares one with the earlier Mythos models). See `shared/model-migration.md` -> Migrating to Claude Fable 5.2.
|
||||
|
||||
### Claude Opus 5.5 (`claude-opus-5-5`) - the current Opus and the default model
|
||||
|
||||
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 these read its blocks: Fable 5.2 and Mythos 5.2, and on the Claude API Fable 5.1 and Mythos 5.1; 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 **on the Claude API and Google Cloud, computer use only through `computer_toolset_20260801`** (`computer_20251124` 400s there; Amazon Bedrock still accepts it). Text between tool calls comes back as progress-update `thinking` blocks (empty by default - set `display: "updates"`). Broader safety classifiers: `bio` joins `cyber` and `reasoning_extraction`. Fast mode: $8 / $40 per MTok (2x standard), platforms in § Fast Mode. See `shared/model-migration.md` -> Migrating to Claude Opus 5.5.
|
||||
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 these read its blocks: Fable 5.2 and Mythos 5.2, and on the Claude API Fable 5.1 and Mythos 5.1; so a fallback to Claude Opus 5 runs without them; failing the history-editing check with `prefix_mismatch_behavior` unset might or might not return a 400; on Bedrock and Vertex, the 400 applies to accounts and projects that first used Claude there on or after August 31, 2026; earlier ones might or might not get it); and **on the Claude API and Google Cloud, computer use only through `computer_toolset_20260801`** (`computer_20251124` 400s there; Amazon Bedrock still accepts it). Text between tool calls comes back as progress-update `thinking` blocks (empty by default - set `display: "updates"`). Broader safety classifiers: `bio` joins `cyber` and `reasoning_extraction`. Fast mode: \$8 / \$40 per MTok (2x standard), platforms in § Fast Mode. See `shared/model-migration.md` -> Migrating to Claude Opus 5.5.
|
||||
|
||||
### Claude Sonnet 5.5 (`claude-sonnet-5-5`) - the current Sonnet: speed and capability for everyday coding, agent, and enterprise work (Claude Opus 5.5 stays the default)
|
||||
|
||||
Successor to Claude Sonnet 5 in the Sonnet line at the same prices ($2 / $10 per MTok), except cache reads at $0.10, with the same tokenizer, 1M context and 128K output. Five breaking changes for code running on Claude Sonnet 5: **`thinking: {type: "disabled"}` returns a 400** - to turn thinking off, send `thinking: {type: "between_tools"}`, which is accepted only at effort `high` or below, takes no other field (`display`, `budget_tokens`, or `block_binding` alongside it is a 400), and doesn't allow per-message effort changes; **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** (only Claude Opus 5.5 on the Claude API and Google Cloud Vertex AI, and Fable / Mythos 5.2, read its blocks; accounts created on or after 2026-08-31 are enforced on the history-editing check); **on the Claude API and Google Cloud, computer use only through `computer_toolset_20260801`** (`computer_20251124` 400s there; Amazon Bedrock still accepts it); and **the advisor tool rejects Claude Opus 4.8, Claude Opus 4.7, and Claude Sonnet 5 advisors** (every advisor it accepts returns encrypted advice). Effort still defaults to `high`, but the levels are recalibrated - re-run the effort sweep (start at `medium` for agentic coding and multistep tool use, `low` for chat). Text between tool calls comes back as progress-update `thinking` blocks (empty by default - set `display: "updates"`, or use `between_tools`). Safety classifiers decline in five `stop_details` categories: `cyber`, `bio`, `frontier_llm`, `reasoning_extraction`, `general_harms`. See `shared/model-migration.md` -> Migrating to Claude Sonnet 5.5.
|
||||
Successor to Claude Sonnet 5 in the Sonnet line at the same prices (\$2 / \$10 per MTok), except cache reads at \$0.10, with the same tokenizer, 1M context and 128K output. Five breaking changes for code running on Claude Sonnet 5: **`thinking: {type: "disabled"}` returns a 400** - to turn thinking off, send `thinking: {type: "between_tools"}`, which is accepted only at effort `high` or below, takes no other field (`display`, `budget_tokens`, or `block_binding` alongside it is a 400), and doesn't allow per-message effort changes; **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** (only Claude Opus 5.5 on the Claude API and Google Cloud Vertex AI, and Fable / Mythos 5.2, read its blocks; failing the history-editing check with `prefix_mismatch_behavior` unset might or might not return a 400; on Bedrock and Vertex, the 400 applies to accounts and projects that first used Claude there on or after August 31, 2026; earlier ones might or might not get it); **on the Claude API and Google Cloud, computer use only through `computer_toolset_20260801`** (`computer_20251124` 400s there; Amazon Bedrock still accepts it); and **the advisor tool rejects Claude Opus 4.8, Claude Opus 4.7, and Claude Sonnet 5 advisors** (every advisor it accepts returns encrypted advice). Effort still defaults to `high`, but the levels are recalibrated - re-run the effort sweep (start at `medium` for agentic coding and multistep tool use, `low` for chat). Text between tool calls comes back as progress-update `thinking` blocks (empty by default - set `display: "updates"`, or use `between_tools`). Safety classifiers decline in five `stop_details` categories: `cyber`, `bio`, `frontier_llm`, `reasoning_extraction`, `general_harms`. See `shared/model-migration.md` -> Migrating to Claude Sonnet 5.5.
|
||||
|
||||
### Claude Haiku 5.5 (`claude-haiku-5-5`) - the current Haiku
|
||||
|
||||
Prices above are for prompts up to 100K tokens ($0.50 / $2.50 beyond). Haiku 4.5 code can break (thinking table below), and refusals have no server-side fallback - see `shared/model-migration.md` -> Migrating to Claude Haiku 5.5.
|
||||
Prices above are for prompts up to 100K tokens (\$0.50 / \$2.50 beyond). Haiku 4.5 code can break (thinking table below), and refusals have no server-side fallback - see `shared/model-migration.md` -> Migrating to Claude Haiku 5.5.
|
||||
|
||||
If any model strings above look unfamiliar, that just means they were released after your training data cutoff - they are real models.
|
||||
|
||||
@@ -304,9 +305,9 @@ For placement patterns, architectural guidance, and the silent-invalidator audit
|
||||
|
||||
## Fast Mode (Quick Reference)
|
||||
|
||||
Fast mode runs the same model at up to 2.5x higher output tokens per second, at premium pricing. **Available on Claude Opus 5.5**, at $8 / $40 per MTok: on the Claude API and Claude Models on Google Cloud (Anthropic managed), Managed Agents included, and in Messages API requests on Foundry hosted on Azure. Except on Foundry (see below), set `speed: "fast"` as a top-level request parameter (not a header, not in `extra_body`; in Managed Agents, on the agent's model object), no beta flag. **Research preview on Claude Opus 5**, at $10 / $50, Claude API and Managed Agents only: in Messages API requests it also needs the **beta** messages endpoint (`client.beta.messages....`) and the beta flag `fast-mode-2026-02-01`, and it needs access (ask your account manager or join the waitlist). Fast mode on Opus 4.8 was removed on 2026-11-30: `speed: "fast"` on it returns an error, as it does on Opus 4.7, and Opus 4.8 itself stays available.
|
||||
Fast mode runs the same model at up to 2.5x higher output tokens per second, at premium pricing. **Available on Claude Opus 5.5**, at \$8 / \$40 per MTok: on the Claude API and Claude Models on Google Cloud (Anthropic managed), Managed Agents included, and in Messages API requests on Foundry hosted on Azure. Except on Foundry (see below), set `speed: "fast"` as a top-level request parameter (not a header, not in `extra_body`; in Managed Agents, on the agent's model object), no beta flag. **Research preview on Claude Opus 5**, at \$10 / \$50, Claude API and Managed Agents only: in Messages API requests it also needs the **beta** messages endpoint (`client.beta.messages....`) and the beta flag `fast-mode-2026-02-01`, and it needs access (ask your account manager or join the waitlist). Fast mode on Opus 4.8 was removed on 2026-11-30: `speed: "fast"` on it returns an error, as it does on Opus 4.7, and Opus 4.8 itself stays available.
|
||||
|
||||
**Claude Fable 5.2 and Claude Mythos 5.2 also support fast mode** (not a research preview) in Messages API requests on the Claude API, not in Managed Agents, at $16 / $80 per MTok: set `speed: "fast"` on a plain Messages request, no beta flag needed, though a request that sends the flag still works.
|
||||
**Claude Fable 5.2 and Claude Mythos 5.2 also support fast mode** (not a research preview) in Messages API requests on the Claude API, not in Managed Agents, at \$16 / \$80 per MTok: set `speed: "fast"` on a plain Messages request, no beta flag needed, though a request that sends the flag still works.
|
||||
|
||||
**On Microsoft Foundry, fast mode is a separate model**: send requests to a `claude-opus-5-5-fast` deployment (hosted on Azure) or, where offered, a `claude-fable-5-2-fast` or `claude-mythos-5-2-fast` deployment (hosted on Anthropic), and leave out `speed`: a request that sets it on a deployment of the model without `-fast` returns an error. To fall back to standard speed there, retry on a deployment of the model without `-fast`. For other models and platforms, fetch the page in the **Fast Mode** row in `shared/live-sources.md`.
|
||||
|
||||
@@ -348,9 +349,9 @@ with client.beta.messages.stream(
|
||||
response = stream.get_final_message()
|
||||
```
|
||||
|
||||
`task_budget` fields: `type` (always `"tokens"`), `total`, and optional `remaining` (defaults to `total`). The server injects a countdown marker Claude sees during generation; the budget counts what Claude generates and the tool results it reads this turn - **not** the full history you resend each request. Not the same thing as **Managed Agents session budgets** - those are hard, dollar-denominated, platform-enforced caps on one CMA session (`shared/managed-agents-core.md` § Session budgets); a task budget is advisory and token-denominated.
|
||||
`task_budget` fields: `type` (always `"tokens"`), `total`, and optional `remaining` (defaults to `total`). The server injects a countdown marker Claude sees during generation; the budget counts each token Claude sees once - what it generates and the tool results it reads - so resending history within a turn adds nothing. A user message with no tool results starts a new turn with a fresh budget, but history from earlier turns currently still counts against it while it stays in context. Not the same thing as **Managed Agents session budgets** - those are hard, dollar-denominated, platform-enforced caps on one CMA session (`shared/managed-agents-core.md` § Session budgets); a task budget is advisory and token-denominated.
|
||||
|
||||
**Observing spend:** accumulate `response.usage.output_tokens` (plus the token count of the tool-result blocks you append) across loop iterations if you want to display progress. Leave `remaining` unset in the normal loop - the server tracks the countdown itself, and passing a client-computed `remaining` while also resending full history under-reports the budget. **Only pass `remaining`** when you compact or rewrite history between requests and the server can no longer derive prior spend.
|
||||
**Observing spend:** accumulate `response.usage.output_tokens` (plus the token count of the tool-result blocks you append) across loop iterations to display progress. Leave `remaining` unset in the normal loop - the server tracks the countdown itself, and passing a client-computed `remaining` while also resending full history under-reports the budget. **Only pass `remaining`** when you compact or rewrite history between requests and the server can no longer derive prior spend. Then send `total` minus the usage of every message removed so far; don't subtract what you still send, including a summary. Keep sending it; change it only when you replace history. Never send it with threshold or on-demand compaction, or a compaction block (400).
|
||||
|
||||
---
|
||||
|
||||
@@ -385,25 +386,25 @@ Use the **Mantle** client (Messages-API Bedrock endpoint). Bedrock model IDs tak
|
||||
| Java | `AnthropicOkHttpClient.builder().backend(FoundryBackend.fromEnv()).build()` (from `com.anthropic.foundry.backends`) |
|
||||
| C# | `new AnthropicFoundryClient(new AnthropicFoundryApiKeyCredentials(...))` (package `Anthropic.Foundry`) |
|
||||
| PHP | `Foundry\Client::fromEnvironment(baseUrl: '...')` (reads `ANTHROPIC_FOUNDRY_API_KEY`) |
|
||||
| Go | `import "github.com/anthropics/anthropic-sdk-go/v2/foundry"` -> `client, err := foundry.NewClient(foundry.ClientConfig{ APIKey: "...", Resource: "..." })` |
|
||||
| Ruby | `Anthropic::FoundryClient.new(resource: "...", api_key: "...")` (gem `anthropic` 2.5.0+) |
|
||||
|
||||
For Claude Mythos models, use Microsoft Entra ID tokens, not API keys (`https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry`).
|
||||
|
||||
The Go and Ruby SDKs do not currently support Foundry. For Ruby, use the standard `Anthropic::Client.new(base_url: "<foundry endpoint>")` as a fallback (Entra ID auth is not built in).
|
||||
|
||||
### Google Cloud Vertex AI
|
||||
|
||||
For Claude Models on Google Cloud (Anthropic managed), use `shared/google-cloud-anthropic-managed.md` instead.
|
||||
|
||||
Two required constructor args: GCP `project_id` and `region`. Vertex model IDs take **no prefix** - current-generation models (Opus 5.5/5/4.8/4.7/4.6, Sonnet 5.5, Sonnet 5, Sonnet 4.6) use the bare first-party ID (e.g. `"claude-opus-5-5"`); dated-snapshot models use an `@` version separator (e.g. `claude-opus-4-5@20251101`, **not** `claude-opus-4-5-20251101`). Auth is GCP ADC (`gcloud auth application-default login`); no Anthropic API key. `region` can be `"global"` (recommended), a multi-region (`"us"`/`"eu"`), or a specific region.
|
||||
Two required constructor args: GCP `project_id` and `region`. Vertex model IDs take **no prefix** - Claude 4.6 and later models use the bare first-party ID (e.g. `"claude-opus-5-5"`); older models put an `@` before the snapshot date (e.g. `claude-opus-4-5@20251101`, **not** `claude-opus-4-5-20251101`). Auth is GCP ADC (`gcloud auth application-default login`); no Anthropic API key. `region` can be `"global"` (recommended), a multi-region (`"us"`/`"eu"`), or, for Claude Sonnet 4.6 and earlier models only, a specific region.
|
||||
|
||||
| Language | Client |
|
||||
|---|---|
|
||||
| Python | `from anthropic import AnthropicVertex` -> `AnthropicVertex(project_id="...", region="...")` (install `"anthropic[vertex]"`) |
|
||||
| TypeScript | `import { AnthropicVertex } from "@anthropic-ai/vertex-sdk"` -> `new AnthropicVertex({ projectId, region })` |
|
||||
| Go | `import "github.com/anthropics/anthropic-sdk-go/v2/vertex"` -> `anthropic.NewClient(vertex.WithGoogleAuth(ctx, region, projectID))` |
|
||||
| Java | `AnthropicOkHttpClient.builder().backend(VertexBackend.builder().region("...").project("...").build()).build()` (from `com.anthropic.vertex.backends`) |
|
||||
| C# | `new AnthropicClient { Backend = new VertexBackend(projectId, region) }` (package `Anthropic.Vertex`) |
|
||||
| PHP | `use Anthropic\Vertex;` -> `Vertex\Client::fromEnvironment(location: '...', projectId: '...')` - note `location`, not `region` |
|
||||
| Java | `AnthropicOkHttpClient.builder().backend(VertexBackend.builder().googleCredentials(GoogleCredentials.getApplicationDefault()).region("...").project("...").build()).build()` (from `com.anthropic.vertex.backends`) |
|
||||
| C# | `new AnthropicVertexClient(new AnthropicVertexCredentials(region, projectId))` (package `Anthropic.Vertex`) |
|
||||
| PHP | `use Anthropic\Vertex;` -> `Vertex\Client::fromEnvironment(region: '...', projectId: '...')` |
|
||||
| Ruby | `Anthropic::VertexClient.new(region: "...", project_id: "...")` |
|
||||
|
||||
---
|
||||
@@ -467,17 +468,17 @@ Availability: `shared/platform-availability.md`. For agents on Vertex / Foundry
|
||||
|
||||
## Server Tools (Quick Reference)
|
||||
|
||||
Server-side tools run on Anthropic's infrastructure - no client-side execution loop. Declare in `tools`; results arrive as content blocks in the same response. **No beta header** unless noted. **Prefer the latest type variant your model supports.** The `_20260209` web search / web fetch variants below (dynamic filtering) require Fable 5/5.1/5.2, Mythos 5/5.1/5.2, Opus 5.5/5/4.8/4.7/4.6, Sonnet 5.5, Sonnet 5, or Sonnet 4.6; the basic variants for older models are listed after the table.
|
||||
Server-side tools run on Anthropic's infrastructure - no client-side execution loop. Declare in `tools`; results arrive as content blocks in the same response. **No beta header** unless noted. **Prefer the latest type variant your model supports.** The web search and web fetch variants dated `_20260209` or later (dynamic filtering) require Claude 4.6 or later, Fable and Mythos included; older models' basic variants follow the table.
|
||||
|
||||
| Tool | `type` | `name` | Key optional params | Result block type |
|
||||
|---|---|---|---|---|
|
||||
| Web search | `web_search_20260209` | `web_search` | `max_uses`, `allowed_domains`/`blocked_domains`, `user_location` | `web_search_tool_result` -> `.content` is a list of `web_search_result` |
|
||||
| Web fetch | `web_fetch_20260209` | `web_fetch` | `max_uses`, `allowed_domains`/`blocked_domains`, `citations`, `max_content_tokens` | `web_fetch_tool_result` -> `.content` is a `web_fetch_result` with a `document` block |
|
||||
| Web search | `web_search_20260318` | `web_search` | `max_uses`, `allowed_domains`/`blocked_domains`, `user_location` | `web_search_tool_result` -> `.content` is a list of `web_search_result` |
|
||||
| Web fetch | `web_fetch_20260318` | `web_fetch` | `max_uses`, `allowed_domains`/`blocked_domains`, `citations`, `max_content_tokens`, `use_cache` (`false` skips the cache) | `web_fetch_tool_result` -> `.content` is a `web_fetch_result` with a `document` block |
|
||||
| Code execution | `code_execution_20260521` | `code_execution` | none | `bash_code_execution_tool_result` -> `.content.stdout` / `.stderr` / `.return_code` |
|
||||
| Tool search (regex) | `tool_search_tool_regex_20251119` | `tool_search_tool_regex` | mark other tools `defer_loading: true` | `tool_search_tool_result` |
|
||||
| Tool search (BM25) | `tool_search_tool_bm25_20251119` | `tool_search_tool_bm25` | mark other tools `defer_loading: true` | `tool_search_tool_result` |
|
||||
|
||||
`web_search_20260209` / `web_fetch_20260209` have built-in dynamic filtering - code execution runs under the hood, so do **not** separately declare `code_execution` in `tools` (a second execution environment confuses the model). For models older than Opus 4.6 / Sonnet 4.6, use the basic variants `web_search_20250305` / `web_fetch_20250910` instead; on Vertex AI only basic `web_search_20250305` is available. `code_execution_20260120` (REPL persistence + programmatic tool calling) runs on Opus 4.5+ / Sonnet 4.6+ / Haiku 5.5 / Fable / Mythos; Haiku 4.5 accepts it without programmatic tool calling. **Go SDK only**: `code_execution_20260521` lives under `client.Beta.Messages.New` with `Betas: []anthropic.AnthropicBeta{"code-execution-2025-08-25"}` (other languages use plain `client.messages.create`); `code_execution_20260120` uses the non-beta `client.Messages.New` in Go like everywhere else. Web fetch only fetches URLs already present in the conversation. Provider availability varies by tool - see `shared/platform-availability.md`. See `shared/tool-use-concepts.md` for `pause_turn` handling.
|
||||
`_20260209` and later web tools have built-in dynamic filtering: the API provisions code execution, so they need no `code_execution` entry in `tools`. For code execution of your own, add `code_execution_20260120` or later; the API rejects older versions beside these web tools. For models older than Opus 4.6 / Sonnet 4.6, use the basic variants `web_search_20250305` / `web_fetch_20250910`; on Vertex AI only basic `web_search_20250305` is available, and on Foundry deployments hosted on Azure only those two basic variants. `code_execution_20260120` adds REPL persistence and programmatic tool calling (neither on Haiku 4.5). Web fetch only fetches URLs already present in the conversation. Provider availability varies by tool - see `shared/platform-availability.md`. See `shared/tool-use-concepts.md` for `pause_turn` handling.
|
||||
|
||||
## Document & File Input (Quick Reference)
|
||||
|
||||
@@ -487,6 +488,8 @@ Server-side tools run on Anthropic's infrastructure - no client-side execution l
|
||||
|
||||
**Citations (no beta):** set `citations: {enabled: true}` on each `document` content block (all or none). Response splits into multiple `text` blocks; cited blocks carry a `citations` array. Each citation has `cited_text`, `document_index`, `document_title`, and a location by `type`: `char_location` (`start_char_index`/`end_char_index`) for plain text, `page_location` (`start_page_number`/`end_page_number`, 1-indexed) for PDF, `content_block_location` for custom content. Incompatible with `output_config.format` (returns a 400).
|
||||
|
||||
**Bounding boxes, click points:** read `shared/vision-coordinates.md`.
|
||||
|
||||
## Tool Use Patterns (Quick Reference)
|
||||
|
||||
**Strict tool use (no beta):** set `strict: true` as a top-level field on the tool definition (alongside `name`/`description`/`input_schema`), **not** on `tool_choice`. Schema must have `additionalProperties: false` + `required`. Guarantees `tool_use.input` validates exactly. Go: `Strict: anthropic.Bool(true)` + `additionalProperties` via `InputSchema.ExtraFields`; Java: `.strict(true)` + `.putAdditionalProperty("additionalProperties", JsonValue.from(false))`.
|
||||
@@ -563,6 +566,8 @@ After you build a large job, read `tool-use.md`'s top.
|
||||
-> Read `shared/prompt-caching.md` (prefix-stability design, breakpoint placement, anti-patterns that silently invalidate cache) + `{lang}/claude-api/README.md` (Prompt Caching section)
|
||||
**Auditing or cleaning up prompts, tool descriptions, skills, or agent configuration files such as `CLAUDE.md` ("is this prompt outdated", "remove the cruft", "this was written for an older model"):**
|
||||
-> Read `shared/prompt-audit.md` - dated-pattern tables with greppable signals, the keep list (what NOT to delete), and the report + proposed-diff output contract
|
||||
**Auditing an agent harness (caps, sub-agents, compaction, injected reminders) for code written for older models:**
|
||||
-> Read `shared/harness-audit.md` - harness anti-pattern tables, keep list, report + proposed diff
|
||||
**Count tokens in a file / prompt / diff ("how many tokens is X"):**
|
||||
-> Read `shared/token-counting.md` - use `messages.count_tokens`, never `tiktoken`
|
||||
**Reducing or reviewing API spend ("the bill is too high", "make this cheaper", "am I overspending", cost per completed task, cheapest model or effort that holds quality):**
|
||||
@@ -582,7 +587,7 @@ After you build a large job, read `tool-use.md`'s top.
|
||||
**File uploads across multiple requests (same file without re-uploading):**
|
||||
-> Read `{lang}/claude-api/README.md` + `{lang}/claude-api/files-api.md`
|
||||
|
||||
**Organization administration (members, invites, workspaces, API keys, rate limit reports, usage and cost reports, service accounts, WIF resources, CMEK):**
|
||||
**Organization administration (members, invites, workspaces, API keys, rate limit reports, usage and cost reports, service accounts, WIF resources, CMEK, user profiles):**
|
||||
-> Read `shared/admin-api.md` - `client.beta.organization` endpoint/method table, admin credentials, per-language naming and pagination, what stays curl-only
|
||||
|
||||
**Monitoring, logging, tracing or observability of Claude API calls or Managed Agents sessions (OpenTelemetry: SDK spans, trace destinations set up through the Admin API or the Console, `traceparent`, span attributes, token counts from spans):**
|
||||
@@ -608,7 +613,7 @@ This skill can lag behind the API and SDKs. Before you tell the user that a feat
|
||||
- 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 / 5.1 / 5.2, Opus 5, Claude Opus 5.5, Sonnet 5, Claude Sonnet 5.5, and the 4.6/4.7/4.8 family):** Assistant message prefills (last-assistant-turn prefills) return a 400 error on Fable 5 / 5.1 / 5.2, Opus 5, Claude Opus 5.5, Sonnet 5, Claude Sonnet 5.5, Claude Haiku 5.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.
|
||||
- **`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 (`~1024`, thinking counts toward it), 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.** (On Claude Opus 5.5, `{type: "disabled"}` is a 400 at every effort level - use `low` effort. On Claude Sonnet 5.5 it is also a 400 - try `low` effort first, and if a route must stay thinking-off, send `{type: "between_tools"}` at `high` effort or below.) Watch for a disabled-thinking setting carried forward from Opus 4.8. With it, the model occasionally writes a tool call into its **visible text** instead of a `tool_use` block (the call never runs, no error is raised), and can leak `<thinking>` tags. Turning thinking on and lowering `effort` fixes both. If a route must stay thinking-off: **delete** any don't-think/don't-reason rule, don't name thinking tags, and add *"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 / 5.1 / 5.2, Opus 5, Claude Opus 5.5, Opus 4.6, Opus 4.7, Opus 4.8, Claude Sonnet 5.5, Sonnet 5, Sonnet 4.6, and Claude Haiku 5.5 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 (Fable 5.2 / 5.1, Mythos 5.2 / 5.1, Claude Opus 5.5, Claude Sonnet 5.5):** `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).
|
||||
@@ -619,17 +624,17 @@ This skill can lag behind the API and SDKs. Before you tell the user that a feat
|
||||
- **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 fetching pages, 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.
|
||||
- **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-5` -> advisor `claude-opus-5-5`. An invalid pair returns 400; a `claude-sonnet-5-5` executor accepts only the advisors its row in the pairing table lists (not Claude Opus 4.8 / 4.7 / 4.6, Claude Sonnet 5, or Sonnet 4.6). 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.messages.create` with `container={"skills": [...]}` and the `code_execution_20260521` tool - no beta header. 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`.
|
||||
- **`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; 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)` and TypeScript's `betaZodTool({..., eager_input_streaming: true})` take it (before TS SDK 0.136.0, spread it onto the returned tool). 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`.
|
||||
- **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.
|
||||
- **Cache diagnostics needs no beta header.** `diagnostics` is the opt-in, so send it on every turn: `{previous_message_id: null}` on the first and `{previous_message_id: <previous response id>}` after that. Read `response.diagnostics`. Availability: `shared/platform-availability.md`.
|
||||
- **Memory tool type is `memory_20250818`.** Declare `{"type": "memory_20250818", "name": "memory"}`. Python/TypeScript/Ruby/PHP/C# use the non-beta `client.messages.create`; Go uses `client.Messages.New` with `{OfMemoryTool20250818: &anthropic.MemoryTool20250818Param{}}`; Java has both a non-beta `MemoryTool20250818` and a beta tool-runner path. Helpers for implementing the backend: `BetaAbstractMemoryTool` (Python, C#), `betaMemoryTool` (TypeScript), `BetaMemoryToolHandler` (Java).
|
||||
- **Use a model the feature actually supports.** Some features are restricted to specific model tiers - fast mode is limited to certain models and platforms (§ Fast Mode), task budgets (Messages API only - Managed Agents session budgets have no model-tier restriction) are Claude Opus 5 / Claude Opus 5.5 / Fable 5 / 5.1 / 5.2 / Mythos 5 / 5.1 / 5.2 / Claude Sonnet 5.5 / Claude Haiku 5.5 / Opus 4.8 / 4.7 only (not Claude Sonnet 5), 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.
|
||||
- **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.
|
||||
- **With `limited` networking, `allowed_hosts` also applies to Managed Agents web tools** (no hosts listed blocks both); `unrestricted` and self-hosted environments don't limit them. The organization's web settings in the Console also apply in sessions. Turn both off (`enabled: false`) unless the job needs the web; then list sites in `allowed_hosts` and restrict 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.
|
||||
- **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`). When another tool in the request lists code execution in its `allowed_callers` (as `web_search_20260209` and later do by default), the output can come back as `code_execution_tool_result` instead, with the same `.content.stdout`. Iterate `response.content` and match on both types.
|
||||
- **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`.
|
||||
|
||||
@@ -12,11 +12,11 @@ Types are organized by namespace. If a type you need isn't shown in an example b
|
||||
| `Anthropic.Models.Messages` | non-beta request/response types - `MessageCreateParams`, `Model`, `UserMessageParam`, `AssistantMessageParam`, `ContentBlock`, `TextBlock`, `ToolUseBlock`, `ToolResultBlockParam`, `Speed`, `Tool*` (tool definition classes) |
|
||||
| `Anthropic.Models.Beta.Messages` | beta-endpoint equivalents - `MessageCreateParams`, `BetaMessage`, `BetaTool*`, `Speed`, `BetaRequestMcpServerUrlDefinition`, context-editing/compaction configs |
|
||||
| `Anthropic.Models.Beta` | shared beta constants |
|
||||
| `Anthropic.Models.Beta.Files` | Files API types |
|
||||
| `Anthropic.Models.Files` | Files API types (`client.Files`) |
|
||||
| `Anthropic.Models.Messages.Batches` | Batch API types |
|
||||
| `Anthropic.Helpers.Beta` | `BetaToolRunner`, beta helper utilities |
|
||||
| `Anthropic.Exceptions` | `AnthropicApiException`, `AnthropicRateLimitException`, `Anthropic5xxException`, etc. - see `shared/error-codes.md` |
|
||||
| `Anthropic.Bedrock` / `Anthropic.Vertex` / `Anthropic.Foundry` / `Anthropic.Aws` | platform clients (separate NuGet packages): `AnthropicBedrockMantleClient`, `AnthropicFoundryClient`, `AnthropicAwsClient` |
|
||||
| `Anthropic.Bedrock` / `Anthropic.Vertex` / `Anthropic.Foundry` / `Anthropic.Aws` | platform clients (separate NuGet packages): `AnthropicBedrockMantleClient`, `AnthropicVertexClient`, `AnthropicFoundryClient`, `AnthropicAwsClient` |
|
||||
|
||||
`client.Messages.*` uses non-beta types; `client.Beta.Messages.*` uses the `Anthropic.Models.Beta.Messages` types. Both namespaces define a `MessageCreateParams` - pick the one matching the client path you call.
|
||||
|
||||
@@ -26,16 +26,17 @@ Write from this table instead of reflecting the SDK assembly. Endpoint column te
|
||||
|
||||
| Feature | Endpoint | Key C# types (namespace per table above) |
|
||||
|---|---|---|
|
||||
| User profiles | beta | `client.Beta.UserProfiles.Create(...)` / `.Retrieve(id)` / `.List()`. Pass the returned profile id on the beta messages call. Requires a beta header - check the SDK's beta-headers reference for the current flag. |
|
||||
| Agent Skills | beta | `BetaContainerParams` (with `Skills = [new BetaSkillParams { ... }]`), `BetaCodeExecutionTool20250825`. `Betas = ["code-execution-2025-08-25"]` (Skills is out of beta - no `skills-2025-10-02`). Download the output via `client.Beta.Files.Download(fileId)`. |
|
||||
| User profiles | non-beta | `client.UserProfiles.Create(...)` / `.Retrieve(id)` / `.List()`. Pass the returned profile id as `UserProfileID` on `MessageCreateParams`. |
|
||||
| Agent Skills | non-beta | `ContainerParams` (with `Skills = [new SkillParams { ... }]`), `CodeExecutionTool20260521`. Download the output via `client.Files.Download(fileId)`, then `ReadAsStream()` on the response (see `files-api.md`). |
|
||||
| Advisor tool | beta | `BetaAdvisorTool20260301` - may not be in all SDK releases yet |
|
||||
| Cache diagnostics | beta | `Diagnostics = new() { PreviousMessageID = ... }`, `BetaCacheControlEphemeral`, `BetaContentBlockParam` |
|
||||
| Context editing | beta | `ContextManagement = new BetaContextManagementConfig { Edits = [new BetaClearToolUses20250919Edit()] }`. `Betas = ["context-management-2025-06-27"]` (not `compact-2026-01-12` - that's for `BetaCompact20260112Edit`). |
|
||||
| Cache diagnostics | non-beta | `Diagnostics = new() { PreviousMessageID = ... }`, `CacheControlEphemeral`, `ContentBlockParam` |
|
||||
| Context editing | beta | `ContextManagement = new BetaContextManagementConfig { Edits = [new BetaClearToolUses20250919Edit { Trigger = new BetaInputTokensTrigger(30000), Keep = new BetaToolUsesKeep(3), ClearAtLeast = new BetaInputTokensClearAtLeast(5000) }] }` (the three settings are optional). `Betas = ["context-management-2025-06-27"]` (not `compact-2026-01-12` - that's for `BetaCompact20260112Edit`). |
|
||||
| Memory tool | non-beta | `Tools = [new ToolUnion(new MemoryTool20250818())]` |
|
||||
| Programmatic tool calling | non-beta | `CodeExecutionTool20260120`, `ToolResultBlockParam`, `ContentBlockParam` |
|
||||
| Programmatic tool calling | non-beta | `CodeExecutionTool20260120`, `ToolResultBlockParam`, `ContentBlockParam`. Continuing a paused call: `tool-use.md`. |
|
||||
| Vision, citations, search results, mid-conversation system messages, request and response headers | non-beta | `content-and-headers.md` |
|
||||
| Task budgets | beta | `BetaOutputConfig` with `TaskBudget = new BetaTokenTaskBudget { ... }` |
|
||||
| Tool search | non-beta | `new ToolUnion(new ToolSearchToolRegex20251119 { Type = ToolSearchToolRegex20251119Type.ToolSearchToolRegex20251119 })` - `Type` must be set explicitly. |
|
||||
| Web search | non-beta | `new ToolUnion(new WebSearchTool20260209())` - a variant with dynamic filtering (Claude Fable 5.2 / Claude Mythos 5.2 + Claude Fable 5.1 / Claude Mythos 5.1 + Claude Opus 5.5 + Claude Opus 5 + Opus 4.8/4.7/4.6 + Claude Sonnet 5.5 + Claude Sonnet 5 + Sonnet 4.6). For older models or Vertex, use `WebSearchTool20250305()` |
|
||||
| Web search | non-beta | `new ToolUnion(new WebSearchTool20260318())` - a variant with dynamic filtering (Claude 4.6 and later models, Fable and Mythos included). For older models, Vertex, or Foundry deployments hosted on Azure, use `WebSearchTool20250305()` |
|
||||
|
||||
### Discovering type and member names
|
||||
|
||||
@@ -47,7 +48,7 @@ Note that `strings` will not surface wire-format snake_case field names (`output
|
||||
|
||||
**Write a plain `Program.cs` body** - `using` statements followed by top-level statements, as below. Do **not** add a `#!/usr/bin/env dotnet` shebang or `#:package Anthropic@*` directive: those are .NET file-based-app syntax and fail with `CS1024: Preprocessor directive expected` when the file is compiled via an existing `.csproj`. The standard project setup (per the [C# quickstart](https://platform.claude.com/docs/en/get-started): `dotnet new console` -> `dotnet add package Anthropic` -> edit `Program.cs` -> `dotnet run`) provides the `.csproj` and package reference.
|
||||
|
||||
Start from this - it compiles as-is. Fill in the feature-specific fields; do not spend turns running reflection or XML-doc inspection to discover type names first.
|
||||
Start from this - it compiles as-is. Fill in the feature-specific fields; do not spend turns running reflection or XML-doc inspection to discover type names first. These pages assume `ImplicitUsings`, which `dotnet new console` turns on. If the `.csproj` has no `<ImplicitUsings>enable</ImplicitUsings>` line, add the `using System...;` lines the code needs (`System.Linq`, `System.Collections.Generic`, `System.Threading.Tasks`, `System.IO`).
|
||||
|
||||
```csharp
|
||||
using System;
|
||||
@@ -195,9 +196,10 @@ using NonBeta = Anthropic.Models.Messages; // only if you also need non-beta ty
|
||||
```
|
||||
|
||||
|
||||
`BetaMessage.Content` is `IReadOnlyList<BetaContentBlock>` - a 15-variant discriminated union. Narrow with `TryPick*`. **Response `BetaContentBlock` is NOT assignable to param `BetaContentBlockParam`** - there's no `.ToParam()` in C#. Round-trip by converting each block:
|
||||
`BetaMessage.Content` is `IReadOnlyList<BetaContentBlock>` - an 18-variant discriminated union. Narrow with `TryPick*`. **Response `BetaContentBlock` is NOT assignable to param `BetaContentBlockParam`** - there's no `.ToParam()` in C#. Send the reply back by wrapping each block's JSON, which keeps thinking and compaction blocks intact:
|
||||
|
||||
```csharp
|
||||
using System.Linq;
|
||||
using Anthropic.Models.Beta.Messages;
|
||||
|
||||
var betaParams = new MessageCreateParams // no Beta prefix - see unprefixed list above
|
||||
@@ -229,20 +231,10 @@ if (resp.ContextManagement is { } ctx)
|
||||
Console.WriteLine($"cleared {edit.ClearedInputTokens} tokens");
|
||||
}
|
||||
|
||||
// ROUND-TRIP: BetaAssistantMessageParam.Content is BetaMessageContentParam (a string|list
|
||||
// union). It implicit-converts from List<BetaContentBlockParam>, NOT from the
|
||||
// response's IReadOnlyList<BetaContentBlock>. Convert each block:
|
||||
List<BetaContentBlockParam> paramBlocks = [];
|
||||
foreach (var b in resp.Content)
|
||||
{
|
||||
if (b.TryPickText(out var t)) paramBlocks.Add(new BetaTextBlockParam { Text = t.Text });
|
||||
else if (b.TryPickCompaction(out var c)) paramBlocks.Add(new BetaCompactionBlockParam { Content = c.Content });
|
||||
// ... other variants as needed
|
||||
}
|
||||
messages.Add(new BetaAssistantMessageParam { Content = paramBlocks });
|
||||
messages.Add(new BetaAssistantMessageParam { Content = resp.Content.Select(b => new BetaContentBlockParam(b.Json)).ToList() });
|
||||
```
|
||||
|
||||
All 15 `BetaContentBlock.TryPick*` variants: `Text`, `Thinking`, `RedactedThinking`, `ToolUse`, `ServerToolUse`, `WebSearchToolResult`, `WebFetchToolResult`, `CodeExecutionToolResult`, `BashCodeExecutionToolResult`, `TextEditorCodeExecutionToolResult`, `ToolSearchToolResult`, `McpToolUse`, `McpToolResult`, `ContainerUpload`, `Compaction`.
|
||||
All 18 `BetaContentBlock.TryPick*` variants: `Text`, `Thinking`, `RedactedThinking`, `ToolUse`, `ServerToolUse`, `WebSearchToolResult`, `WebFetchToolResult`, `AdvisorToolResult`, `CodeExecutionToolResult`, `BashCodeExecutionToolResult`, `TextEditorCodeExecutionToolResult`, `ToolSearchToolResult`, `McpToolUse`, `McpToolResult`, `McpToolListing`, `ContainerUpload`, `Compaction`, `Fallback`.
|
||||
|
||||
**`BetaToolUseBlock.Input` is `IReadOnlyDictionary<string, JsonElement>`** - index by key then call the `JsonElement` extractor:
|
||||
|
||||
@@ -352,7 +344,7 @@ if (response.StopReason == "refusal" && response.StopDetails is { } details)
|
||||
}
|
||||
```
|
||||
|
||||
**Refusal fallbacks (Claude Fable 5.2) - opt in by default.** Fallbacks are opt-in: without them a refused request simply stops. In `claude-fable-5-2` code, include `Fallbacks = new([new("claude-opus-4-8")])` plus the `AnthropicBeta.ServerSideFallback2026_07_01` beta (namespace `Anthropic.Models.Beta`) on the beta messages call by default - a policy decline is re-served by the fallback model inside the same call. Not available on Amazon Bedrock, Vertex AI, or Microsoft Foundry - use the client-side handler there: `new AnthropicClient { Handlers = [new BetaRefusalFallbackHandler { Fallbacks = [new("claude-opus-4-8")] }] }` (namespace `Anthropic.Helpers`), with per-conversation state via `BetaFallbackState.Create()` scoped with `using (fallbackState.Use()) { ... }`. Full semantics (billing, sticky routing, streaming) and a runnable example: `shared/model-migration.md` -> Migrating to Claude Fable 5.1 -> `refusal` stop reason, and the C# SDK repo's `examples/` (fetch it from `shared/live-sources.md`).
|
||||
**Refusal fallbacks - opt in by default.** Fallbacks are opt-in: without them a refused request simply stops. In `claude-fable-5-2`, `claude-fable-5-1`, `claude-opus-5-5`, `claude-opus-5`, and `claude-sonnet-5-5` code, include `Fallbacks = new Default()` (the API's `"default"` form) plus `Betas = ["server-side-fallback-2026-07-01"]` on the beta messages call by default - a decline in a category that has a recommended fallback is re-served by that model inside the same call; in other categories the refusal stands. The array form takes the same beta: `Fallbacks = new([new("claude-opus-4-8")])` (a bare `[...]` doesn't compile on the request); for `claude-sonnet-5-5` it may name only `claude-sonnet-5`. Both forms are documented only for the Claude API and Claude Models on Google Cloud (Anthropic managed). Elsewhere, set `Handlers` on the platform's client (shown here on `AnthropicClient`): `new AnthropicClient { Handlers = [new BetaRefusalFallbackHandler { Fallbacks = [new("claude-opus-4-8")] }] }` (namespace `Anthropic.Helpers`), with per-conversation state via `BetaFallbackState.Create()` scoped with `using (fallbackState.Use()) { ... }`. A `claude-sonnet-5-5` request that sends `between_tools` can't use the handler: see `shared/model-migration.md` -> Migrating to Claude Sonnet 5.5 -> Safeguards and fallback. Full semantics (billing, sticky routing, streaming) and a runnable example: `shared/model-migration.md` -> Migrating to Claude Fable 5.1 -> `refusal` stop reason, and the C# SDK repo's `examples/` (fetch it from `shared/live-sources.md`).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -3,12 +3,53 @@
|
||||
## Message Batches API
|
||||
|
||||
```csharp
|
||||
var batch = await client.Messages.Batches.Create(new() {
|
||||
Requests = [
|
||||
new() { CustomID = "req-1", Params = new() { Model = "claude-opus-5-5", MaxTokens = 1024, Messages = [...] } },
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Anthropic;
|
||||
using Anthropic.Models.Messages;
|
||||
using Anthropic.Models.Messages.Batches;
|
||||
|
||||
AnthropicClient client = new();
|
||||
|
||||
var batch = await client.Messages.Batches.Create(new BatchCreateParams
|
||||
{
|
||||
Requests =
|
||||
[
|
||||
new()
|
||||
{
|
||||
CustomID = "req-1",
|
||||
Params = new()
|
||||
{
|
||||
Model = "claude-opus-5-5",
|
||||
MaxTokens = 1024,
|
||||
Messages = [new UserMessageParam { Content = "Hello" }],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
// Poll client.Messages.Batches.Retrieve(batch.ID) until ProcessingStatus == "ended",
|
||||
// then iterate client.Messages.Batches.Results(batch.ID).
|
||||
|
||||
while (batch.ProcessingStatus != "ended")
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(60));
|
||||
batch = await client.Messages.Batches.Retrieve(batch.ID);
|
||||
}
|
||||
|
||||
// The results method is ResultsStreaming; there is no Results. Results can come in any order.
|
||||
await foreach (var item in client.Messages.Batches.ResultsStreaming(batch.ID))
|
||||
{
|
||||
if (item.Result.TryPickSucceeded(out var ok))
|
||||
{
|
||||
foreach (var text in ok.Message.Content.Select(b => b.Value).OfType<TextBlock>())
|
||||
{
|
||||
Console.WriteLine($"{item.CustomID}: {text.Text}");
|
||||
}
|
||||
}
|
||||
else if (item.Result.TryPickErrored(out var failed))
|
||||
{
|
||||
Console.WriteLine($"{item.CustomID}: {failed.Error.Error.Type.Raw()}");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`item.Result` also has `TryPickCanceled` and `TryPickExpired`.
|
||||
|
||||
205
skills/claude-api/csharp/claude-api/content-and-headers.md
Normal file
205
skills/claude-api/csharp/claude-api/content-and-headers.md
Normal file
@@ -0,0 +1,205 @@
|
||||
# Content Blocks and HTTP Details - C#
|
||||
|
||||
Each sample below is a complete `Program.cs`, except the search result snippet.
|
||||
|
||||
## Vision
|
||||
|
||||
`Content` takes a `List<ContentBlockParam>`; a bare `[...]` there is error CS9174. An image's `Source` is a `Base64ImageSource`, a `UrlImageSource`, or a `FileImageSource` (a Files API id).
|
||||
|
||||
```csharp
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Anthropic;
|
||||
using Anthropic.Models.Messages;
|
||||
|
||||
AnthropicClient client = new();
|
||||
|
||||
string imageData = Convert.ToBase64String(File.ReadAllBytes("chart.png"));
|
||||
|
||||
var response = await client.Messages.Create(new MessageCreateParams
|
||||
{
|
||||
Model = "claude-opus-5-5",
|
||||
MaxTokens = 1024,
|
||||
Messages =
|
||||
[
|
||||
new UserMessageParam
|
||||
{
|
||||
Content = new List<ContentBlockParam>
|
||||
{
|
||||
new ImageBlockParam { Source = new Base64ImageSource { Data = imageData, MediaType = MediaType.ImagePng } },
|
||||
new ImageBlockParam { Source = new UrlImageSource { Url = "https://example.com/chart.jpg" } },
|
||||
new TextBlockParam { Text = "What is in these images?" },
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
foreach (var text in response.Content.Select(b => b.Value).OfType<TextBlock>())
|
||||
{
|
||||
Console.WriteLine(text.Text);
|
||||
}
|
||||
```
|
||||
|
||||
## Citations
|
||||
|
||||
Turn citations on per document with `Citations = new CitationsConfigParam { Enabled = true }`. `TextBlock.Citations` is null when a block cites nothing. Each entry is a `TextCitation` union: switch on `.Value`, or call `TryPickCitationCharLocation`, `TryPickCitationPageLocation`, `TryPickCitationContentBlockLocation`, `TryPickCitationsSearchResultLocation`, or `TryPickCitationsWebSearchResultLocation`. The last two have `Citations` in the plural.
|
||||
|
||||
```csharp
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Anthropic;
|
||||
using Anthropic.Models.Messages;
|
||||
|
||||
AnthropicClient client = new();
|
||||
|
||||
var response = await client.Messages.Create(new MessageCreateParams
|
||||
{
|
||||
Model = "claude-opus-5-5",
|
||||
MaxTokens = 1024,
|
||||
Messages =
|
||||
[
|
||||
new UserMessageParam
|
||||
{
|
||||
Content = new List<ContentBlockParam>
|
||||
{
|
||||
new DocumentBlockParam
|
||||
{
|
||||
Source = new PlainTextSource("The grass is green. The sky is blue."),
|
||||
Title = "My Document",
|
||||
Citations = new CitationsConfigParam { Enabled = true },
|
||||
},
|
||||
new TextBlockParam { Text = "What color is the grass?" },
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
foreach (var block in response.Content)
|
||||
{
|
||||
if (!block.TryPickText(out var text)) continue;
|
||||
Console.WriteLine(text.Text);
|
||||
|
||||
foreach (var citation in text.Citations ?? [])
|
||||
{
|
||||
switch (citation.Value)
|
||||
{
|
||||
case CitationCharLocation c: // plain text documents
|
||||
Console.WriteLine($"{c.CitedText} (chars {c.StartCharIndex}-{c.EndCharIndex})");
|
||||
break;
|
||||
case CitationPageLocation p: // PDFs
|
||||
Console.WriteLine($"{p.CitedText} (pages {p.StartPageNumber}-{p.EndPageNumber})");
|
||||
break;
|
||||
case CitationContentBlockLocation b: // custom content documents
|
||||
Console.WriteLine($"{b.CitedText} (blocks {b.StartBlockIndex}-{b.EndBlockIndex})");
|
||||
break;
|
||||
case CitationsSearchResultLocation s: // search_result blocks
|
||||
Console.WriteLine($"{s.CitedText} ({s.Source})");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
A search result goes in the same `List<ContentBlockParam>`:
|
||||
|
||||
```csharp
|
||||
new SearchResultBlockParam
|
||||
{
|
||||
Source = "https://docs.example.com/api",
|
||||
Title = "API Reference",
|
||||
Content = [new() { Text = "Rate limit: 1000 requests per hour." }],
|
||||
Citations = new() { Enabled = true },
|
||||
},
|
||||
```
|
||||
|
||||
## Mid-conversation system messages
|
||||
|
||||
Add a `SystemMessageParam` to `Messages` right after a user message, as the last entry or followed by an assistant turn, and leave `System` as it was. The beta path uses `BetaSystemMessageParam`.
|
||||
|
||||
```csharp
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Anthropic;
|
||||
using Anthropic.Models.Messages;
|
||||
|
||||
AnthropicClient client = new();
|
||||
|
||||
List<MessageParam> messages = [new UserMessageParam { Content = "Review process() in utils.py." }];
|
||||
var first = await client.Messages.Create(new MessageCreateParams
|
||||
{
|
||||
Model = "claude-opus-5-5", MaxTokens = 1024, System = "You are a code reviewer.", Messages = messages,
|
||||
});
|
||||
|
||||
messages.Add(new AssistantMessageParam { Content = first.Content.Select(b => new ContentBlockParam(b.Json)).ToList() });
|
||||
messages.Add(new UserMessageParam { Content = "Now review the calling code." });
|
||||
messages.Add(new SystemMessageParam { Content = "From now on, include type annotations." });
|
||||
|
||||
var second = await client.Messages.Create(new MessageCreateParams
|
||||
{
|
||||
Model = "claude-opus-5-5", MaxTokens = 1024, System = "You are a code reviewer.", Messages = messages,
|
||||
});
|
||||
Console.WriteLine(second.ID);
|
||||
```
|
||||
|
||||
## Request headers
|
||||
|
||||
`ClientOptions.ExtraHeaders` sends a header on every request, and `WithOptions` does the same on a copy of the client. `new AnthropicClient { ExtraHeaders = ... }` doesn't compile. With an API key, setting `ANTHROPIC_WORKSPACE_ID` sends no header.
|
||||
|
||||
```csharp
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Anthropic;
|
||||
using Anthropic.Core;
|
||||
using Anthropic.Models.Messages;
|
||||
|
||||
// Every request from this client:
|
||||
AnthropicClient client = new(new ClientOptions
|
||||
{
|
||||
ExtraHeaders = new Dictionary<string, string> { ["anthropic-workspace-id"] = "wrkspc_..." },
|
||||
});
|
||||
|
||||
// A copy with other headers; the original client is unchanged:
|
||||
var otherWorkspace = client.WithOptions(options => options with
|
||||
{
|
||||
ExtraHeaders = new Dictionary<string, string> { ["anthropic-workspace-id"] = "wrkspc_other" },
|
||||
});
|
||||
|
||||
var message = await otherWorkspace.Messages.Create(new MessageCreateParams
|
||||
{
|
||||
Model = "claude-opus-5-5",
|
||||
MaxTokens = 1024,
|
||||
Messages = [new UserMessageParam { Content = "Hello" }],
|
||||
});
|
||||
Console.WriteLine(message.ID);
|
||||
```
|
||||
|
||||
## Response headers
|
||||
|
||||
Put `WithRawResponse` after the client to get the HTTP response, then `Deserialize()` for the usual object. Rate limit headers are named `anthropic-ratelimit-*`, and the request id is on `RequestID`.
|
||||
|
||||
```csharp
|
||||
using System;
|
||||
using Anthropic;
|
||||
using Anthropic.Models.Messages;
|
||||
|
||||
AnthropicClient client = new();
|
||||
|
||||
using var response = await client.WithRawResponse.Messages.Create(new MessageCreateParams
|
||||
{
|
||||
Model = "claude-opus-5-5",
|
||||
MaxTokens = 1024,
|
||||
Messages = [new UserMessageParam { Content = "Hello" }],
|
||||
});
|
||||
|
||||
if (response.TryGetHeaderValues("anthropic-ratelimit-requests-remaining", out var values))
|
||||
{
|
||||
Console.WriteLine(string.Join(", ", values));
|
||||
}
|
||||
Console.WriteLine(response.RequestID);
|
||||
|
||||
Message message = await response.Deserialize();
|
||||
Console.WriteLine(message.ID);
|
||||
```
|
||||
@@ -2,24 +2,90 @@
|
||||
|
||||
## Files API
|
||||
|
||||
> **Out of beta.** In current SDKs `client.Beta.Files` has breaking shape changes from previous versions, matching the stable `client.Files` - migrate per the Files API row in `shared/live-sources.md`. Examples below predate this.
|
||||
> **Out of beta.** Use `client.Files` with no beta header. In current SDKs `client.Beta.Files` has breaking shape changes from previous versions, matching the stable `client.Files` - migrate per the Files API row in `shared/live-sources.md`.
|
||||
|
||||
Files live under `client.Beta.Files` (namespace `Anthropic.Models.Beta.Files`). `BinaryContent` implicit-converts from `Stream` and `byte[]`.
|
||||
Files live under `client.Files` (namespace `Anthropic.Models.Files`). `BinaryContent` implicit-converts from `Stream` and `byte[]`; build one yourself, as below, to set the file name and content type.
|
||||
|
||||
```csharp
|
||||
using Anthropic.Models.Beta.Files;
|
||||
using Anthropic.Models.Beta.Messages;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using Anthropic;
|
||||
using Anthropic.Core;
|
||||
using Anthropic.Models.Files;
|
||||
using Anthropic.Models.Messages;
|
||||
|
||||
FileMetadata meta = await client.Beta.Files.Upload(
|
||||
new FileUploadParams { File = File.OpenRead("doc.pdf") });
|
||||
AnthropicClient client = new();
|
||||
|
||||
// Referencing the uploaded file requires Beta message types:
|
||||
new BetaRequestDocumentBlock {
|
||||
Source = new BetaFileDocumentSource { FileID = meta.ID },
|
||||
}
|
||||
FileMetadata meta = await client.Files.Upload(new FileUploadParams
|
||||
{
|
||||
File = new BinaryContent
|
||||
{
|
||||
Stream = File.OpenRead("doc.pdf"),
|
||||
FileName = "doc.pdf",
|
||||
ContentType = new("application/pdf"),
|
||||
},
|
||||
});
|
||||
|
||||
var message = await client.Messages.Create(new MessageCreateParams
|
||||
{
|
||||
Model = "claude-opus-5-5",
|
||||
MaxTokens = 1024,
|
||||
Messages =
|
||||
[
|
||||
new UserMessageParam
|
||||
{
|
||||
Content = new List<ContentBlockParam>
|
||||
{
|
||||
new DocumentBlockParam { Source = new FileDocumentSource { FileID = meta.ID } },
|
||||
new TextBlockParam { Text = "Summarize this document." },
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
Console.WriteLine(message.ID);
|
||||
```
|
||||
|
||||
The non-beta `DocumentBlockParamSource` union has no file-ID variant - file references need `client.Beta.Messages.Create()`.
|
||||
`Download` returns an `HttpResponse`: read it with `ReadAsStream()` or `ReadAsString()`.
|
||||
|
||||
```csharp
|
||||
using System.IO;
|
||||
using Anthropic;
|
||||
|
||||
AnthropicClient client = new();
|
||||
|
||||
using var download = await client.Files.Download("file_011CNha8iCJcU1wXNR6q4V8w");
|
||||
await using Stream body = await download.ReadAsStream();
|
||||
await using FileStream target = File.Create("output.csv");
|
||||
await body.CopyToAsync(target);
|
||||
```
|
||||
|
||||
### Set an expiry
|
||||
|
||||
`ExpiresInSeconds` sets when a file expires: a whole number of seconds from 3,600 (1 hour) to 7,776,000 (90 days), counted from the upload. It can't be changed later.
|
||||
|
||||
```csharp
|
||||
using System;
|
||||
using System.IO;
|
||||
using Anthropic;
|
||||
using Anthropic.Core;
|
||||
using Anthropic.Models.Files;
|
||||
|
||||
AnthropicClient client = new();
|
||||
|
||||
FileMetadata temporary = await client.Files.Upload(new FileUploadParams
|
||||
{
|
||||
File = new BinaryContent
|
||||
{
|
||||
Stream = File.OpenRead("doc.pdf"),
|
||||
FileName = "doc.pdf",
|
||||
ContentType = new("application/pdf"),
|
||||
},
|
||||
ExpiresInSeconds = 86400,
|
||||
});
|
||||
Console.WriteLine($"{temporary.ID} {temporary.ExpiresAt}");
|
||||
```
|
||||
|
||||
`ExpiresAt` is `null` for a file with no expiry. Use `client.Files` with no beta header, as here: requests that send `files-api-2025-04-14` don't get this field back. A message that references an expired file fails. Expiry isn't a guaranteed-deletion control: before relying on it for data handling, read File expiration in `https://platform.claude.com/docs/en/build-with-claude/files.md`.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -51,10 +51,19 @@ var parameters = new MessageCreateParams
|
||||
|
||||
Derived from `anthropic-sdk-csharp/src/Anthropic/Models/Messages/Tool.cs` and `ToolUnion.cs:799` (implicit conversion).
|
||||
|
||||
`InputExamples` takes example inputs as dictionaries, on the non-beta `Tool` with no beta header:
|
||||
|
||||
```csharp
|
||||
InputExamples =
|
||||
[
|
||||
new Dictionary<string, JsonElement> { ["location"] = JsonSerializer.SerializeToElement("Paris") },
|
||||
],
|
||||
```
|
||||
|
||||
See [shared tool use concepts](../../shared/tool-use-concepts.md) for the loop pattern.
|
||||
### Converting response content to the follow-up assistant message
|
||||
|
||||
When echoing Claude's response back in the assistant turn, **there is no `.ToParam()` helper** - manually reconstruct each `ContentBlock` variant as its `*Param` counterpart. Do NOT use `new ContentBlockParam(block.Json)`: it compiles and serializes, but `.Value` stays `null` so `TryPick*`/`Validate()` fail (degraded JSON pass-through, not the typed path).
|
||||
When echoing Claude's response back in the assistant turn, **there is no `.ToParam()` helper**. To send a block back unchanged, wrap its JSON: `new ContentBlockParam(block.Json)`. The wrapped param's `.Value` is `null`, so `TryPick*` returns false and `Validate()` throws on it. To change a block before sending it, or to read the param later with `TryPick*`, rebuild it as its `*Param` counterpart, as below.
|
||||
|
||||
```csharp
|
||||
using Anthropic.Models.Messages;
|
||||
@@ -86,12 +95,13 @@ foreach (ContentBlock block in response.Content)
|
||||
}
|
||||
else if (block.TryPickToolUse(out ToolUseBlock? toolUse))
|
||||
{
|
||||
// ToolUseBlock has required Caller; ToolUseBlockParam.Caller is optional - don't copy it
|
||||
assistantContent.Add(new ToolUseBlockParam
|
||||
{
|
||||
ID = toolUse.ID,
|
||||
Name = toolUse.Name,
|
||||
Input = toolUse.Input,
|
||||
// Caller has a different type on the param. A programmatic call must send it back.
|
||||
Caller = new ToolUseBlockParamCaller(toolUse.Caller.Json),
|
||||
});
|
||||
// Execute the tool; collect ONE result per tool_use block - the API
|
||||
// rejects the follow-up if any tool_use ID lacks a matching tool_result.
|
||||
@@ -142,27 +152,236 @@ Web search, bash, text editor, and code execution are Anthropic-defined tools wi
|
||||
|
||||
```csharp
|
||||
Tools = [
|
||||
new ToolUnion(new WebSearchTool20260209()),
|
||||
new ToolUnion(new WebSearchTool20260318()),
|
||||
new ToolUnion(new ToolBash20250124()),
|
||||
new ToolUnion(new ToolTextEditor20250728()),
|
||||
new ToolUnion(new CodeExecutionTool20260120()),
|
||||
],
|
||||
```
|
||||
|
||||
Also available: `new ToolUnion(new WebFetchTool20260209())`, `new ToolUnion(new MemoryTool20250818())`. `WebSearchTool20260209` optionals: `AllowedDomains`, `BlockedDomains`, `MaxUses`, `UserLocation`.
|
||||
Also available: `new ToolUnion(new WebFetchTool20260318())` (see Web fetch below), `new ToolUnion(new MemoryTool20250818())`. `WebSearchTool20260318` optionals: `AllowedDomains`, `BlockedDomains`, `MaxUses`, `UserLocation`, `ResponseInclusion`.
|
||||
|
||||
### Reading code execution results
|
||||
|
||||
Each result's `Content` is a union, so `.Content.Stdout` doesn't compile. Narrow it first. Bash and file operations return `bash_code_execution_tool_result` and `text_editor_code_execution_tool_result` blocks. Code that runs through programmatic tool calling returns `code_execution_tool_result`.
|
||||
|
||||
```csharp
|
||||
using System;
|
||||
using Anthropic;
|
||||
using Anthropic.Models.Messages;
|
||||
|
||||
AnthropicClient client = new();
|
||||
|
||||
var message = await client.Messages.Create(new MessageCreateParams
|
||||
{
|
||||
Model = "claude-opus-5-5",
|
||||
MaxTokens = 4096,
|
||||
Messages = [new UserMessageParam { Content = "Use Python to add the numbers from 1 to 100." }],
|
||||
Tools = [new ToolUnion(new CodeExecutionTool20260120())],
|
||||
});
|
||||
|
||||
foreach (var block in message.Content)
|
||||
{
|
||||
if (block.TryPickBashCodeExecutionToolResult(out var bash))
|
||||
{
|
||||
if (bash.Content.TryPickBashCodeExecutionResultBlock(out var run))
|
||||
{
|
||||
Console.WriteLine($"exit {run.ReturnCode}: {run.Stdout}{run.Stderr}");
|
||||
foreach (var output in run.Content)
|
||||
{
|
||||
Console.WriteLine(output.FileID); // download with client.Files.Download
|
||||
}
|
||||
}
|
||||
else if (bash.Content.TryPickBashCodeExecutionToolResultError(out var error))
|
||||
{
|
||||
Console.WriteLine(error.ErrorCode.Raw());
|
||||
}
|
||||
}
|
||||
else if (block.TryPickCodeExecutionToolResult(out var code) && code.Content.TryPickResultBlock(out var result))
|
||||
{
|
||||
Console.WriteLine(result.Stdout);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Web fetch
|
||||
|
||||
`UseCache = false` fetches fresh content. It needs `WebFetchTool20260309` or later.
|
||||
|
||||
```csharp
|
||||
using System;
|
||||
using Anthropic;
|
||||
using Anthropic.Models.Messages;
|
||||
|
||||
AnthropicClient client = new();
|
||||
|
||||
var message = await client.Messages.Create(new MessageCreateParams
|
||||
{
|
||||
Model = "claude-opus-5-5",
|
||||
MaxTokens = 1024,
|
||||
Messages = [new UserMessageParam { Content = "Summarize https://example.com" }],
|
||||
Tools = [new ToolUnion(new WebFetchTool20260318 { UseCache = false })],
|
||||
});
|
||||
|
||||
foreach (var block in message.Content)
|
||||
{
|
||||
if (block.TryPickWebFetchToolResult(out var fetch) && fetch.Content.TryPickWebFetchBlock(out var page))
|
||||
{
|
||||
Console.WriteLine(page.Url);
|
||||
}
|
||||
else if (block.TryPickText(out var text))
|
||||
{
|
||||
Console.WriteLine(text.Text);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Programmatic tool calling
|
||||
|
||||
`AllowedCallers` makes a tool callable from code execution. When the code pauses on your tool, send the whole assistant turn back as it came, because its `server_tool_use` block and each `tool_use` block's `caller` must be returned. Pass the container id back too (assign the id string to `Container`, as below). The same loop continues a `pause_turn`.
|
||||
|
||||
```csharp
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using Anthropic;
|
||||
using Anthropic.Models.Messages;
|
||||
|
||||
AnthropicClient client = new();
|
||||
|
||||
List<ToolUnion> tools =
|
||||
[
|
||||
new ToolUnion(new CodeExecutionTool20260120()),
|
||||
new ToolUnion(new Tool
|
||||
{
|
||||
Name = "lookup_order",
|
||||
Description = "Look up an order by id. Returns it as JSON.",
|
||||
InputSchema = new()
|
||||
{
|
||||
Properties = new Dictionary<string, JsonElement>
|
||||
{
|
||||
["order_id"] = JsonSerializer.SerializeToElement(new { type = "string" }),
|
||||
},
|
||||
Required = ["order_id"],
|
||||
},
|
||||
AllowedCallers = [ToolAllowedCaller.CodeExecution20260120],
|
||||
}),
|
||||
];
|
||||
|
||||
List<MessageParam> messages = [new UserMessageParam { Content = "Which of orders A-1 and A-2 shipped first?" }];
|
||||
MessageCreateParamsContainer? container = null;
|
||||
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
Message response = await client.Messages.Create(new MessageCreateParams
|
||||
{
|
||||
Model = "claude-opus-5-5",
|
||||
MaxTokens = 4096,
|
||||
Messages = messages,
|
||||
Tools = tools,
|
||||
Container = container,
|
||||
});
|
||||
if (response.Container is { } live)
|
||||
{
|
||||
container = live.ID;
|
||||
}
|
||||
|
||||
List<ToolUseBlock> toolUses = [];
|
||||
foreach (ContentBlock block in response.Content)
|
||||
{
|
||||
if (block.TryPickToolUse(out ToolUseBlock? use))
|
||||
{
|
||||
toolUses.Add(use);
|
||||
}
|
||||
else if (block.TryPickText(out TextBlock? text))
|
||||
{
|
||||
Console.WriteLine(text.Text);
|
||||
}
|
||||
}
|
||||
|
||||
StopReason? stop = response.StopReason?.Value();
|
||||
AssistantMessageParam assistantTurn = new() { Content = response.Content.Select(b => new ContentBlockParam(b.Json)).ToList() };
|
||||
|
||||
// Server-side tool hit iteration limit; append the paused turn and re-send to continue
|
||||
if (stop == StopReason.PauseTurn)
|
||||
{
|
||||
messages.Add(assistantTurn);
|
||||
continue;
|
||||
}
|
||||
|
||||
// A tool input cut off at max_tokens can still parse as a valid object; don't run it
|
||||
if (stop == StopReason.MaxTokens && toolUses.Count > 0)
|
||||
{
|
||||
throw new InvalidOperationException("tool input truncated; retry with a higher MaxTokens");
|
||||
}
|
||||
|
||||
// Done: end_turn, another stop that can cut a tool call off, or (rarely) a tool_use stop with no tool call
|
||||
if (stop != StopReason.ToolUse || toolUses.Count == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
List<ContentBlockParam> results = [];
|
||||
foreach (ToolUseBlock use in toolUses)
|
||||
{
|
||||
results.Add(new ToolResultBlockParam { ToolUseID = use.ID, Content = "{\"status\": \"shipped\"}" });
|
||||
}
|
||||
|
||||
messages.Add(assistantTurn);
|
||||
messages.Add(new UserMessageParam { Content = results });
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Tool Runner (Beta)
|
||||
|
||||
The C# SDK provides a `BetaToolRunner` for automatic tool execution loops. Define tools with raw JSON schemas, and the runner handles the API call -> tool execution -> result feedback loop.
|
||||
The C# SDK provides a `BetaToolRunner` for automatic tool execution loops. Define each tool as a `BetaRunnableTool` with a raw JSON schema and a `Run` function, and the runner handles the API call -> tool execution -> result feedback loop.
|
||||
|
||||
```csharp
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
using Anthropic;
|
||||
using Anthropic.Helpers.Beta;
|
||||
using Anthropic.Models.Beta.Messages;
|
||||
|
||||
// Define tools and create params as shown in the Tool Use section above,
|
||||
// but using the beta namespace types (BetaToolUnion, etc.)
|
||||
var runner = client.Beta.Messages.ToolRunner(betaParams);
|
||||
AnthropicClient client = new();
|
||||
var weatherTool = new BetaRunnableTool
|
||||
{
|
||||
Name = "get_weather",
|
||||
Definition = new BetaTool
|
||||
{
|
||||
Name = "get_weather",
|
||||
Description = "Get the current weather in a given location",
|
||||
InputSchema = new InputSchema
|
||||
{
|
||||
Properties = new Dictionary<string, JsonElement>
|
||||
{
|
||||
["location"] = JsonSerializer.SerializeToElement(
|
||||
new { type = "string", description = "City name" }),
|
||||
},
|
||||
Required = ["location"],
|
||||
},
|
||||
},
|
||||
Run = (toolUse, _) =>
|
||||
{
|
||||
var location = toolUse.Input["location"].GetString();
|
||||
return Task.FromResult<BetaToolResultBlockParamContent>($"Clear skies in {location}");
|
||||
},
|
||||
};
|
||||
|
||||
var betaParams = new MessageCreateParams
|
||||
{
|
||||
Model = "claude-opus-5-5",
|
||||
MaxTokens = 16000,
|
||||
Messages = [new BetaUserMessageParam { Content = "Is it raining in Tokyo?" }],
|
||||
};
|
||||
|
||||
// Runnable tools go here, not in betaParams.Tools: the runner sends each one's Definition itself.
|
||||
var runner = client.Beta.Messages.ToolRunner(betaParams, [weatherTool]);
|
||||
|
||||
await foreach (BetaMessage message in runner)
|
||||
{
|
||||
@@ -176,5 +395,63 @@ await foreach (BetaMessage message in runner)
|
||||
}
|
||||
```
|
||||
|
||||
### Approval gates
|
||||
|
||||
For human approval, use a manual loop (`shared/tool-use-concepts.md` -> Manual Agentic Loop). To do it in the runner instead, put the gate inside `Run`. The runner calls `Run` after your `await foreach` body, even when that body called `PushMessages` or `SetParams`, so pushing a denial from the loop doesn't stop the tool. Return a "user declined" result from `Run` instead of executing. A `BetaToolError` thrown in `Run` also goes back to Claude, as a `tool_result` with `is_error: true`. `maxIterations` caps the API calls.
|
||||
|
||||
```csharp
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
using Anthropic;
|
||||
using Anthropic.Helpers.Beta;
|
||||
using Anthropic.Models.Beta.Messages;
|
||||
|
||||
AnthropicClient client = new();
|
||||
|
||||
var sendEmail = new BetaRunnableTool
|
||||
{
|
||||
Name = "send_email",
|
||||
Definition = new BetaTool
|
||||
{
|
||||
Name = "send_email",
|
||||
Description = "Send an email.",
|
||||
InputSchema = new InputSchema
|
||||
{
|
||||
Properties = new Dictionary<string, JsonElement>
|
||||
{
|
||||
["to"] = JsonSerializer.SerializeToElement(new { type = "string" }),
|
||||
},
|
||||
Required = ["to"],
|
||||
},
|
||||
},
|
||||
Run = (toolUse, _) =>
|
||||
{
|
||||
string to = toolUse.Input["to"].GetString()!;
|
||||
Console.Write($"Send an email to {to}? [y/N] ");
|
||||
if (Console.ReadLine()?.Trim() != "y")
|
||||
{
|
||||
return Task.FromResult<BetaToolResultBlockParamContent>("user declined");
|
||||
}
|
||||
// ... send the email here ...
|
||||
return Task.FromResult<BetaToolResultBlockParamContent>($"Sent to {to}");
|
||||
},
|
||||
};
|
||||
|
||||
var runner = client.Beta.Messages.ToolRunner(
|
||||
new MessageCreateParams
|
||||
{
|
||||
Model = "claude-opus-5-5",
|
||||
MaxTokens = 1024,
|
||||
Messages = [new BetaUserMessageParam { Content = "Email sam@example.com the meeting notes." }],
|
||||
},
|
||||
[sendEmail],
|
||||
maxIterations: 10);
|
||||
|
||||
BetaMessage final = await runner.RunUntilDoneAsync();
|
||||
Console.WriteLine(final.StopReason?.Raw());
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -243,7 +243,7 @@ if [ "$(echo "$response" | jq -r '.stop_reason')" != "refusal" ] && \
|
||||
fi
|
||||
```
|
||||
|
||||
This array form takes `server-side-fallback-2026-06-01` or `-2026-07-01`; the `fallbacks: "default"` scalar form needs `-2026-07-01` (see `shared/model-migration.md` -> Migrating to Claude Opus 5 -> New API features). Any other `server-side-fallback-*` value returns a 400. The parameter is rejected on the Batches API and unavailable on Amazon Bedrock, Vertex AI, and Microsoft Foundry. Full semantics (sticky routing, billing, streaming, echoing fallback turns back): `shared/model-migration.md` -> Migrating to Claude Fable 5.1 -> `refusal` stop reason.
|
||||
This array form takes `server-side-fallback-2026-06-01` or `-2026-07-01`; the `fallbacks: "default"` scalar form needs `-2026-07-01` (see `shared/model-migration.md` -> Migrating to Claude Opus 5 -> New API features). Any other `server-side-fallback-*` value returns a 400. The Batches API rejects the parameter. It is unavailable on Amazon Bedrock, Vertex AI and Microsoft Foundry, and the docs don't list it for Claude Platform on AWS. Full semantics (sticky routing, billing, streaming, echoing fallback turns back): `shared/model-migration.md` -> Migrating to Claude Fable 5.1 -> `refusal` stop reason.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
go get github.com/anthropics/anthropic-sdk-go/v2
|
||||
```
|
||||
|
||||
Other task pages: `batches.md` has message batches. `tool-use.md` has code execution results and generated files, Agent Skills, container reuse, programmatic tool calling, input examples and the MCP connector.
|
||||
|
||||
## Client Initialization
|
||||
|
||||
```go
|
||||
@@ -23,6 +25,9 @@ client := anthropic.NewClient()
|
||||
client := anthropic.NewClient(
|
||||
option.WithAPIKey("your-api-key"),
|
||||
)
|
||||
|
||||
// Key not scoped to one workspace
|
||||
client := anthropic.NewClient(option.WithHeader("anthropic-workspace-id", "wrkspc_..."))
|
||||
```
|
||||
|
||||
---
|
||||
@@ -120,6 +125,13 @@ For 1-hour TTL: `anthropic.CacheControlEphemeralParam{TTL: anthropic.CacheContro
|
||||
|
||||
Verify hits via `resp.Usage.CacheCreationInputTokens` / `resp.Usage.CacheReadInputTokens`.
|
||||
|
||||
**Cache diagnostics:** send `Diagnostics` on every turn. `DiagnosticsParam{}` sends nothing, so the first turn needs an explicit null:
|
||||
|
||||
```go
|
||||
Diagnostics: anthropic.DiagnosticsParam{PreviousMessageID: param.Null[string]()}, // first turn; param is .../v2/packages/param
|
||||
Diagnostics: anthropic.DiagnosticsParam{PreviousMessageID: anthropic.String(previous.ID)}, // later turns
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Stop Details
|
||||
@@ -133,7 +145,7 @@ if resp.StopReason == anthropic.StopReasonRefusal {
|
||||
}
|
||||
```
|
||||
|
||||
**Refusal fallbacks (Claude Fable 5.2) - opt in by default.** Fallbacks are opt-in: without them a refused request simply stops. In `claude-fable-5-2` code, include `Fallbacks: anthropic.BetaFallbacksParamUnion{OfBetaFallbackArray: []anthropic.BetaFallbackParam{{Model: anthropic.ModelClaudeOpus4_8}}}` plus the `anthropic.AnthropicBetaServerSideFallback2026_07_01` beta on `client.Beta.Messages.New` by default - a policy decline is re-served by the fallback model inside the same call. Not available on Amazon Bedrock, Vertex AI, or Microsoft Foundry - register the client-side middleware there: `option.WithMiddleware(betafallback.BetaRefusalFallbackMiddleware(...))` from `lib/betafallback`, with per-conversation state via `betafallback.WithBetaFallbackState(&betafallback.BetaFallbackState{})`. Full semantics (billing, sticky routing, streaming) and a runnable example: `shared/model-migration.md` -> Migrating to Claude Fable 5.1 -> `refusal` stop reason, and the Go SDK repo's `examples/` (fetch it from `shared/live-sources.md`).
|
||||
**Refusal fallbacks (Claude Fable 5.2) - opt in by default.** Fallbacks are opt-in: without them a refused request simply stops. In `claude-fable-5-2` code, include `Fallbacks: anthropic.BetaFallbacksParamUnion{OfBetaFallbackArray: []anthropic.BetaFallbackParam{{Model: anthropic.ModelClaudeOpus4_8}}}` plus the `anthropic.AnthropicBetaServerSideFallback2026_07_01` beta on `client.Beta.Messages.New` by default - a policy decline is re-served by the fallback model inside the same call. Documented only for the Claude API and Claude Models on Google Cloud (Anthropic managed). Elsewhere, register the client-side middleware: `option.WithMiddleware(betafallback.BetaRefusalFallbackMiddleware(...))` from `lib/betafallback`, with per-conversation state via `betafallback.WithBetaFallbackState(&betafallback.BetaFallbackState{})`. Full semantics (billing, sticky routing, streaming) and a runnable example: `shared/model-migration.md` -> Migrating to Claude Fable 5.1 -> `refusal` stop reason, and the Go SDK repo's `examples/` (fetch it from `shared/live-sources.md`).
|
||||
|
||||
---
|
||||
|
||||
@@ -188,3 +200,35 @@ for _, block := range resp.Content {
|
||||
```
|
||||
|
||||
Other edit types: `BetaClearToolUses20250919EditParam`, `BetaClearThinking20251015EditParam` - these need `Betas: []anthropic.AnthropicBeta{"context-management-2025-06-27"}`, not `compact-2026-01-12`.
|
||||
|
||||
**Clearing old tool results** (beta `anthropic.AnthropicBetaContextManagement2025_06_27`). `Keep` and `ClearAtLeast` are plain structs; `Trigger` is a union:
|
||||
|
||||
```go
|
||||
ContextManagement: anthropic.BetaContextManagementConfigParam{
|
||||
Edits: []anthropic.BetaContextManagementConfigEditUnionParam{
|
||||
{OfClearToolUses20250919: &anthropic.BetaClearToolUses20250919EditParam{
|
||||
Trigger: anthropic.BetaClearToolUses20250919EditTriggerUnionParam{OfInputTokens: &anthropic.BetaInputTokensTriggerParam{Value: 30000}},
|
||||
Keep: anthropic.BetaToolUsesKeepParam{Value: 3},
|
||||
ClearAtLeast: anthropic.BetaInputTokensClearAtLeastParam{Value: 5000},
|
||||
}},
|
||||
},
|
||||
},
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Search Results (RAG with Citations)
|
||||
|
||||
Pass your own retrieved text as `search_result` blocks, in a user message or inside a tool result. Cited text comes back on each `TextBlock`'s `Citations`.
|
||||
|
||||
```go
|
||||
anthropic.NewUserMessage(
|
||||
anthropic.ContentBlockParamUnion{OfSearchResult: &anthropic.SearchResultBlockParam{
|
||||
Source: "https://docs.example.com/auth",
|
||||
Title: "Authentication",
|
||||
Content: []anthropic.TextBlockParam{{Text: "Send the API key in the Authorization header."}},
|
||||
Citations: anthropic.CitationsConfigParam{Enabled: anthropic.Bool(true)},
|
||||
}},
|
||||
anthropic.NewTextBlock("How do I authenticate?"),
|
||||
)
|
||||
```
|
||||
|
||||
113
skills/claude-api/go/claude-api/batches.md
Normal file
113
skills/claude-api/go/claude-api/batches.md
Normal file
@@ -0,0 +1,113 @@
|
||||
# Message Batches API - Go
|
||||
|
||||
The Batches API (`POST /v1/messages/batches`) processes Messages API requests asynchronously at 50% of standard prices.
|
||||
|
||||
## Key Facts
|
||||
|
||||
- Up to 100,000 requests or 256 MB per batch
|
||||
- Most batches complete within 1 hour; maximum 24 hours
|
||||
- Results available for 29 days after creation
|
||||
- Most Messages API features work (vision, tools, caching, etc.); a batch request can't set `stream`, `speed`, `fallbacks` or `max_tokens: 0`
|
||||
- Every service method takes a params struct after the batch ID, even when it is empty: `Get(ctx, id, anthropic.MessageBatchGetParams{})`
|
||||
- Results arrive in any order: key by `CustomID`, never by position
|
||||
|
||||
---
|
||||
|
||||
## Create a Batch
|
||||
|
||||
Each request's `Params` is a `MessageBatchNewParamsRequestParams`, not a `MessageNewParams`; most of its fields are the same.
|
||||
|
||||
```go
|
||||
batch, err := client.Messages.Batches.New(ctx, anthropic.MessageBatchNewParams{
|
||||
Requests: []anthropic.MessageBatchNewParamsRequest{
|
||||
{
|
||||
CustomID: "request-1",
|
||||
Params: anthropic.MessageBatchNewParamsRequestParams{
|
||||
Model: "claude-opus-5-5",
|
||||
MaxTokens: 16000,
|
||||
Messages: []anthropic.MessageParam{
|
||||
anthropic.NewUserMessage(anthropic.NewTextBlock("Summarize climate change impacts")),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
fmt.Println(batch.ID, batch.ProcessingStatus)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Poll for Completion
|
||||
|
||||
```go
|
||||
for {
|
||||
batch, err = client.Messages.Batches.Get(ctx, batch.ID, anthropic.MessageBatchGetParams{})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if batch.ProcessingStatus == anthropic.MessageBatchProcessingStatusEnded {
|
||||
break
|
||||
}
|
||||
fmt.Println("processing:", batch.RequestCounts.Processing)
|
||||
time.Sleep(60 * time.Second)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Retrieve Results
|
||||
|
||||
```go
|
||||
stream := client.Messages.Batches.ResultsStreaming(ctx, batch.ID, anthropic.MessageBatchResultsParams{})
|
||||
defer stream.Close()
|
||||
for stream.Next() {
|
||||
result := stream.Current()
|
||||
switch r := result.Result.AsAny().(type) {
|
||||
case anthropic.MessageBatchSucceededResult:
|
||||
for _, block := range r.Message.Content {
|
||||
if text, ok := block.AsAny().(anthropic.TextBlock); ok {
|
||||
fmt.Printf("[%s] %s\n", result.CustomID, text.Text)
|
||||
}
|
||||
}
|
||||
case anthropic.MessageBatchErroredResult:
|
||||
// r.Error.Error is the API error; "invalid_request_error" means fix the request before resubmitting.
|
||||
fmt.Printf("[%s] %s: %s\n", result.CustomID, r.Error.Error.Type, r.Error.Error.Message)
|
||||
case anthropic.MessageBatchCanceledResult:
|
||||
fmt.Printf("[%s] canceled\n", result.CustomID)
|
||||
case anthropic.MessageBatchExpiredResult:
|
||||
fmt.Printf("[%s] expired - resubmit\n", result.CustomID)
|
||||
}
|
||||
}
|
||||
if err := stream.Err(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Cancel and List
|
||||
|
||||
```go
|
||||
canceled, err := client.Messages.Batches.Cancel(ctx, batch.ID, anthropic.MessageBatchCancelParams{})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
fmt.Println(canceled.ProcessingStatus) // "canceling"
|
||||
|
||||
iter := client.Messages.Batches.ListAutoPaging(ctx, anthropic.MessageBatchListParams{Limit: anthropic.Int(20)})
|
||||
for iter.Next() {
|
||||
fmt.Println(iter.Current().ID)
|
||||
}
|
||||
if err := iter.Err(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Beta Features in a Batch
|
||||
|
||||
A batch that needs a beta feature goes through `client.Beta.Messages.Batches`, with the `Beta` twin of every type above: `BetaMessageBatchNewParams` (which carries `Betas`), `BetaMessageBatchNewParamsRequest`, `BetaMessageBatchNewParamsRequestParams` (its `Messages` are `BetaMessageParam`), `BetaMessageBatchGetParams`, `BetaMessageBatchResultsParams` and `BetaMessageBatchSucceededResult`. For example, `Betas: []anthropic.AnthropicBeta{"output-300k-2026-03-24"}` raises the `max_tokens` cap to 300,000 for batches on supported models.
|
||||
@@ -21,3 +21,25 @@ Other `Beta.Files` methods: `List`, `Delete`, `Download`, `GetMetadata`.
|
||||
|
||||
---
|
||||
|
||||
### Set an Expiry
|
||||
|
||||
`ExpiresInSeconds` sets when a file expires: a whole number of seconds from 3,600 (1 hour) to 7,776,000 (90 days), counted from the upload. It can't be changed later.
|
||||
|
||||
```go
|
||||
report, err := os.Open("report.pdf")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer report.Close()
|
||||
|
||||
temporary, err := client.Files.Upload(ctx, anthropic.FileUploadParams{
|
||||
File: anthropic.File(report, "report.pdf", "application/pdf"),
|
||||
ExpiresInSeconds: anthropic.Int(86400),
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
fmt.Println(temporary.ID, temporary.ExpiresAt)
|
||||
```
|
||||
|
||||
`ExpiresAt` is the zero `time.Time` for a file with no expiry. Use `client.Files` with no beta header, as here: requests that send `files-api-2025-04-14` don't get this field back. A message that references an expired file fails. Expiry isn't a guaranteed-deletion control: before relying on it for data handling, read File expiration in `https://platform.claude.com/docs/en/build-with-claude/files.md`.
|
||||
|
||||
@@ -97,7 +97,7 @@ for _, block := range message.Content {
|
||||
|
||||
### Manual Loop
|
||||
|
||||
Prefer the tool runner above to a manual loop. For interception, validation, logging, or human-in-the-loop approval, gate inside the tool's run function or step the runner with `NextMessage()`/`All()` and inspect each message (the runner's public `Params` field lets you adjust the next request) - a manual loop is not required. Drop to a manual loop only when you need control the runner does not expose: define tools with `ToolParam`, check `StopReason`, execute tools yourself, and feed `tool_result` blocks back.
|
||||
Use a manual loop when a tool call needs a person's approval first, or for custom logging or conditional execution: define tools with `ToolParam`, check `StopReason`, execute tools yourself, and feed `tool_result` blocks back. Otherwise use the tool runner above. If you already use the tool runner, gate approvals in the tool's handler (Denying a Tool Call in the Tool Runner, below); to inspect or validate, step the runner with `NextMessage()`/`All()` and read each message (its public `Params` field lets you adjust the next request).
|
||||
|
||||
Derived from `anthropic-sdk-go/examples/tools/main.go`.
|
||||
|
||||
@@ -201,18 +201,185 @@ func main() {
|
||||
|
||||
## Anthropic-Defined Tools
|
||||
|
||||
Version-suffixed struct names with `Param` suffix. `Name`/`Type` are `constant.*` types - zero value marshals correctly, so `{}` works. Wrap in `ToolUnionParam` with the matching `Of*` field. Web search and code execution are server-executed; bash and text editor are client-executed (you handle the `tool_use` locally - see `shared/tool-use-concepts.md`).
|
||||
Version-suffixed struct names with `Param` suffix. `Name`/`Type` are `constant.*` types - zero value marshals correctly, so `{}` works. The exception is the tool-search params: their `Type` is a string enum you must set, e.g. `ToolSearchToolRegex20251119Param{Type: anthropic.ToolSearchToolRegex20251119TypeToolSearchToolRegex20251119}` (BM25: `anthropic.ToolSearchToolBm25_20251119TypeToolSearchToolBm25_20251119`). Wrap in `ToolUnionParam` with the matching `Of*` field. Web search and code execution are server-executed; bash and text editor are client-executed (you handle the `tool_use` locally - see `shared/tool-use-concepts.md`).
|
||||
|
||||
```go
|
||||
Tools: []anthropic.ToolUnionParam{
|
||||
{OfWebSearchTool20260209: &anthropic.WebSearchTool20260209Param{}},
|
||||
{OfWebSearchTool20260318: &anthropic.WebSearchTool20260318Param{}},
|
||||
{OfBashTool20250124: &anthropic.ToolBash20250124Param{}},
|
||||
{OfTextEditor20250728: &anthropic.ToolTextEditor20250728Param{}},
|
||||
{OfCodeExecutionTool20260120: &anthropic.CodeExecutionTool20260120Param{}},
|
||||
},
|
||||
```
|
||||
|
||||
Also available: `WebFetchTool20260209Param`, `ToolSearchToolBm25_20251119Param`, `ToolSearchToolRegex20251119Param`. For the advisor and memory tools, use `BetaAdvisorTool20260301Param` / `BetaMemoryTool20250818Param` in the beta namespace on `client.Beta.Messages.New`.
|
||||
Also available: `WebFetchTool20260318Param` (set `UseCache: anthropic.Bool(false)` to bypass the cache), `MemoryTool20250818Param`, `ToolSearchToolBm25_20251119Param`, `ToolSearchToolRegex20251119Param`. For the advisor tool, use `BetaAdvisorTool20260301Param` in the beta namespace on `client.Beta.Messages.New`.
|
||||
|
||||
### Code Execution Results and Generated Files
|
||||
|
||||
`CodeExecutionTool20260521Param` (non-beta, on `client.Messages.New`) returns `BashCodeExecutionToolResultBlock`; `b.Content` is a union, so check `b.Content.Type` first. Files Claude wrote are in `b.Content.Content`, one `FileID` each. When another tool in the request lists code execution in its `AllowedCallers` (as `web_search_20260209` and later do by default), the output can come back as a `CodeExecutionToolResultBlock` instead, with the same `Content.Stdout` / `Stderr` / `ReturnCode`.
|
||||
|
||||
```go
|
||||
var fileIDs []string
|
||||
for _, block := range response.Content {
|
||||
switch b := block.AsAny().(type) {
|
||||
case anthropic.ServerToolUseBlock:
|
||||
fmt.Println("tool:", b.Name, "input:", b.JSON.Input.Raw())
|
||||
case anthropic.BashCodeExecutionToolResultBlock:
|
||||
if b.Content.Type == "bash_code_execution_result" {
|
||||
fmt.Println("stdout:", b.Content.Stdout, "exit:", b.Content.ReturnCode)
|
||||
for _, output := range b.Content.Content {
|
||||
fileIDs = append(fileIDs, output.FileID)
|
||||
}
|
||||
} else {
|
||||
fmt.Println("error:", b.Content.ErrorCode)
|
||||
}
|
||||
case anthropic.CodeExecutionToolResultBlock:
|
||||
fmt.Println("stdout:", b.Content.Stdout)
|
||||
}
|
||||
}
|
||||
|
||||
for _, id := range fileIDs {
|
||||
file, err := client.Files.Download(ctx, id, anthropic.FileDownloadParams{})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
out, err := os.Create(id)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if _, err := io.Copy(out, file.Body); err != nil { // file is an *http.Response
|
||||
log.Fatal(err)
|
||||
}
|
||||
file.Body.Close()
|
||||
if err := out.Close(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Agent Skills and Containers
|
||||
|
||||
`Container` is a union. `OfContainers` loads skills, and on a later request carries the container's `ID` beside the same `Skills`. `OfString` passes back a container id when no skills are in use (on a `pause_turn` continuation, or to keep files across requests). Both are non-beta. Skills need a code execution tool; read generated files as shown above.
|
||||
|
||||
```go
|
||||
skills := []anthropic.SkillParams{
|
||||
{Type: anthropic.SkillParamsTypeAnthropic, SkillID: "pptx", Version: anthropic.String("latest")},
|
||||
}
|
||||
|
||||
response, err := client.Messages.New(ctx, anthropic.MessageNewParams{
|
||||
Model: "claude-opus-5-5",
|
||||
MaxTokens: 16000,
|
||||
Container: anthropic.MessageCreateParamsContainerUnion{
|
||||
OfContainers: &anthropic.ContainerParams{Skills: skills},
|
||||
},
|
||||
Tools: []anthropic.ToolUnionParam{
|
||||
{OfCodeExecutionTool20260521: &anthropic.CodeExecutionTool20260521Param{}},
|
||||
},
|
||||
Messages: []anthropic.MessageParam{
|
||||
anthropic.NewUserMessage(anthropic.NewTextBlock("Create a 3-slide presentation on X")),
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Later request on the same container. response.Container.ID is "" when the response has none.
|
||||
next := anthropic.MessageNewParams{
|
||||
Model: "claude-opus-5-5",
|
||||
MaxTokens: 16000,
|
||||
Container: anthropic.MessageCreateParamsContainerUnion{
|
||||
OfContainers: &anthropic.ContainerParams{Skills: skills},
|
||||
},
|
||||
Tools: []anthropic.ToolUnionParam{
|
||||
{OfCodeExecutionTool20260521: &anthropic.CodeExecutionTool20260521Param{}},
|
||||
},
|
||||
Messages: []anthropic.MessageParam{
|
||||
anthropic.NewUserMessage(anthropic.NewTextBlock("Create a 3-slide presentation on X")),
|
||||
response.ToParam(),
|
||||
anthropic.NewUserMessage(anthropic.NewTextBlock("Add a fourth slide")),
|
||||
},
|
||||
}
|
||||
if response.Container.ID != "" {
|
||||
next.Container.OfContainers.ID = anthropic.String(response.Container.ID)
|
||||
}
|
||||
```
|
||||
|
||||
### Programmatic Tool Calling and Input Examples
|
||||
|
||||
Both are plain fields on `ToolParam`, with no beta namespace or header: `AllowedCallers` is a `[]string` and `InputExamples` a `[]map[string]any`. Declare `CodeExecutionTool20260120Param` beside a tool that sets `AllowedCallers`; a pending call comes back as a `ToolUseBlock`. The next request must pass the container id, as `anthropic.MessageCreateParamsContainerUnion{OfString: anthropic.String(id)}`, or the API rejects the request, and its user message must hold only `tool_result` blocks.
|
||||
|
||||
```go
|
||||
Tools: []anthropic.ToolUnionParam{
|
||||
{OfCodeExecutionTool20260120: &anthropic.CodeExecutionTool20260120Param{}},
|
||||
{OfTool: &anthropic.ToolParam{
|
||||
Name: "lookup_order",
|
||||
Description: anthropic.String("Look up an order by id. Returns it as JSON."),
|
||||
InputSchema: anthropic.ToolInputSchemaParam{Properties: map[string]any{"order_id": map[string]any{"type": "string"}}, Required: []string{"order_id"}},
|
||||
AllowedCallers: []string{"code_execution_20260120"},
|
||||
InputExamples: []map[string]any{{"order_id": "A-1001"}},
|
||||
}},
|
||||
},
|
||||
```
|
||||
|
||||
### MCP Connector (beta)
|
||||
|
||||
Needs both halves on `client.Beta.Messages.New`: `MCPServers` and a `BetaMCPToolsetParam` naming the same server.
|
||||
|
||||
```go
|
||||
response, err := client.Beta.Messages.New(ctx, anthropic.BetaMessageNewParams{
|
||||
Model: "claude-opus-5-5",
|
||||
MaxTokens: 16000,
|
||||
Betas: []anthropic.AnthropicBeta{anthropic.AnthropicBetaMCPClient2025_11_20},
|
||||
MCPServers: []anthropic.BetaRequestMCPServerURLDefinitionParam{
|
||||
{URL: "https://mcp.example.com/mcp", Name: "my-server"},
|
||||
},
|
||||
Tools: []anthropic.BetaToolUnionParam{
|
||||
{OfMCPToolset: &anthropic.BetaMCPToolsetParam{
|
||||
MCPServerName: "my-server",
|
||||
DefaultConfig: anthropic.BetaMCPToolDefaultConfigParam{Enabled: anthropic.Bool(false)}, // allowlist mode
|
||||
Configs: map[string]anthropic.BetaMCPToolConfigParam{"search_tickets": {Enabled: anthropic.Bool(true)}},
|
||||
}},
|
||||
},
|
||||
Messages: []anthropic.BetaMessageParam{
|
||||
anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("List my open tickets")),
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
for _, block := range response.Content {
|
||||
switch b := block.AsAny().(type) {
|
||||
case anthropic.BetaMCPToolUseBlock:
|
||||
fmt.Println("call:", b.ServerName, b.Name, b.Input)
|
||||
case anthropic.BetaMCPToolResultBlock:
|
||||
fmt.Println("result:", b.IsError, b.JSON.Content.Raw())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Denying a Tool Call in the Tool Runner
|
||||
|
||||
In the tool runner, Go always runs the tools and appends the assistant message and the tool results, so your loop can't deny a call; changing `runner.Params` only affects later requests. Put an approval gate in the tool's handler, before the work; handlers for one turn run concurrently, so the gate must be safe to call in parallel. An error returned there goes back to Claude as a `tool_result` with `is_error: true`, and the work never runs. Keep `MaxIterations` set to bound the loop.
|
||||
|
||||
```go
|
||||
type SendEmailInput struct {
|
||||
To string `json:"to" jsonschema:"required"`
|
||||
}
|
||||
|
||||
sendEmailTool, err := toolrunner.NewBetaToolFromJSONSchema("send_email", "Send an email",
|
||||
func(ctx context.Context, input SendEmailInput) (anthropic.BetaToolResultBlockParamContentUnion, error) {
|
||||
if !approved(input.To) {
|
||||
return anthropic.BetaToolResultBlockParamContentUnion{}, fmt.Errorf("denied by the user: %s", input.To)
|
||||
}
|
||||
if err := sendEmail(input.To); err != nil {
|
||||
return anthropic.BetaToolResultBlockParamContentUnion{}, err
|
||||
}
|
||||
return anthropic.BetaToolResultBlockParamContentUnion{
|
||||
OfText: &anthropic.BetaTextBlockParam{Text: "sent to " + input.To},
|
||||
}, nil
|
||||
},
|
||||
)
|
||||
```
|
||||
|
||||
### Advisor tool (beta)
|
||||
|
||||
|
||||
@@ -161,7 +161,7 @@ if err != nil {
|
||||
}
|
||||
```
|
||||
|
||||
> Tip: **Stream-first:** Open the stream *before* (or concurrently with) sending the message. The stream only delivers events that occur after it opens - stream-after-send means early events arrive buffered in one batch. See [Steering Patterns](../../shared/managed-agents-events.md#steering-patterns).
|
||||
> Tip: **Stream-first:** Open the stream *before* sending the message. The stream only delivers events that occur after it opens. See [Steering Patterns](../../shared/managed-agents-events.md#steering-patterns).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ Types are organized by package. If a class you need isn't shown in an example be
|
||||
|---|---|
|
||||
| `com.anthropic.client` / `com.anthropic.client.okhttp` | `AnthropicClient`, `AnthropicOkHttpClient` |
|
||||
| `com.anthropic.models.messages` | non-beta request/response types - `MessageCreateParams`, `Model`, `Message`, `TextBlockParam`, `ContentBlockParam`, `ToolUseBlockParam`, `ToolResultBlockParam`, `CacheControlEphemeral`, `Tool*` (e.g. `ToolBash20250124`, `ToolTextEditor20250728`), `StopReason`, `StructuredMessage*` |
|
||||
| `com.anthropic.models.messages.batches` | Batch API - `BatchResultsParams`, `MessageBatchIndividualResponse` |
|
||||
| `com.anthropic.models.messages.batches` | Batch API - `BatchCreateParams`, `MessageBatch`, `BatchResultsParams`, `MessageBatchIndividualResponse` (see `batches.md`) |
|
||||
| `com.anthropic.models.beta` | `AnthropicBeta` (beta-flag constants) |
|
||||
| `com.anthropic.models.beta.messages` | beta-endpoint types - `MessageCreateParams`, `BetaMessage`, `BetaStopReason`, `BetaContextManagementConfig`, `BetaMcpToolset`, `BetaRequestMcpServerUrlDefinition`, `BetaTool*` |
|
||||
| `com.anthropic.core` | `JsonValue`, `JsonField`, `JsonSchemaLocalValidation`, `com.anthropic.core.http.StreamResponse` |
|
||||
@@ -24,16 +24,19 @@ Write from this table instead of `javap`/jar inspection. Endpoint column tells y
|
||||
|
||||
| Feature | Endpoint | Key Java types / builder calls |
|
||||
|---|---|---|
|
||||
| User profiles | beta | `client.beta().userProfiles().create(...)` / `.retrieve(id)` / `.list()`. Pass the returned profile id on the beta `MessageCreateParams`. Requires a beta header - check the SDK's beta-headers reference for the current flag. |
|
||||
| Agent Skills | beta | `BetaContainerParams`, `BetaSkillParams`, `BetaCodeExecutionTool20250825`. `.addBeta("code-execution-2025-08-25")` (Skills is out of beta - no `skills-2025-10-02`). Download the output via `client.beta().files().download(fileId)`. |
|
||||
| Cache diagnostics | beta | `BetaDiagnosticsParam`, `BetaCacheControlEphemeral` |
|
||||
| User profiles | non-beta | `client.userProfiles().create(...)` / `.retrieve(id)` / `.list()`. Pass the returned profile id with `.userProfileId(id)` on `MessageCreateParams`. |
|
||||
| Agent Skills | non-beta | `ContainerParams`, `SkillParams`, `CodeExecutionTool20260521`. Download the output via `client.files().download(fileId)`. |
|
||||
| Cache diagnostics | non-beta | `.diagnostics(DiagnosticsParam.builder().previousMessageId((String) null).build())` on the first turn (without the cast the call is ambiguous), then `.previousMessageId(previous.id())`. Mark the cached block with `CacheControlEphemeral` |
|
||||
| Context editing | beta | `.contextManagement(BetaContextManagementConfig.builder()...)`. The edit strategy is a `BetaClearToolUses20250919Edit` (or `BetaClearThinking20251015Edit`); its trigger is a `BetaInputTokensTrigger` built separately and passed to the edit's builder - there is no direct `.inputTokensTrigger(N)` shortcut on the edit builder. `javap` the edit and trigger classes for the exact setter names. |
|
||||
| Generated files | non-beta | `block.bashCodeExecutionToolResult()`, then `r.content().bashCodeExecutionResultBlock()`, then `.content()`, each with `.fileId()`; sample in `tool-use.md` |
|
||||
| MCP connector | beta | `.addMcpServer(...)` plus `.addTool(BetaMcpToolset.builder().mcpServerName(...).build())`; sample in `tool-use.md` |
|
||||
| Memory tool | non-beta | `.addTool(MemoryTool20250818.builder().build())` from `com.anthropic.models.messages` |
|
||||
| Programmatic tool calling | non-beta | `CodeExecutionTool20260120`, `Tool`, `ContentBlockParam` |
|
||||
| Programmatic tool calling | non-beta | `CodeExecutionTool20260120`, `Tool`, `ContentBlockParam`. On the tool: `.addAllowedCaller(Tool.AllowedCaller.CODE_EXECUTION_20260120)`. On the next request: `.container(response.container().get().id())` |
|
||||
| Reading tool input | non-beta | `ToolUseBlock` and `ServerToolUseBlock` have no `.input()`: use `._input().convert(Map.class)`, or `.convert(MyInput.class)` where `MyInput` is a record or has `@JsonProperty` on its fields. Beta `BetaToolUseBlock` has `.input(MyInput.class)` |
|
||||
| Strict tool use | non-beta | `Tool`, `Tool.InputSchema` |
|
||||
| Task budgets | beta | `.outputConfig(BetaOutputConfig.builder().taskBudget(BetaTokenTaskBudget.builder()...))` |
|
||||
| Tool search | non-beta | `.addTool(ToolSearchToolRegex20251119.builder()...)` from `com.anthropic.models.messages` |
|
||||
| Web search | non-beta | `WebSearchTool20260209` from `com.anthropic.models.messages` - a variant with dynamic filtering (Claude Fable 5.2 / Claude Mythos 5.2 + Claude Fable 5.1 / Claude Mythos 5.1 + Claude Opus 5.5 + Claude Opus 5 + Opus 4.8/4.7/4.6 + Claude Sonnet 5.5 + Claude Sonnet 5 + Sonnet 4.6). For older models or Vertex, use `WebSearchTool20250305` |
|
||||
| Tool search | non-beta | `.addTool(ToolSearchToolRegex20251119.builder().type(ToolSearchToolRegex20251119.Type.TOOL_SEARCH_TOOL_REGEX_20251119).build())` from `com.anthropic.models.messages` |
|
||||
| Web search | non-beta | `WebSearchTool20260318` from `com.anthropic.models.messages` - a variant with dynamic filtering (Claude 4.6 and later models, Fable and Mythos included). For older models, Vertex, or Foundry deployments hosted on Azure, use `WebSearchTool20250305` |
|
||||
|
||||
### Discovering type and member names
|
||||
|
||||
@@ -47,16 +50,18 @@ Maven:
|
||||
<dependency>
|
||||
<groupId>com.anthropic</groupId>
|
||||
<artifactId>anthropic-java</artifactId>
|
||||
<version>3.3.0</version>
|
||||
<version>3.16.0</version>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
Gradle:
|
||||
|
||||
```groovy
|
||||
implementation("com.anthropic:anthropic-java:3.3.0")
|
||||
implementation("com.anthropic:anthropic-java:3.16.0")
|
||||
```
|
||||
|
||||
For a cloud platform, add the matching artifact beside `anthropic-java`, at the same version: `anthropic-java-vertex`, `anthropic-java-bedrock`, `anthropic-java-foundry`, `anthropic-java-aws` for Claude Platform on AWS, or `anthropic-java-google-cloud` (beta) for Claude Models on Google Cloud (Anthropic managed). `GoogleCredentials` is in `com.google.auth.oauth2`.
|
||||
|
||||
## Client Initialization
|
||||
|
||||
```java
|
||||
@@ -70,6 +75,12 @@ AnthropicClient client = AnthropicOkHttpClient.fromEnv();
|
||||
AnthropicClient client = AnthropicOkHttpClient.builder()
|
||||
.apiKey("your-api-key")
|
||||
.build();
|
||||
|
||||
// Key not scoped to one workspace
|
||||
AnthropicClient client = AnthropicOkHttpClient.builder()
|
||||
.fromEnv()
|
||||
.putHeader("anthropic-workspace-id", "wrkspc_...")
|
||||
.build();
|
||||
```
|
||||
|
||||
---
|
||||
@@ -217,7 +228,7 @@ response.stopDetails().ifPresent(details -> {
|
||||
});
|
||||
```
|
||||
|
||||
**Refusal fallbacks (Claude Fable 5.2) - opt in by default.** Fallbacks are opt-in: without them a refused request simply stops. New `claude-fable-5-2` code should include the server-side `fallbacks` parameter (beta header `server-side-fallback-2026-07-01`, fallback model `claude-opus-4-8`, on the beta messages call) by default. The exact Java builder methods (and the client-side middleware for providers without server-side support) are not documented here - fetch the Java SDK repo's `examples/` from `shared/live-sources.md`; full semantics in `shared/model-migration.md` -> Migrating to Claude Fable 5.1 -> `refusal` stop reason.
|
||||
**Refusal fallbacks (Claude Fable 5.2) - opt in by default.** Fallbacks are opt-in: without them a refused request simply stops. New `claude-fable-5-2` code should include the server-side `fallbacks` parameter (beta header `server-side-fallback-2026-07-01`, on the beta messages call) by default. On the beta `MessageCreateParams.builder()`, call `.fallbacksDefault()` and `.addBeta(AnthropicBeta.SERVER_SIDE_FALLBACK_2026_07_01)`. To name the models yourself, use `.fallbacksOfFallbackParams(List.of(BetaFallbackParam.builder().model(Model.CLAUDE_OPUS_4_8).build()))`. On that builder, the content-block call is `.addUserMessageOfContentBlockParams(...)`, not `addUserMessageOfBetaContentBlockParams`, and takes `BetaContentBlockParam` items, such as `BetaContentBlockParam.ofImage(BetaImageBlockParam.builder()...build())`. For the client-side `BetaRefusalFallbackInterceptor` (providers without server-side support), see `anthropic-java-example/src/main/java/com/anthropic/example/FallbacksExample.java` in the Java SDK repo (`shared/live-sources.md`). Full semantics: `shared/model-migration.md` -> Migrating to Claude Fable 5.1 -> `refusal` stop reason.
|
||||
|
||||
---
|
||||
|
||||
|
||||
89
skills/claude-api/java/claude-api/batches.md
Normal file
89
skills/claude-api/java/claude-api/batches.md
Normal file
@@ -0,0 +1,89 @@
|
||||
# Message Batches API - Java
|
||||
|
||||
The Batches API (`POST /v1/messages/batches`) processes Messages API requests asynchronously at 50% of standard prices.
|
||||
|
||||
## Key Facts
|
||||
|
||||
- Up to 100,000 requests or 256 MB per batch
|
||||
- Most batches complete within 1 hour; maximum 24 hours
|
||||
- Results available for 29 days after creation
|
||||
- Most Messages API features work (vision, tools, caching, etc.); a batch request can't set `stream`, `speed`, `fallbacks` or `max_tokens: 0`, even where the builder has the method
|
||||
- Results arrive in any order: key by `customId()`, never by position
|
||||
|
||||
---
|
||||
|
||||
## Create a Batch
|
||||
|
||||
`Request.Builder.params(...)` takes only `BatchCreateParams.Request.Params`, not a `MessageCreateParams`. Its builder has the same methods (`.model()`, `.maxTokens()`, `.addUserMessage()`, `.addTool()`).
|
||||
|
||||
```java
|
||||
import com.anthropic.models.messages.batches.BatchCreateParams;
|
||||
import com.anthropic.models.messages.batches.MessageBatch;
|
||||
|
||||
MessageBatch batch = client.messages().batches().create(BatchCreateParams.builder()
|
||||
.addRequest(BatchCreateParams.Request.builder()
|
||||
.customId("request-1")
|
||||
.params(BatchCreateParams.Request.Params.builder()
|
||||
.model("claude-opus-5-5")
|
||||
.maxTokens(16000L)
|
||||
.addUserMessage("Summarize climate change impacts")
|
||||
.build())
|
||||
.build())
|
||||
.build());
|
||||
|
||||
System.out.println(batch.id() + " " + batch.processingStatus());
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Poll for Completion
|
||||
|
||||
`processingStatus()` returns a class, not a Java enum, so compare with `equals`.
|
||||
|
||||
```java
|
||||
while (!batch.processingStatus().equals(MessageBatch.ProcessingStatus.ENDED)) {
|
||||
Thread.sleep(60_000);
|
||||
batch = client.messages().batches().retrieve(batch.id());
|
||||
}
|
||||
System.out.println("Succeeded: " + batch.requestCounts().succeeded());
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Retrieve Results
|
||||
|
||||
```java
|
||||
import com.anthropic.core.http.StreamResponse;
|
||||
import com.anthropic.models.messages.batches.MessageBatchIndividualResponse;
|
||||
|
||||
try (StreamResponse<MessageBatchIndividualResponse> results =
|
||||
client.messages().batches().resultsStreaming(batch.id())) {
|
||||
results.stream().forEach(response -> {
|
||||
String id = response.customId();
|
||||
response.result().succeeded().ifPresent(ok ->
|
||||
ok.message().content().forEach(block ->
|
||||
block.text().ifPresent(text -> System.out.println(id + ": " + text.text()))));
|
||||
response.result().errored().ifPresent(failed ->
|
||||
System.out.println(id + ": " + failed.error().error()));
|
||||
response.result().canceled().ifPresent(canceled -> System.out.println(id + ": canceled"));
|
||||
response.result().expired().ifPresent(expired -> System.out.println(id + ": expired - resubmit"));
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Cancel and List
|
||||
|
||||
```java
|
||||
MessageBatch canceled = client.messages().batches().cancel(batch.id());
|
||||
System.out.println(canceled.processingStatus()); // canceling
|
||||
|
||||
client.messages().batches().list().autoPager().forEach(b -> System.out.println(b.id()));
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Beta Features in a Batch
|
||||
|
||||
A batch that needs a beta feature goes through `client.beta().messages().batches()`. The params classes keep their names in `com.anthropic.models.beta.messages.batches` (`BatchCreateParams`, `BatchResultsParams`), so import the one matching the client path, and the result classes gain a `Beta` prefix (`BetaMessageBatch`, `BetaMessageBatchIndividualResponse`). `.addBeta(...)` goes on the outer `BatchCreateParams` builder, not on `Request.Params`. For example, `.addBeta("output-300k-2026-03-24")` raises the `max_tokens` cap to 300,000 for batches on supported models.
|
||||
@@ -25,3 +25,22 @@ BetaRequestDocumentBlock doc = BetaRequestDocumentBlock.builder()
|
||||
```
|
||||
|
||||
Other methods: `.list()`, `.delete(String fileId)`, `.download(String fileId)`, `.retrieveMetadata(String fileId)`.
|
||||
|
||||
### Set an Expiry
|
||||
|
||||
`expiresInSeconds` sets when a file expires: a whole number of seconds from 3,600 (1 hour) to 7,776,000 (90 days), counted from the upload. It can't be changed later.
|
||||
|
||||
```java
|
||||
import com.anthropic.models.files.FileMetadata;
|
||||
import com.anthropic.models.files.FileUploadParams;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
FileMetadata temporary = client.files().upload(
|
||||
FileUploadParams.builder()
|
||||
.file(Paths.get("/path/to/doc.pdf"))
|
||||
.expiresInSeconds(86400L)
|
||||
.build());
|
||||
System.out.println(temporary.id() + " " + temporary.expiresAt()); // an Optional
|
||||
```
|
||||
|
||||
`expiresAt()` is empty for a file with no expiry. Use `client.files()` with no beta header, as here: requests that send `files-api-2025-04-14` don't get this field back. A message that references an expired file fails. Expiry isn't a guaranteed-deletion control: before relying on it for data handling, read File expiration in `https://platform.claude.com/docs/en/build-with-claude/files.md`.
|
||||
|
||||
@@ -119,7 +119,7 @@ MessageCreateParams params = MessageCreateParams.builder()
|
||||
.build();
|
||||
```
|
||||
|
||||
For manual tool loops, handle `tool_use` blocks in the response, send `tool_result` back, loop until `stop_reason` is `"end_turn"`. See [shared tool use concepts](../../shared/tool-use-concepts.md).
|
||||
For manual tool loops, handle `tool_use` blocks in the response, send `tool_result` back, loop while `stop_reason` is `"tool_use"`. See [shared tool use concepts](../../shared/tool-use-concepts.md).
|
||||
|
||||
### Building `MessageParam` with Content Blocks (Tool Result Round-Trip)
|
||||
|
||||
@@ -173,15 +173,15 @@ Supports Jackson annotations: `@JsonPropertyDescription`, `@JsonIgnore`, `@Array
|
||||
|
||||
## Anthropic-Defined Tools
|
||||
|
||||
Version-suffixed types; `name`/`type` auto-set by builder. Direct `.addTool()` overloads exist for most tool types; where one is missing (newer or less-common tools - see the advisor note below), wrap via the union type's static factory: `.addTool(BetaToolUnion.of<ToolName>(builder...build()))`. Web search and code execution are server-executed; bash and text editor are client-executed (you handle the `tool_use` locally - see `shared/tool-use-concepts.md`).
|
||||
Version-suffixed types; `name`/`type` auto-set by builder, except the two tool search classes (see "Also available" below). Direct `.addTool()` overloads exist for most tool types; where one is missing, wrap via the union type's static factory: `.addTool(BetaToolUnion.of<ToolName>(builder...build()))`. Web search and code execution are server-executed; bash and text editor are client-executed (you handle the `tool_use` locally - see `shared/tool-use-concepts.md`).
|
||||
|
||||
```java
|
||||
import com.anthropic.models.messages.WebSearchTool20260209;
|
||||
import com.anthropic.models.messages.WebSearchTool20260318;
|
||||
import com.anthropic.models.messages.ToolBash20250124;
|
||||
import com.anthropic.models.messages.ToolTextEditor20250728;
|
||||
import com.anthropic.models.messages.CodeExecutionTool20260120;
|
||||
|
||||
.addTool(WebSearchTool20260209.builder()
|
||||
.addTool(WebSearchTool20260318.builder()
|
||||
.maxUses(5L) // optional
|
||||
.allowedDomains(List.of("example.com")) // optional
|
||||
.build())
|
||||
@@ -190,7 +190,7 @@ import com.anthropic.models.messages.CodeExecutionTool20260120;
|
||||
.addTool(CodeExecutionTool20260120.builder().build())
|
||||
```
|
||||
|
||||
Also available: `WebFetchTool20260209`, `MemoryTool20250818`, `ToolSearchToolBm25_20251119`. For the advisor tool, use `BetaAdvisorTool20260301` in the beta namespace with `.addBeta("advisor-tool-2026-03-01")` (server-side; advisor model >= executor model). There is no direct `.addTool(BetaAdvisorTool20260301)` overload on the beta builder - wrap it via the `BetaToolUnion` static factory for the advisor type; if `javac` rejects the specific factory method name, `javap com.anthropic.models.beta.messages.BetaToolUnion | grep -i advisor` shows the exact one.
|
||||
Also available: `WebFetchTool20260318` (`.useCache(false)` bypasses the cache), `MemoryTool20250818`, `ToolSearchToolBm25_20251119` (its builder needs `.type(ToolSearchToolBm25_20251119.Type.TOOL_SEARCH_TOOL_BM25_20251119)` before `.build()`, or `build()` throws; `ToolSearchToolRegex20251119`'s builder needs `.type(ToolSearchToolRegex20251119.Type.TOOL_SEARCH_TOOL_REGEX_20251119)` the same way). For the advisor tool, use `BetaAdvisorTool20260301` in the beta namespace with `.addBeta("advisor-tool-2026-03-01")` (server-side; advisor model >= executor model). Pass it straight to `.addTool(...)`.
|
||||
|
||||
### Beta namespace (MCP, compaction)
|
||||
|
||||
@@ -201,6 +201,7 @@ import com.anthropic.models.beta.messages.MessageCreateParams;
|
||||
import com.anthropic.models.beta.messages.BetaToolBash20250124;
|
||||
import com.anthropic.models.beta.messages.BetaCodeExecutionTool20260120;
|
||||
import com.anthropic.models.beta.messages.BetaRequestMcpServerUrlDefinition;
|
||||
import com.anthropic.models.beta.messages.BetaMcpToolset;
|
||||
|
||||
MessageCreateParams params = MessageCreateParams.builder()
|
||||
.model("claude-opus-5-5")
|
||||
@@ -212,12 +213,15 @@ MessageCreateParams params = MessageCreateParams.builder()
|
||||
.name("my-server")
|
||||
.url("https://example.com/mcp")
|
||||
.build())
|
||||
.addTool(BetaMcpToolset.builder().mcpServerName("my-server").build())
|
||||
.addUserMessage("...")
|
||||
.build();
|
||||
|
||||
client.beta().messages().create(params);
|
||||
```
|
||||
|
||||
The toolset's server name must match `addMcpServer`. For allowlist mode, add `.defaultConfig(BetaMcpToolDefaultConfig.builder().enabled(false).build())` and `.configs(BetaMcpToolset.Configs.builder().putAdditionalProperty("search_tickets", JsonValue.from(Map.of("enabled", true))).build())`; `Configs` is a freeform map keyed by tool name.
|
||||
|
||||
`BetaTool*` types are NOT interchangeable with non-beta `Tool*` - pick one namespace per request.
|
||||
|
||||
**Reading server-tool blocks in the response:** `ServerToolUseBlock` has `.id()`, `.name()` (enum), and `._input()` returning raw `JsonValue` - there is NO typed `.input()`. For code execution results, unwrap two levels:
|
||||
@@ -237,5 +241,120 @@ for (ContentBlock block : response.content()) {
|
||||
}
|
||||
```
|
||||
|
||||
**Reading bash code execution results:** Code execution returns `bashCodeExecutionToolResult()` blocks, or `codeExecutionToolResult()` blocks when another tool in the request lists code execution in its allowed callers (as `web_search_20260209` and later do by default). Bash blocks hold the exit code and any files Claude wrote. Download a file with `client.files().download(fileId)`.
|
||||
|
||||
```java
|
||||
import com.anthropic.core.http.HttpResponse;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.ArrayList;
|
||||
|
||||
List<String> fileIds = new ArrayList<>();
|
||||
for (ContentBlock block : response.content()) {
|
||||
block.bashCodeExecutionToolResult().ifPresent(r ->
|
||||
r.content().bashCodeExecutionResultBlock().ifPresent(result -> {
|
||||
System.out.println("stdout: " + result.stdout());
|
||||
System.out.println("exit: " + result.returnCode());
|
||||
result.content().forEach(output -> fileIds.add(output.fileId()));
|
||||
}));
|
||||
}
|
||||
for (String fileId : fileIds) {
|
||||
try (HttpResponse file = client.files().download(fileId)) {
|
||||
Files.copy(file.body(), Path.of(fileId), StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Agent Skills and Containers
|
||||
|
||||
`.container(...)` takes a `ContainerParams` to load skills, and on a later request the same `ContainerParams` with the container's `.id(...)`. Without skills, it takes the `String` id, as on a `pause_turn` continuation. Both are non-beta.
|
||||
|
||||
```java
|
||||
import com.anthropic.models.messages.CodeExecutionTool20260521;
|
||||
import com.anthropic.models.messages.ContainerParams;
|
||||
import com.anthropic.models.messages.Message;
|
||||
import com.anthropic.models.messages.MessageCreateParams;
|
||||
import com.anthropic.models.messages.SkillParams;
|
||||
|
||||
SkillParams skill = SkillParams.builder()
|
||||
.type(SkillParams.Type.ANTHROPIC)
|
||||
.skillId("pptx")
|
||||
.version("latest")
|
||||
.build();
|
||||
|
||||
MessageCreateParams.Builder params = MessageCreateParams.builder()
|
||||
.model("claude-opus-5-5")
|
||||
.maxTokens(16000L)
|
||||
.container(ContainerParams.builder().addSkill(skill).build())
|
||||
.addTool(CodeExecutionTool20260521.builder().build())
|
||||
.addUserMessage("Create a 3-slide presentation on X");
|
||||
|
||||
Message response = client.messages().create(params.build());
|
||||
|
||||
// Continue on the same container:
|
||||
response.container().ifPresent(c -> params.container(ContainerParams.builder().id(c.id()).addSkill(skill).build()));
|
||||
params.addMessage(response);
|
||||
params.addUserMessage("Add a fourth slide");
|
||||
```
|
||||
|
||||
### Custom Tool Options and Reading Tool Input
|
||||
|
||||
`.addAllowedCaller(...)` and `.addInputExample(...)` are non-beta `Tool` builder methods. A `Tool.InputExample` is a freeform map built with `putAdditionalProperty`. Declare `CodeExecutionTool20260120` beside a tool that sets allowed callers.
|
||||
|
||||
```java
|
||||
Tool lookupTool = Tool.builder()
|
||||
.name("lookup_order")
|
||||
.description("Look up an order by id. Returns it as JSON.")
|
||||
.inputSchema(Tool.InputSchema.builder()
|
||||
.properties(JsonValue.from(Map.of("order_id", Map.of("type", "string"))))
|
||||
.addRequired("order_id")
|
||||
.build())
|
||||
.addAllowedCaller(Tool.AllowedCaller.CODE_EXECUTION_20260120)
|
||||
.addInputExample(Tool.InputExample.builder()
|
||||
.putAdditionalProperty("order_id", JsonValue.from("A-1001"))
|
||||
.build())
|
||||
.build();
|
||||
```
|
||||
|
||||
Non-beta `ToolUseBlock` and `ServerToolUseBlock` have no typed `.input()`: `._input()` returns a `JsonValue`, and `convert` turns it into a map, a record, or a class with `@JsonProperty` on its fields. A plain class with public fields throws `Unrecognized field`.
|
||||
|
||||
```java
|
||||
block.toolUse().ifPresent(use -> {
|
||||
Map<?, ?> input = use._input().convert(Map.class);
|
||||
System.out.println(use.name() + " " + input.get("order_id"));
|
||||
});
|
||||
```
|
||||
|
||||
### Denying a Tool Call in the Tool Runner
|
||||
|
||||
For human approval, use a manual loop: call `client.messages().create(...)`, run each `tool_use` yourself, and send back a `tool_result` for each (`shared/tool-use-concepts.md` -> Manual Agentic Loop). If you already use the tool runner, check each call inside the loop and call `runner.setNextParams(...)` before the next iteration. The runner then doesn't run the tools from that message or append anything, so add the assistant message and a `tool_result` for every `tool_use` in it: one denial stops every call in that message. The runner doesn't carry the container forward on this path, so in a run with code execution also add `.container(...)` with the id from `message.container()`. `ToolRunnerCreateParams.builder().maxIterations(...)` bounds the loop.
|
||||
|
||||
```java
|
||||
import com.anthropic.models.beta.messages.BetaContentBlockParam;
|
||||
import com.anthropic.models.beta.messages.BetaToolResultBlockParam;
|
||||
import com.anthropic.models.beta.messages.BetaToolUseBlock;
|
||||
|
||||
for (BetaMessage message : runner) {
|
||||
List<BetaToolUseBlock> calls = new ArrayList<>();
|
||||
message.content().forEach(block -> block.toolUse().ifPresent(calls::add));
|
||||
if (calls.stream().allMatch(use -> approved(use.name()))) {
|
||||
continue; // the runner runs the tools, or the loop ends
|
||||
}
|
||||
List<BetaContentBlockParam> denials = new ArrayList<>();
|
||||
for (BetaToolUseBlock use : calls) {
|
||||
denials.add(BetaContentBlockParam.ofToolResult(BetaToolResultBlockParam.builder()
|
||||
.toolUseId(use.id())
|
||||
.content("user declined")
|
||||
.isError(true)
|
||||
.build()));
|
||||
}
|
||||
runner.setNextParams(runner.params().toBuilder()
|
||||
.addMessage(message)
|
||||
.addUserMessageOfContentBlockParams(denials)
|
||||
.build());
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
<dependency>
|
||||
<groupId>com.anthropic</groupId>
|
||||
<artifactId>anthropic-java</artifactId>
|
||||
<version>3.3.0</version>
|
||||
<version>3.16.0</version>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
@@ -130,7 +130,7 @@ client.beta().sessions().events().send(session.id(), EventSendParams.builder()
|
||||
.build());
|
||||
```
|
||||
|
||||
> Tip: **Stream-first:** Open the stream *before* (or concurrently with) sending the message. The stream only delivers events that occur after it opens - stream-after-send means early events arrive buffered in one batch. See [Steering Patterns](../../shared/managed-agents-events.md#steering-patterns).
|
||||
> Tip: **Stream-first:** Open the stream *before* sending the message. The stream only delivers events that occur after it opens. See [Steering Patterns](../../shared/managed-agents-events.md#steering-patterns).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
composer require "anthropic-ai/sdk"
|
||||
composer require "anthropic-ai/sdk" "guzzlehttp/guzzle:^7"
|
||||
```
|
||||
|
||||
## Client Initialization
|
||||
@@ -17,6 +17,8 @@ use Anthropic\Client;
|
||||
$client = new Client();
|
||||
```
|
||||
|
||||
Timeouts, retries, raw responses and headers, list paging: `php/claude-api/client-options.md`.
|
||||
|
||||
### Amazon Bedrock
|
||||
|
||||
```php
|
||||
@@ -35,9 +37,9 @@ For a model older than Claude 4.7, pin `anthropic-ai/sdk` to 0.x (`composer requ
|
||||
```php
|
||||
use Anthropic\Vertex;
|
||||
|
||||
// Constructor is private. Parameter is `location`, not `region`.
|
||||
// Needs `composer require google/auth`. Constructor is private.
|
||||
$client = Vertex\Client::fromEnvironment(
|
||||
location: 'us-east5',
|
||||
region: 'global',
|
||||
projectId: 'my-project-id',
|
||||
);
|
||||
```
|
||||
|
||||
@@ -4,12 +4,19 @@
|
||||
|
||||
```php
|
||||
$batch = $client->messages->batches->create(requests: [
|
||||
['customId' => 'req-1', 'params' => ['model' => 'claude-opus-5-5', 'maxTokens' => 1024, 'messages' => [...]]],
|
||||
['customId' => 'req-2', 'params' => [...]],
|
||||
['customID' => 'req-1', 'params' => ['model' => 'claude-opus-5-5', 'maxTokens' => 1024, 'messages' => [...]]],
|
||||
['customID' => 'req-2', 'params' => [...]],
|
||||
]);
|
||||
// Poll $client->messages->batches->retrieve($batch->id) until processingStatus === 'ended',
|
||||
// then iterate $client->messages->batches->results($batch->id).
|
||||
// Poll $client->messages->batches->retrieve($batch->id) until processingStatus === 'ended'.
|
||||
|
||||
foreach ($client->messages->batches->resultsStream($batch->id) as $entry) {
|
||||
if ($entry->result->type === 'succeeded') { // or 'errored', 'canceled', 'expired'
|
||||
echo $entry->customID, ': ', $entry->result->message->stopReason, "\n";
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Write the key as `customID` or `custom_id`. `customId` goes out as written, so the request has no `custom_id`. The property on a result is `customID`. Results arrive in any order, so match them on `$entry->customID`. `resultsStream()` is the only results method; `results()` doesn't exist. `->beta->messages->batches` has the same names, and takes `betas:` on both `create()` and `resultsStream()`.
|
||||
|
||||
---
|
||||
|
||||
|
||||
66
skills/claude-api/php/claude-api/client-options.md
Normal file
66
skills/claude-api/php/claude-api/client-options.md
Normal file
@@ -0,0 +1,66 @@
|
||||
# Client Options - PHP
|
||||
|
||||
## Timeouts and retries
|
||||
|
||||
`new Client()` has no `timeout:` or `maxRetries:` argument: both are options in `requestOptions:`. The SDK doesn't enforce `'timeout'`, so that option alone has no effect. A real timeout is set on the HTTP client:
|
||||
|
||||
```php
|
||||
use Anthropic\Client;
|
||||
use GuzzleHttp\Client as GuzzleClient;
|
||||
|
||||
$client = new Client(requestOptions: [
|
||||
'transporter' => new GuzzleClient(['timeout' => 5.0]), // seconds
|
||||
'maxRetries' => 2, // the default
|
||||
]);
|
||||
```
|
||||
|
||||
`requestOptions:` also works per request, on `create()` and the other methods. A timed-out attempt is retried, so wall-clock time can reach the timeout times (`maxRetries` + 1), plus backoff. The call then throws `Anthropic\Core\Exceptions\APIConnectionException`. On `createStream()` the timeout limits only the wait for the response to start. To set it per request there, use `'streamingTransporter' => new GuzzleClient(['timeout' => 5.0, 'stream' => true])`: `'transporter'` is ignored, and without `'stream' => true` nothing arrives until the whole response has, and the timeout limits the whole stream. To limit a stall mid-stream, also set `'read_timeout'` on the Guzzle client; that error comes from the HTTP client, not the SDK.
|
||||
|
||||
## Request headers
|
||||
|
||||
For a key that isn't scoped to one workspace, pass `workspaceID:` on each `create()` call, or set the header for the whole client with a middleware. The middleware's header also reaches the tool runner and the Managed Agents methods, and a `workspaceID:` on a call still wins over it. Don't use the client's `extraHeaders` for this: the tool runner and the Managed Agents methods send their own `extraHeaders`, which replace the client's.
|
||||
|
||||
```php
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
$workspaceMiddleware = function (RequestInterface $request, callable $next): ResponseInterface {
|
||||
if (!$request->hasHeader('anthropic-workspace-id')) {
|
||||
$request = $request->withHeader('anthropic-workspace-id', 'wrkspc_...');
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
};
|
||||
|
||||
$client = new Client(requestOptions: ['middleware' => [$workspaceMiddleware]]);
|
||||
```
|
||||
|
||||
## Raw responses and headers
|
||||
|
||||
`->raw` returns the HTTP response. Its methods take one array of the usual camelCase keys, not named arguments, and `parse()` gives the normal result:
|
||||
|
||||
```php
|
||||
$response = $client->messages->raw->create([
|
||||
'model' => 'claude-opus-5-5',
|
||||
'maxTokens' => 1024,
|
||||
'messages' => [['role' => 'user', 'content' => 'Hello']],
|
||||
]);
|
||||
|
||||
echo $response->getHeaderLine('anthropic-ratelimit-requests-remaining'), "\n";
|
||||
echo $response->getHeaderLine('anthropic-ratelimit-tokens-reset'), "\n";
|
||||
$message = $response->parse();
|
||||
```
|
||||
|
||||
`$client->beta->messages->raw` works the same way, with `'betas'` as a key. There is no `withRawResponse()`. On an error, read the headers from the exception's `$e->response`.
|
||||
|
||||
## List paging
|
||||
|
||||
A list call returns a page, and `foreach` over a page yields pages, not items. Use `pagingEachItem()` to fetch every item, or `getItems()` for the current page only:
|
||||
|
||||
```php
|
||||
foreach ($client->models->list()->pagingEachItem() as $model) {
|
||||
echo $model->id, "\n";
|
||||
}
|
||||
```
|
||||
|
||||
`$client->models->retrieve($id)` fetches one model; its `maxInputTokens` is the context window.
|
||||
@@ -2,12 +2,37 @@
|
||||
|
||||
## Files API
|
||||
|
||||
> **Out of beta.** In current SDKs `$client->beta->files` has breaking shape changes from previous versions, matching the stable `$client->files` - migrate per the Files API row in `shared/live-sources.md`. Example below predates this.
|
||||
> **Out of beta.** Use `$client->files` with no beta header. In current SDKs `$client->beta->files` has breaking shape changes from previous versions, matching the stable `$client->files` - migrate per the Files API row in `shared/live-sources.md`.
|
||||
|
||||
```php
|
||||
$file = $client->beta->files->upload(
|
||||
file: fopen('upload_me.txt', 'r'),
|
||||
betas: ['files-api-2025-04-14'],
|
||||
use Anthropic\Core\FileParam;
|
||||
|
||||
$file = $client->files->upload(
|
||||
file: FileParam::fromResource(fopen('upload_me.txt', 'r'), contentType: 'text/plain'),
|
||||
);
|
||||
|
||||
$message = $client->messages->create(
|
||||
model: 'claude-opus-5-5',
|
||||
maxTokens: 1024,
|
||||
messages: [['role' => 'user', 'content' => [
|
||||
['type' => 'document', 'source' => ['type' => 'file', 'fileID' => $file->id]],
|
||||
['type' => 'text', 'text' => 'Summarize this document.'],
|
||||
]]],
|
||||
);
|
||||
// Reference $file->id as a file content block on ->beta->messages->create().
|
||||
```
|
||||
|
||||
`file:` takes a `FileParam` or a string: a raw `fopen()` handle is a `TypeError`, and a plain string is uploaded as the file's contents, not opened as a path. For content already in memory, use `FileParam::fromString($content, 'name.txt', contentType: 'text/plain')`.
|
||||
|
||||
### Set an expiry
|
||||
|
||||
`expiresInSeconds` sets when a file expires: a whole number of seconds from 3,600 (1 hour) to 7,776,000 (90 days), counted from the upload. It can't be changed later.
|
||||
|
||||
```php
|
||||
$temporary = $client->files->upload(
|
||||
file: FileParam::fromString($content, 'report.txt', contentType: 'text/plain'),
|
||||
expiresInSeconds: 86400,
|
||||
);
|
||||
echo $temporary->expiresAt?->format(DATE_ATOM), "\n";
|
||||
```
|
||||
|
||||
`expiresAt` is `null` for a file with no expiry. Use `$client->files` with no beta header, as here: requests that send `files-api-2025-04-14` don't get this field back. A message that references an expired file fails. Expiry isn't a guaranteed-deletion control: before relying on it for data handling, read File expiration in `https://platform.claude.com/docs/en/build-with-claude/files.md`.
|
||||
|
||||
@@ -23,5 +23,41 @@ foreach ($stream as $event) {
|
||||
}
|
||||
```
|
||||
|
||||
### Tool input and final usage
|
||||
|
||||
Tool input arrives as JSON fragments in `$event->delta->partialJSON` (`JSON` in capitals; any other spelling throws), and can't be parsed until its block ends. Usage in `RawMessageDeltaEvent` is a running total, so read the last value and don't add them up. `MessageAccumulator` does both for you, and `$message->content` then holds parsed input:
|
||||
|
||||
```php
|
||||
use Anthropic\Lib\Streaming\MessageAccumulator;
|
||||
use Anthropic\Messages\InputJSONDelta;
|
||||
use Anthropic\Messages\RawContentBlockDeltaEvent;
|
||||
use Anthropic\Messages\RawContentBlockStartEvent;
|
||||
use Anthropic\Messages\RawContentBlockStopEvent;
|
||||
use Anthropic\Messages\ToolUseBlock;
|
||||
|
||||
$stream = $client->messages->createStream(
|
||||
model: 'claude-opus-5-5',
|
||||
maxTokens: 64000,
|
||||
tools: $tools,
|
||||
messages: [['role' => 'user', 'content' => 'Check the stock level of item A-100']],
|
||||
);
|
||||
|
||||
$accumulator = MessageAccumulator::forMessages(); // for ->beta->messages: forBetaMessages(), and import the Beta-prefixed versions of these classes from Anthropic\Beta\Messages
|
||||
$json = [];
|
||||
foreach ($stream as $event) {
|
||||
$accumulator->accumulate($event);
|
||||
if ($event instanceof RawContentBlockStartEvent && $event->contentBlock instanceof ToolUseBlock) {
|
||||
$json[$event->index] = '';
|
||||
} elseif ($event instanceof RawContentBlockDeltaEvent && $event->delta instanceof InputJSONDelta && isset($json[$event->index])) {
|
||||
$json[$event->index] .= $event->delta->partialJSON;
|
||||
} elseif ($event instanceof RawContentBlockStopEvent && isset($json[$event->index])) {
|
||||
print_r(json_decode($json[$event->index], true)); // the block is complete
|
||||
}
|
||||
}
|
||||
|
||||
$message = $accumulator->message();
|
||||
echo $message->usage->outputTokens, "\n";
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -60,6 +60,36 @@ foreach ($runner as $message) {
|
||||
}
|
||||
```
|
||||
|
||||
### Denying a tool call in the runner
|
||||
|
||||
For human approval, use the manual loop below. If you use the runner, it yields each assistant message before it runs that message's tools. To deny a call, push that message's role and content, then a user message holding one `tool_result` per tool call: the runner sends those and never calls `run`. Without the `tool_result` it runs the tool. Pass each message as its own argument. To replace the whole history instead, call `setMessagesParams(['messages' => $history])`; a bare list is a fatal error.
|
||||
|
||||
```php
|
||||
$runner = $client->beta->messages->toolRunner(
|
||||
maxTokens: 16000,
|
||||
messages: [['role' => 'user', 'content' => 'Email the report to the team']],
|
||||
model: 'claude-opus-5-5',
|
||||
tools: [$sendEmail],
|
||||
maxIterations: 5, // every request counts, denied turns included
|
||||
);
|
||||
|
||||
foreach ($runner as $message) {
|
||||
$toolUses = array_values(array_filter($message->content, fn ($block) => $block->type === 'tool_use'));
|
||||
if ($toolUses === [] || userApproved($toolUses)) {
|
||||
continue; // the runner runs the tools, or the loop ends
|
||||
}
|
||||
$runner->pushMessages(
|
||||
['role' => 'assistant', 'content' => $message->content],
|
||||
['role' => 'user', 'content' => array_map(fn ($block) => [
|
||||
'type' => 'tool_result',
|
||||
'toolUseID' => $block->id,
|
||||
'content' => 'user declined',
|
||||
'isError' => true,
|
||||
], $toolUses)],
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Manual Loop
|
||||
|
||||
Tools are passed as arrays. **The SDK uses camelCase keys** (`inputSchema`, `toolUseID`, `stopReason`) and auto-maps to the API's snake_case on the wire - since v0.5.0. See [shared tool use concepts](../../shared/tool-use-concepts.md) for the loop pattern.
|
||||
@@ -236,20 +266,26 @@ $response = $client->beta->messages->create(
|
||||
);
|
||||
```
|
||||
|
||||
### Cache diagnostics
|
||||
### Cache diagnostics (non-beta)
|
||||
|
||||
Pass the previous response's `id` on the next request; print the `diagnostics` object on the response:
|
||||
Send `diagnostics` on every request: a null previous ID on the first, the previous response's `id` after that. Use `withPreviousMessageID()`: `DiagnosticsParam::with()` drops a null and sends `{}`, and before SDK 1.10.0 a plain array does the same. The result is on `$r2->diagnostics`; null there means no divergence was found.
|
||||
|
||||
```php
|
||||
$r2 = $client->beta->messages->create(
|
||||
use Anthropic\Messages\DiagnosticsParam;
|
||||
|
||||
$r1 = $client->messages->create(
|
||||
model: 'claude-opus-5-5', maxTokens: 1024,
|
||||
diagnostics: ['previousMessageId' => $r1->id],
|
||||
betas: ['cache-diagnosis-2026-04-07'],
|
||||
diagnostics: (new DiagnosticsParam)->withPreviousMessageID(null),
|
||||
messages: [...],
|
||||
);
|
||||
$r2 = $client->messages->create(
|
||||
model: 'claude-opus-5-5', maxTokens: 1024,
|
||||
diagnostics: (new DiagnosticsParam)->withPreviousMessageID($r1->id),
|
||||
messages: [...],
|
||||
);
|
||||
```
|
||||
|
||||
**Anthropic-defined tools** (bash, web_search, text_editor, code_execution) are GA and work on both paths. Of these, web_search and code_execution are server-executed; bash and text_editor are client-executed (you handle the `tool_use` locally) - `Anthropic\Messages\ToolBash20250124` / `WebSearchTool20260209` / `ToolTextEditor20250728` / `CodeExecutionTool20260120` for non-beta, `Anthropic\Beta\Messages\BetaToolBash20250124` / `BetaWebSearchTool20260209` / `BetaToolTextEditor20250728` / `BetaCodeExecutionTool20260120` for beta. No `betas:` header needed for these.
|
||||
**Anthropic-defined tools** (bash, web_search, text_editor, code_execution) are GA and work on both paths. Of these, web_search and code_execution are server-executed; bash and text_editor are client-executed (you handle the `tool_use` locally) - `Anthropic\Messages\ToolBash20250124` / `WebSearchTool20260318` / `ToolTextEditor20250728` / `CodeExecutionTool20260120` for non-beta, `Anthropic\Beta\Messages\BetaToolBash20250124` / `BetaWebSearchTool20260318` / `BetaToolTextEditor20250728` / `BetaCodeExecutionTool20260120` for beta. No `betas:` header needed for these.
|
||||
|
||||
### Tool search (non-beta, server-side)
|
||||
|
||||
|
||||
@@ -119,7 +119,7 @@ $client->beta->sessions->events->send(
|
||||
);
|
||||
```
|
||||
|
||||
> Tip: **Stream-first:** Open the stream *before* (or concurrently with) sending the message. The stream only delivers events that occur after it opens - stream-after-send means early events arrive buffered in one batch. See [Steering Patterns](../../shared/managed-agents-events.md#steering-patterns).
|
||||
> Tip: **Stream-first:** Open the stream *before* sending the message. The stream only delivers events that occur after it opens. See [Steering Patterns](../../shared/managed-agents-events.md#steering-patterns).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -19,6 +19,8 @@ client = anthropic.Anthropic()
|
||||
# Explicit API key (only when you must inject a specific key)
|
||||
client = anthropic.Anthropic(api_key="your-api-key")
|
||||
|
||||
client = anthropic.Anthropic(default_headers={"anthropic-workspace-id": "wrkspc_..."}) # key not scoped to one workspace
|
||||
|
||||
# Async client
|
||||
async_client = anthropic.AsyncAnthropic()
|
||||
```
|
||||
@@ -467,7 +469,7 @@ if fallback_ran and response.stop_reason != "refusal":
|
||||
print(f"Served by {response.model}")
|
||||
```
|
||||
|
||||
A `stop_reason: "refusal"` on the final response means the whole chain refused. This array form takes `server-side-fallback-2026-06-01` or `-2026-07-01`; the `fallbacks: "default"` scalar form needs `-2026-07-01` (see `shared/model-migration.md` -> Migrating to Claude Opus 5 -> New API features). Any other `server-side-fallback-*` value returns a 400. The parameter is rejected on the Batches API and unavailable on Amazon Bedrock, Vertex AI, and Microsoft Foundry - register the client-side `BetaRefusalFallbackMiddleware` on the client there instead. Full semantics (sticky routing, billing, streaming, echoing fallback turns back): `shared/model-migration.md` -> Migrating to Claude Fable 5.1 -> `refusal` stop reason.
|
||||
A `stop_reason: "refusal"` on the final response means the whole chain refused. This array form takes `server-side-fallback-2026-06-01` or `-2026-07-01`; the `fallbacks: "default"` scalar form needs `-2026-07-01` (see `shared/model-migration.md` -> Migrating to Claude Opus 5 -> New API features). Any other `server-side-fallback-*` value returns a 400. The Batches API rejects the parameter. It is unavailable on Amazon Bedrock, Vertex AI and Microsoft Foundry, and the docs don't list it for Claude Platform on AWS - register the client-side `BetaRefusalFallbackMiddleware` on the client there instead. Full semantics (sticky routing, billing, streaming, echoing fallback turns back): `shared/model-migration.md` -> Migrating to Claude Fable 5.1 -> `refusal` stop reason.
|
||||
|
||||
---
|
||||
|
||||
@@ -527,42 +529,3 @@ count_response = client.messages.count_tokens(
|
||||
estimated_input_cost = count_response.input_tokens * 0.000004 # $4/1M tokens
|
||||
print(f"Estimated input cost: ${estimated_input_cost:.4f}")
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Retry with Exponential Backoff
|
||||
|
||||
> **Note:** The Anthropic SDK automatically retries rate limit (429) and server errors (5xx) with exponential backoff. You can configure this with `max_retries` (default: 2). Only implement custom retry logic if you need behavior beyond what the SDK provides.
|
||||
|
||||
```python
|
||||
import time
|
||||
import random
|
||||
import anthropic
|
||||
|
||||
def call_with_retry(
|
||||
client: anthropic.Anthropic,
|
||||
max_retries: int = 5,
|
||||
base_delay: float = 1.0,
|
||||
max_delay: float = 60.0,
|
||||
**kwargs
|
||||
):
|
||||
"""Call the API with exponential backoff retry."""
|
||||
last_exception = None
|
||||
|
||||
for attempt in range(max_retries):
|
||||
try:
|
||||
return client.messages.create(**kwargs)
|
||||
except anthropic.RateLimitError as e:
|
||||
last_exception = e
|
||||
except anthropic.APIStatusError as e:
|
||||
if e.status_code >= 500:
|
||||
last_exception = e
|
||||
else:
|
||||
raise # Client errors (4xx except 429) should not be retried
|
||||
|
||||
delay = min(base_delay * (2 ** attempt) + random.uniform(0, 1), max_delay)
|
||||
print(f"Retry {attempt + 1}/{max_retries} after {delay:.1f}s")
|
||||
time.sleep(delay)
|
||||
|
||||
raise last_exception
|
||||
```
|
||||
|
||||
@@ -79,7 +79,8 @@ for result in client.messages.batches.results(message_batch.id):
|
||||
text = next((b.text for b in msg.content if b.type == "text"), "")
|
||||
print(f"[{result.custom_id}] {text[:100]}")
|
||||
case "errored":
|
||||
if result.result.error.type == "invalid_request":
|
||||
api_error = result.result.error.error
|
||||
if api_error.type == "invalid_request_error":
|
||||
print(f"[{result.custom_id}] Validation error - fix request and retry")
|
||||
else:
|
||||
print(f"[{result.custom_id}] Server error - safe to retry")
|
||||
|
||||
@@ -32,6 +32,20 @@ print(f"File ID: {uploaded.id}")
|
||||
print(f"Size: {uploaded.size_bytes} bytes")
|
||||
```
|
||||
|
||||
### Set an Expiry
|
||||
|
||||
`expires_in_seconds` sets when a file expires: a whole number of seconds from 3,600 (1 hour) to 7,776,000 (90 days), counted from the upload. It can't be changed later.
|
||||
|
||||
```python
|
||||
temporary = client.files.upload(
|
||||
file=Path("report.pdf"),
|
||||
expires_in_seconds=86400,
|
||||
)
|
||||
print(f"Expires at: {temporary.expires_at}")
|
||||
```
|
||||
|
||||
`expires_at` is `None` for a file with no expiry. Use `client.files` with no beta header, as here: requests that send `files-api-2025-04-14` don't get this field back. A message that references an expired file fails. Expiry isn't a guaranteed-deletion control: before relying on it for data handling, read File expiration in `https://platform.claude.com/docs/en/build-with-claude/files.md`.
|
||||
|
||||
---
|
||||
|
||||
## Use a File in Messages
|
||||
@@ -121,6 +135,8 @@ file_content = client.beta.files.download("file_011CNha8iCJcU1wXNR6q4V8w")
|
||||
file_content.write_to_file("output.txt")
|
||||
```
|
||||
|
||||
To read it in memory instead: `file_content.read()` for bytes, `file_content.text()` for text (both are methods).
|
||||
|
||||
---
|
||||
|
||||
## Full End-to-End Example
|
||||
|
||||
@@ -56,6 +56,20 @@ for message in runner:
|
||||
|
||||
For async usage, use `@beta_async_tool` with `async def` functions.
|
||||
|
||||
**In the runner, approval gates go inside the tool.** For human approval, use the manual loop below instead. `runner.append_messages()` and `runner.set_messages_params()` change what is sent next, but the runner still calls the function, so neither stops a call. Leaving the loop with `break` stops it, but the call stays pending: iterating again or `until_done()` runs it, so call `runner.close()` before you leave (`await` it on the async runner; `anthropic` 1.14.0 and later). Check first in the function itself:
|
||||
|
||||
```python
|
||||
@beta_tool
|
||||
def send_email(to: str, body: str) -> str:
|
||||
"""Send an email."""
|
||||
if not user_approved(to):
|
||||
return "user declined"
|
||||
deliver(to, body)
|
||||
return "sent"
|
||||
```
|
||||
|
||||
Calling `generate_tool_call_response()` and then `append_messages()` with its result runs the function twice.
|
||||
|
||||
**Key benefits of the tool runner:**
|
||||
|
||||
- No manual loop - the SDK handles calling tools and feeding results back
|
||||
@@ -65,7 +79,7 @@ For async usage, use `@beta_async_tool` with `async def` functions.
|
||||
|
||||
### Server tools with the tool runner
|
||||
|
||||
The runner's `tools` list accepts raw server-tool definitions (`web_search_20260209`, `web_fetch_20260209`, code execution) alongside decorated tools - pass the literal tool dict; server tools run on Anthropic's servers, so there is no function to implement.
|
||||
The runner's `tools` list accepts raw server-tool definitions (`web_search_20260318`, `web_fetch_20260318`, code execution) alongside decorated tools - pass the literal tool dict; server tools run on Anthropic's servers, so there is no function to implement.
|
||||
|
||||
**`pause_turn`:** a long-running server-tool turn can stop with `stop_reason: "pause_turn"`. From `anthropic` 1.1.0 the runner sends a paused turn back by itself so the server continues it; each resume counts toward `max_iterations`, so a capped run can still end paused - check `stop_reason` on the message `runner.until_done()` returns (or the last one the loop yields). Earlier releases end the loop on a paused turn and return it as the final message, with no error; upgrade, or use the manual loop below, which handles `pause_turn` explicitly.
|
||||
|
||||
@@ -152,7 +166,7 @@ Conversion functions raise `UnsupportedMCPValueError` if an MCP value cannot be
|
||||
|
||||
## Manual Agentic Loop
|
||||
|
||||
Prefer the tool runner above to a manual loop. Drop to a manual loop only when you need control the runner does not expose (e.g., a custom transport, request shapes the SDK cannot build, or avoiding a beta dependency - the runner is beta). Human-in-the-loop approval does *not* require a manual loop - gate inside the tool function (return a "user declined" result) or inspect pending `tool_use` blocks in the `for message in runner:` body and call `runner.set_messages_params()`.
|
||||
For human-in-the-loop approval, custom logging or conditional execution, use the manual loop. If you stay on the runner, put the approval check inside the tool function and return a "user declined" result (see "In the runner, approval gates go inside the tool" above). For everything else, prefer the tool runner, and drop to a manual loop only when you need control the runner does not expose (e.g., a custom transport, request shapes the SDK cannot build, or avoiding a beta dependency - the runner is beta).
|
||||
|
||||
If you do need a manual loop:
|
||||
|
||||
@@ -172,11 +186,12 @@ while True:
|
||||
messages=messages
|
||||
)
|
||||
|
||||
# If Claude is done (no more tool calls), break
|
||||
if response.stop_reason == "end_turn":
|
||||
# Run tools only on tool_use: any other stop can cut a tool call off
|
||||
if response.stop_reason not in ("tool_use", "pause_turn"):
|
||||
break
|
||||
|
||||
# Server-side tool hit iteration limit; append the paused turn and re-send to continue
|
||||
# (once a response has a `container`, send its ID on every later request)
|
||||
if response.stop_reason == "pause_turn":
|
||||
messages.append({"role": "assistant", "content": response.content})
|
||||
continue
|
||||
@@ -201,7 +216,7 @@ while True:
|
||||
messages.append({"role": "user", "content": tool_results})
|
||||
|
||||
# Final response text
|
||||
final_text = next(b.text for b in response.content if b.type == "text")
|
||||
final_text = "".join(b.text for b in response.content if b.type == "text")
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -140,7 +140,7 @@ client.beta.sessions.events.send(
|
||||
)
|
||||
```
|
||||
|
||||
> Tip: **Stream-first:** Open the stream *before* (or concurrently with) sending the message. The stream only delivers events that occur after it opens - stream-after-send means early events arrive buffered in one batch. See [Steering Patterns](../../shared/managed-agents-events.md#steering-patterns).
|
||||
> Tip: **Stream-first:** Open the stream *before* sending the message. The stream only delivers events that occur after it opens. See [Steering Patterns](../../shared/managed-agents-events.md#steering-patterns).
|
||||
|
||||
---
|
||||
|
||||
@@ -340,7 +340,7 @@ for f in files.data:
|
||||
print(f.filename, f.size_bytes)
|
||||
# Download each file and save to disk
|
||||
file_content = client.beta.files.download(f.id)
|
||||
file_content.write_to_file(f.filename)
|
||||
file_content.write_to_file(f.id) # not f.filename: the agent chose it, so it could be a path
|
||||
```
|
||||
|
||||
> Tip: There's a brief indexing lag (~1-3s) between `session.status_idle` and output files appearing in `files.list`. Retry once or twice if the list is empty.
|
||||
|
||||
@@ -20,6 +20,8 @@ client = Anthropic::Client.new
|
||||
client = Anthropic::Client.new(api_key: "your-api-key")
|
||||
```
|
||||
|
||||
A key that isn't scoped to one workspace must name one: pass `workspace_id: "wrkspc_..."` on each `create`.
|
||||
|
||||
---
|
||||
|
||||
## Basic Message Request
|
||||
|
||||
@@ -10,6 +10,25 @@ stream = client.messages.stream(
|
||||
)
|
||||
|
||||
stream.text.each { |text| print(text) }
|
||||
|
||||
message = stream.accumulated_message # waits for the end of the stream
|
||||
puts message.usage.output_tokens # final usage
|
||||
```
|
||||
|
||||
`client.messages.stream` is the way to stream: `client.messages.create(..., stream: true)` raises `ArgumentError`. With beta features, call `client.beta.messages.stream(..., betas: [...])`, which has the same helpers. Call `stream.text` before `stream.accumulated_message`: once the stream is consumed, `stream.text` yields nothing.
|
||||
|
||||
### Tool input
|
||||
|
||||
On a new stream created with `tools:`, `stream.each` yields the raw events plus helper events. Tool input arrives as fragments, and the accumulated message holds it parsed:
|
||||
|
||||
```ruby
|
||||
stream.each do |event|
|
||||
print(event.partial_json) if event.is_a?(Anthropic::Streaming::InputJsonEvent)
|
||||
end
|
||||
|
||||
stream.accumulated_message.content.each do |block|
|
||||
puts block.input if block.type == :tool_use
|
||||
end
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -49,6 +49,34 @@ client.beta.messages.tool_runner(
|
||||
end
|
||||
```
|
||||
|
||||
### Denying a tool call in the runner
|
||||
|
||||
For human approval, use the manual loop below. If you use the runner, `each_message` yields each assistant message before its tools run. To deny a call, pass that message's role and content and a user message holding one `tool_result` per tool call to `runner.feed_messages` (separate arguments, not an array): the runner sends those and never calls the tool. `runner.params[:messages] = ...` does the same, but appending in place with `<<` doesn't, and the tool still runs. `max_iterations:` doesn't count a turn you answered with `feed_messages`, so bound those yourself.
|
||||
|
||||
```ruby
|
||||
runner = client.beta.messages.tool_runner(
|
||||
model: :"claude-opus-5-5",
|
||||
max_tokens: 16000,
|
||||
max_iterations: 5,
|
||||
tools: [SendEmail.new],
|
||||
messages: [{ role: "user", content: "Email the report to the team" }]
|
||||
)
|
||||
|
||||
denied_turns = 0
|
||||
runner.each_message do |message|
|
||||
tool_uses = message.content.select { |block| block.type == :tool_use }
|
||||
next if tool_uses.empty? || user_approved?(tool_uses)
|
||||
break if (denied_turns += 1) > 5
|
||||
|
||||
runner.feed_messages(
|
||||
{ role: "assistant", content: message.content },
|
||||
{ role: "user", content: tool_uses.map { |block|
|
||||
{ type: "tool_result", tool_use_id: block.id, content: "user declined", is_error: true }
|
||||
} }
|
||||
)
|
||||
end
|
||||
```
|
||||
|
||||
### Manual Loop
|
||||
|
||||
See the [shared tool use concepts](../../shared/tool-use-concepts.md) for the tool definition format and agentic loop pattern.
|
||||
|
||||
@@ -113,7 +113,7 @@ client.beta.sessions.events.send_(
|
||||
)
|
||||
```
|
||||
|
||||
> Tip: **Stream-first:** Open the stream *before* (or concurrently with) sending the message. The stream only delivers events that occur after it opens - stream-after-send means early events arrive buffered in one batch. See [Steering Patterns](../../shared/managed-agents-events.md#steering-patterns).
|
||||
> Tip: **Stream-first:** Open the stream *before* sending the message. The stream only delivers events that occur after it opens. See [Steering Patterns](../../shared/managed-agents-events.md#steering-patterns).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Admin API (Organization Management)
|
||||
|
||||
Read this file when the user wants to manage their Anthropic organization programmatically: members and roles, invites, workspaces and workspace members, API keys, rate limit reports, usage and cost reports, service accounts, workload identity federation (WIF), or customer-managed encryption keys (CMEK).
|
||||
Read this file when the user wants to manage their Anthropic organization programmatically: members and roles, invites, workspaces and workspace members, API keys, rate limit reports, usage and cost reports, service accounts, workload identity federation (WIF), or customer-managed encryption keys (CMEK). It also covers user profiles for end customers, which are a separate API (see User Profiles).
|
||||
|
||||
The Admin API lives under `https://api.anthropic.com/v1/organizations/*`. It manages the organization itself - it does not send messages. As of **August 26, 2026** it is available in all seven SDKs (Python, TypeScript, C#, Go, Java, PHP, Ruby) under `client.beta.organization`, and in the `ant` CLI under `ant beta:organization`. Current SDK releases also have endpoints for Claude Enterprise organizations: the Claude Enterprise Analytics API (`.analytics`), RBAC groups and roles (`.rbac_groups`, `.rbac_roles`) and spend limits (`.spend_limits`). Claude Enterprise organizations call them with a scoped key that the primary owner creates in claude.ai with the matching scopes (custom-role reads use `read:members`), not an `sk-ant-admin` key. An early-access preview lets some Console organizations use their admin credential here instead, to set, read, list and delete spend limits on their organization and workspaces. The Usage and Cost Analytics API (`.analytics.usage`, `.analytics.cost`), which is separate from the Claude Enterprise Analytics API though it shares the `.analytics` accessor, serves Console and Claude Enterprise organizations alike: see Usage and Cost Analytics below. The Admin API's older usage and cost reports (`GET /v1/organizations/usage_report/messages`, `GET /v1/organizations/cost_report`) are legacy but still supported, and are **not** in the SDKs - call those with raw HTTP.
|
||||
|
||||
@@ -202,6 +202,30 @@ These roles apply to Claude Console organizations. Claude Enterprise organizatio
|
||||
- **Claude Models on Google Cloud (Anthropic managed):** most of these endpoints are not offered, and Admin API keys don't work there. The usage and cost analytics endpoints and the legacy usage report (`GET /v1/organizations/usage_report/messages`) go through the organization-level base URL (this platform's docs page in `shared/live-sources.md`) with Google Cloud credentials and `roles/claude.admin`, the only predefined role that grants their permissions. There is no legacy cost report. Register, verify and attach CMEK keys in the Claude Console, and manage workspaces there too.
|
||||
- **Claude Enterprise (claude.ai orgs):** members and invites, usage and cost analytics, plus Enterprise-only endpoints (groups and group members, read and write; custom-role reads; spend limits; the Claude Enterprise Analytics API), all called with the scoped claude.ai key described at the top of this file. Current SDK releases have them under `client.beta.organization`.
|
||||
|
||||
## User Profiles (End-Customer Attribution)
|
||||
|
||||
On the Claude API, the `/v1/user_profiles` endpoints take a normal API key, not an Admin API key. If the code serves end customers (a platform, a gateway, or resold API access), register each one once and attribute its requests, so a safety enforcement action can apply to that customer instead of the whole organization. `POST /v1/user_profiles` returns a `uprof_` ID: store it on your customer record, because the call isn't idempotent. Send the ID as the `anthropic-user-profile-id` header on every request for that customer (on Amazon Bedrock, as a top-level `user_profile_id` body field instead, and only on the models and endpoints that take it: elsewhere it can return a 400); the SDKs and the CLI have a `user_profile_id` argument for this, in each SDK's casing. A company that is your customer gets one profile, not one for each person there. Set `access_type: "passthrough"` for a customer that buys API access from you; leave it out (the default is `application`) for a customer that uses your product. Requests with no profile count as your own usage.
|
||||
|
||||
Amazon Bedrock, Vertex AI and Microsoft Foundry don't have these endpoints. Create the profiles in a Claude API organization. Before you send an ID, link your AWS account, Google Cloud project or the organization that holds your Foundry resource to it (on Foundry, only deployments hosted on Anthropic). On Bedrock and Vertex AI a successful response doesn't confirm that the ID matches a profile. Steps, and which Bedrock models and endpoints take the ID: `https://platform.claude.com/docs/en/manage-claude/user-profiles/platforms.md`.
|
||||
|
||||
```python
|
||||
profile = client.user_profiles.create( # TypeScript: client.userProfiles.create
|
||||
name="Example Corp",
|
||||
access_type="passthrough",
|
||||
external_user_details={"reference_id": "cust-123"},
|
||||
)
|
||||
message = client.messages.create(
|
||||
model="claude-opus-5-5",
|
||||
max_tokens=16000,
|
||||
messages=[{"role": "user", "content": "Hello"}],
|
||||
user_profile_id=profile.id,
|
||||
)
|
||||
```
|
||||
|
||||
Full guide: `https://platform.claude.com/docs/en/manage-claude/user-profiles/attribute-requests.md`
|
||||
|
||||
---
|
||||
|
||||
## Live Docs
|
||||
|
||||
| Topic | URL |
|
||||
|
||||
@@ -14,9 +14,9 @@
|
||||
| TypeScript | `npm install @anthropic-ai/aws-sdk` | `import AnthropicAws from "@anthropic-ai/aws-sdk"` -> `new AnthropicAws()` |
|
||||
| Go | `go get github.com/anthropics/anthropic-sdk-go/v2` | `import anthropicaws "github.com/anthropics/anthropic-sdk-go/v2/aws"` -> `anthropicaws.NewClient(ctx, anthropicaws.ClientConfig{})` |
|
||||
| C# | `dotnet add package Anthropic.Aws` | `new AnthropicAwsClient()` |
|
||||
| Java | See SDK repo in `shared/live-sources.md` | See SDK repo in `shared/live-sources.md` |
|
||||
| Ruby | `gem install anthropic aws-sdk-core` | See SDK repo in `shared/live-sources.md` |
|
||||
| PHP | `composer require anthropic-ai/sdk aws/aws-sdk-php` | See SDK repo in `shared/live-sources.md` |
|
||||
| Java | `com.anthropic:anthropic-java-aws`, beside `anthropic-java` at the same version | `import com.anthropic.aws.backends.AwsBackend;` -> `AnthropicOkHttpClient.builder().backend(AwsBackend.fromEnv()).build()` |
|
||||
| Ruby | `gem install anthropic aws-sdk-core` | `Anthropic::AWSClient.new(aws_region: "...", workspace_id: "...")`, or `Anthropic::AWSClient.new` with the two values below in the environment. `AWS` is in capitals: `AwsClient` is a `NameError` |
|
||||
| PHP | `composer require anthropic-ai/sdk aws/aws-sdk-php` | `new Anthropic\Aws\Client(awsRegion: '...', workspaceId: '...')`, or `new Anthropic\Aws\Client()` with the two values below in the environment |
|
||||
| `ant` CLI | See `shared/anthropic-cli.md` -> Install and auth | No client to construct: with the two values below set, `ant` commands other than `ant beta:worker` go to Claude Platform on AWS. A missing workspace ID doesn't throw, so confirm with `ant auth status` |
|
||||
|
||||
After construction, **use the client exactly as you would `Anthropic()`** - `client.messages.create(...)`, `client.beta.sessions.*`, etc., with bare model IDs.
|
||||
|
||||
@@ -25,7 +25,7 @@ Measured expectations below give the direction and rough size of each effect fro
|
||||
- **From history, free**: with Step 1's usage and cost reports, compute the baseline from them - the reports supply the dollars, but the per-task denominator must come from the user or the application's own logs; or roll up the application's own logged `usage` objects per task, not per request - four token counts, each at its own rate: regular input, cache writes (1.25x input for the 5-minute duration, 2x for 1-hour), cache reads (a fraction of base input that differs by model), and output - multiplier structure as published on the pricing page; take the values from it when you fetch the rates, not from memory.
|
||||
- **From a baseline run, paid**: run the project's eval (or, with no eval, replay a representative sample of real requests) and roll up the same way. This spends real API money: state the expected cost - from Step 1's token estimates and live pricing, and "estimated - pending Step 1" is an acceptable first answer - **and get the user's approval before running it.** If the user declines the spend, estimate the baseline from the code and any bill figure they can read off the Console, label it an estimate, and continue.
|
||||
|
||||
**Fetch before you size - this gates every rate and every measured figure in the audit.** Before any dollar amount, multiplier, or published figure is written into the report or into code, fetch two rows from `shared/live-sources.md`: **Pricing** (per-model rates and multipliers) and **Cost Optimization** (current measured expectations and the starting-model recommendation). Fetch both in one turn. When a lever that edits conversation history, `system`, or `tools` (§ 2.2, § 2.3, a model switch) enters the shortlist, also fetch the Preserved thinking page (URL in § 2.1) before proposing its diff, for which models and accounts run the check. Record in the report which pages were fetched and when, so a reader can see it happened, and cite the fetched page beside each figure taken from it. Remembered rates or figures, for any model, are not a source. If a fetch fails, say so in the report. For rates: with Step 1's usage and cost reports, derive effective realized rates by dividing `GET /v1/organizations/analytics/cost` amounts (cents) by `/usage`'s matching token counts over the same range, with both ends on UTC midnights and `ending_at` at or before the earlier of the `data_refreshed_at` values the two endpoints have returned. Group both reads by `model` and `service_tier`, plus `context_window`, `speed` and `inference_geo` where prices differ by them. Group `/cost` also by `token_type`; each of its values is the name of the matching `/usage` field. Drop the `priority` rows: their token cost reads zero. On seat-based Claude Enterprise plans, both endpoints reflect usage credits only; ask the user for rates if you can't derive them. For a model whose prices change with prompt length (the Pricing page's long context pricing), check the derived rate against the Pricing page before using it. Without those reports, ask the user for the current rates. For measured expectations: size them in relative buckets with no figures. Only if none of these is available and the user still wants a number may one appear, and then labeled "unverified - from memory" every place it appears.
|
||||
**Fetch before you size - this gates every rate and every measured figure in the audit.** Before any dollar amount, multiplier, or published figure is written into the report or into code, fetch two rows from `shared/live-sources.md`: **Pricing** (per-model rates and multipliers) and **Cost Optimization** (current measured expectations and the starting-model recommendation). Fetch both in one turn. When a lever that edits conversation history, `system`, or `tools` (§ 2.2, § 2.3, a model switch) enters the shortlist, also fetch the Preserved thinking page (URL in § 2.1) before proposing its diff, for which models run the check and what a failed check does on each. Record in the report which pages were fetched and when, so a reader can see it happened, and cite the fetched page beside each figure taken from it. Remembered rates or figures, for any model, are not a source. If a fetch fails, say so in the report. For rates: with Step 1's usage and cost reports, derive effective realized rates by dividing `GET /v1/organizations/analytics/cost` amounts (cents) by `/usage`'s matching token counts over the same range, with both ends on UTC midnights and `ending_at` at or before the earlier of the `data_refreshed_at` values the two endpoints have returned. Group both reads by `model` and `service_tier`, plus `context_window`, `speed` and `inference_geo` where prices differ by them. Group `/cost` also by `token_type`; each of its values is the name of the matching `/usage` field. Drop the `priority` rows: their token cost reads zero. On seat-based Claude Enterprise plans, both endpoints reflect usage credits only; ask the user for rates if you can't derive them. For a model whose prices change with prompt length (the Pricing page's long context pricing), check the derived rate against the Pricing page before using it. Without those reports, ask the user for the current rates. For measured expectations: size them in relative buckets with no figures. Only if none of these is available and the user still wants a number may one appear, and then labeled "unverified - from memory" every place it appears.
|
||||
|
||||
For counting tokens in prompts and files, see `shared/token-counting.md` (`count_tokens` returns the count without running inference). Sanity-check an estimated baseline against any known monthly bill: divergence usually means multi-turn history growth the single-turn estimate missed.
|
||||
|
||||
@@ -108,9 +108,9 @@ For design and placement - the prefix-match invariant, classifying inputs by sta
|
||||
- **Audit for mid-task cache-breakers**: dynamic content above a breakpoint; changing `thinking` or top-level `effort` between requests (treat either as starting the cache over - `shared/prompt-caching.md` § Invalidation hierarchy); setting or changing a structured-output format; switching `speed`; changing a task budget mid-task; every context-editing pass; a thinking block the API drops (the messages cache changes from that block onward); switching models mid-conversation (caches are per-model).
|
||||
- **Not breakers, and where to put a change that is one**: setting effort explicitly to the model's default is the same as omitting it; a per-message effort change keeps the cache only where the model and the `thinking` setting the code sends both accept it, and returns a 400 otherwise (which models and settings: the **Per-message Effort** URL in `shared/live-sources.md`); and most edits to `system` or `tools` have an append-only form that keeps the prefix: a mid-conversation system message (a `role: "system"` message inside `messages`) instead of editing `system`, `tool_addition` / `tool_removal` blocks instead of editing `tools`, and a turn-scoped reminder (`clear_at`) for text that should not persist. The table in `shared/prompt-caching.md` § Invalidation hierarchy lists each with its model availability. When a model or top-level effort change is wanted anyway, make it where the cache is already going to break: on the first request after a compaction (not the one that triggers it), or between conversations.
|
||||
- **On models that run the preserved-thinking check, an edit to `system`, `tools`, or earlier messages breaks the model's earlier reasoning as well as the cache.** Each thinking block is tied to the conversation that produced it, and the edits that invalidate it are the same edits that restart the cache, so one discipline serves both: keep `system` and `tools` fixed for the session and treat `messages` as append-only. `cache_control` markers, `effort`, `max_tokens`, and `tool_choice` are outside the check. A diff that moves content out of `system` or `tools` is still an edit for conversations in flight when it deploys: have the diff keep sending the stored `system` and `tools` bytes to those conversations and the new bytes to new conversations only. Where the harness cannot do that, say in the report that in-flight conversations take one cold miss and, where the check is enforced, are rejected until their thinking blocks are dropped (next bullet).
|
||||
- **What an invalid edit costs**: by default the request is rejected where the check is enforced. Opting into dropping the failing blocks instead (the Preserved thinking page has the field, and the beta header that both it and the response's list of dropped blocks need) leaves them unbilled, but the session can still cost more, because the model may think again to rebuild them. Which models and accounts are checked changes with releases - read it from that page (`https://platform.claude.com/docs/en/build-with-claude/preserved-thinking/prefix-checks.md`), never from this guide - and hand off to the `preserved-thinking-migration` subcommand (`shared/preserved-thinking-migration.md`) to find and fix a harness's edits.
|
||||
- **What an invalid edit costs**: by default the request is rejected where the check is enforced. Opting into dropping the failing blocks instead (the Preserved thinking page has the field, and the beta header that both it and the response's list of dropped blocks need) leaves them unbilled, but the session can still cost more, because the model may think again to rebuild them. Which models are checked and what a failed check does change with releases - read it from that page (`https://platform.claude.com/docs/en/build-with-claude/preserved-thinking/prefix-checks.md`), never from this guide - and hand off to the `preserved-thinking-migration` subcommand (`shared/preserved-thinking-migration.md`) to find and fix a harness's edits.
|
||||
- **Short prefixes**: the minimum cacheable prefix is per-model, so after any model change re-check whether a short prompt still caches, or now does - table in `shared/prompt-caching.md` § API reference.
|
||||
- **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 (the Cost Optimization page gives the current bar for how much of its input a healthy loop reads from the cache). 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 where the platform has it (availability in `shared/platform-availability.md`): include a `diagnostics` object on every request (`previous_message_id: null` on the first, the previous response's `id` after that), and the response's `diagnostics` object names where the two requests diverged - no payload logging needed. `shared/prompt-caching.md` § Verifying cache hits also sends a beta header on every request; the Cache diagnostics page (`https://platform.claude.com/docs/en/build-with-claude/cache-diagnostics.md`) says that header is no longer required, that requests that still send it work as before, and that the `diagnostics` object is the opt-in, so a harness that already sends the header can keep it, and every request needs the object either way. That page has the current shape. On other platforms, fall back to the payload-diff method in the same section.
|
||||
- **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 (the Cost Optimization page gives the current bar for how much of its input a healthy loop reads from the cache). 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 where the platform has it (availability in `shared/platform-availability.md`): include a `diagnostics` object on every request (`previous_message_id: null` on the first, the previous response's `id` after that), and the response's `diagnostics` object names where the two requests diverged - no payload logging needed. The Cache diagnostics page (`https://platform.claude.com/docs/en/build-with-claude/cache-diagnostics.md`) has the current shape. On other platforms, fall back to the payload-diff method in `shared/prompt-caching.md` § Verifying cache hits.
|
||||
- **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
|
||||
@@ -123,6 +123,7 @@ Send the model what the task needs, let it fetch the rest. Each sub-lever has a
|
||||
- **Images and PDFs at full resolution** -> pre-downscale to what the task needs. Vision inputs are tokenized by pixel area at roughly one token per 28×28 patch, so cost scales with resolution, not information content; 1280×720 is a safe default that caps an image near 1,200 tokens (current formula - verify via the Vision docs in `shared/live-sources.md`).
|
||||
- **Large tables and artifacts inlined** -> Files API plus code execution: mount the file, let the model compute in the sandbox, and only the answer enters context. Skip when there is nothing to extract or compute - the sandbox round-trip only adds tokens (and sandbox container time bills hourly beyond a free allowance).
|
||||
- **Fetched web pages** -> dynamic filtering in the web fetch tool keeps boilerplate out of the context.
|
||||
- **The same passage printed more than once in one search result** (one list per sub-query) -> print each passage once, tagged with the queries that returned it, and keep the label the model cites it by. Don't swap a repeat for a pointer ("already shown above"): the model may search again or drop facts it needed. Leave results from earlier turns as they are. Skip when repeats are a small share of input tokens.
|
||||
- **Chained tool calls whose intermediates don't matter** -> programmatic tool calling runs the calls from code so only the filtered result enters context; its documentation reports 24% fewer input tokens on agentic search benchmarks, with a higher score.
|
||||
- **Broad data-dump tools** -> prefer narrow accessors (`get_policy(claim_id)` over `get_all_policies()`), and give list tools `limit`/`fields`/`date_range` parameters.
|
||||
- **Unbounded user-supplied input** -> the token-counting endpoint as an ingestion gate (`shared/token-counting.md`): count first, then truncate, summarize, or route oversize payloads to the Files API.
|
||||
@@ -172,7 +173,7 @@ From here down, every lever trades capability for cost. Sweep on the eval, one c
|
||||
- **Re-run failures at higher effort** - when the workload has a usable failure signal (tests, a checker, a validator). Run everything at a low setting and re-run only the failures at a higher one: in Anthropic's coding runs this held the pass rate of running everything at the higher setting, or slightly beat it, for a little over half the cost, counting the failed cheap attempts. Use this for the saving, not the lift, and price in the checker and the doubled wall-clock on failures.
|
||||
- **Vary effort between user turns** when the sweep's curve is mixed: run routine user turns at the lower setting and raise effort only for the ones that need it. Use the per-message form, which keeps the cached prefix (where it's accepted, when a change takes effect and how long it holds: the **Per-message Effort** URL in `shared/live-sources.md`). Something has to decide which turns are hard: the task type where the application knows it, or a classifier, whose own cost and mistakes count. Validate it on the eval like any other tradeoff.
|
||||
- **Tell the model that time matters, and show it the elapsed time**, when wall-clock time matters: the published runs finished sooner and cost less per task for a small score cost. Append the clock as a new message after the newest user message (a mid-conversation system message where the model accepts one), never by rewriting `system` - recipe and figures: the Cost Optimization URL in `shared/live-sources.md`. Validate it like any other tradeoff.
|
||||
- **Task budgets** (the model sees the budget and paces itself - this is the budget control that saves money): set from the loop's 90th-percentile token usage, then tighten. The budget is advisory - it steers the model rather than stopping it - so verify adherence on the workload. Measured on coding: pass rate fell a few points as the budget tightened while cost per task fell by a much larger share - budgets bought efficiency at a price in pass rate that grows as they tighten. Budgets below the documented floor are rejected; very tight budgets can produce refusal-like behavior; set the budget once on the first request - a mid-task change invalidates the cache. Check model availability before wiring it in (beta, and not available on every current model) - parameter shape, the streaming requirement, and supported models are in this skill's SKILL.md -> Task Budgets (Quick Reference) and `shared/model-migration.md` -> Task Budgets.
|
||||
- **Task budgets** (the model sees the budget and paces itself - this is the budget control that saves money): start from the 99th percentile of per-task token spend without a budget, then test up or down. The budget is advisory - it steers the model rather than stopping it - so verify adherence on the workload. Measured on coding: pass rate fell a few points as the budget tightened while cost per task fell by a much larger share - budgets bought efficiency at a price in pass rate that grows as they tighten. Budgets below the documented floor are rejected; very tight budgets can produce refusal-like behavior; set the budget once on the first request - a mid-task change invalidates the cache. Check model availability before wiring it in (beta, and not available on every current model) - parameter shape, the streaming requirement, and supported models are in this skill's SKILL.md -> Task Budgets (Quick Reference) and `shared/model-migration.md` -> Task Budgets.
|
||||
- **Backstops that don't save per-task money but cap the damage**: a Managed Agents session budget is a hard dollar stop; a workspace spend limit is the final backstop on the whole workspace.
|
||||
|
||||
### 2.7 Model selection - last, deliberately
|
||||
|
||||
@@ -126,8 +126,8 @@ Some 400 errors are specifically related to parameter validation:
|
||||
- **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. On the Claude API, 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 Haiku 5.5:** `thinking: {type: "enabled", budget_tokens: N}`, a non-default `temperature` / `top_p` (and any `top_k`; on API version `2026-10-21`, any value of any of the three), and an assistant prefill each return 400 (Claude Haiku 4.5 accepts `budget_tokens` and prefill on every API version, and the sampling parameters only on `2023-06-01`); a `fallbacks` list returns 400 (no server-side fallback); `thinking: {type: "disabled"}` returns 400 when `effort` is `xhigh` or `max` - it is accepted at `high` or below - and a per-message effort change with thinking off returns 400; on the Claude API and Google Cloud a `tools` entry of type `computer_20250124` returns 400 - send `computer_toolset_20260801`. See `shared/model-migration.md` -> Migrating to Claude Haiku 5.5.
|
||||
- **Claude Fable 5.2 / Claude Mythos 5.2 / Claude Fable 5.1 / Claude Mythos 5.1 / Claude Opus 5.5 / Claude Sonnet 5.5:** `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 Sonnet 5.5:** `thinking: {type: "disabled"}` returns 400 `To turn thinking off on this model, send "thinking": {"type": "between_tools"} instead of {"type": "disabled"}. The model does not think before responding. The short updates it writes between tool calls come back as thinking blocks.` - send `{type: "between_tools"}` to turn thinking off, or leave thinking on at a lower effort. `between_tools` has its own 400s: at effort `xhigh` / `max` (`output_config.effort 'xhigh' is not supported when thinking is disabled on this model. Use effort 'high' or below, or enable thinking.`), with `display`, `budget_tokens`, or `block_binding` beside it, on a per-message effort change (`messages.N: output_config.effort 'low' differs from the 'high' in effect before it; ...`), and on any other model (`"thinking.type.between_tools" is not supported for this model.`). On the Claude API and Google Cloud a `computer_20251124` tool returns 400 `'claude-sonnet-5-5' does not support tool types: computer_20251124.` - declare `{type: "computer_toolset_20260801"}` (Amazon Bedrock still accepts the earlier tool). An advisor tool `model` of Claude Opus 4.8, Claude Opus 4.7, Claude Opus 4.6, Claude Sonnet 5, or Sonnet 4.6 returns 400 with a Claude Sonnet 5.5 executor. The history-editing check in the next bullet also applies to Claude Sonnet 5.5 thinking blocks - enforced by default for new accounts - and `block_binding` is accepted only with thinking on. See `shared/model-migration.md` -> Migrating to Claude Sonnet 5.5.
|
||||
- **Claude Fable 5.2 / Claude Mythos 5.2 / Claude Fable 5.1 / Claude Mythos 5.1 / Claude Opus 5.5 - preserved thinking / history-editing check (every account on Claude Fable 5.2 and Claude Mythos 5.2, and on Claude Mythos 5.1 on the Claude API, Vertex and Foundry, though not by default on Amazon Bedrock; on the others, 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` (the beta is available on the Claude API, Claude Platform on AWS, Bedrock, and Vertex; Foundry unconfirmed - `shared/platform-availability.md`; 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 Sonnet 5.5:** `thinking: {type: "disabled"}` returns 400 `To turn thinking off on this model, send "thinking": {"type": "between_tools"} instead of {"type": "disabled"}. The model does not think before responding. The short updates it writes between tool calls come back as thinking blocks.` - send `{type: "between_tools"}` to turn thinking off, or leave thinking on at a lower effort. `between_tools` has its own 400s: at effort `xhigh` / `max` (`output_config.effort 'xhigh' is not supported when thinking is disabled on this model. Use effort 'high' or below, or enable thinking.`), with `display`, `budget_tokens`, or `block_binding` beside it, on a per-message effort change (`messages.N: output_config.effort 'low' differs from the 'high' in effect before it; ...`), and on any other model (`"thinking.type.between_tools" is not supported for this model.`). On the Claude API and Google Cloud a `computer_20251124` tool returns 400 `'claude-sonnet-5-5' does not support tool types: computer_20251124.` - declare `{type: "computer_toolset_20260801"}` (Amazon Bedrock still accepts the earlier tool). An advisor tool `model` of Claude Opus 4.8, Claude Opus 4.7, Claude Opus 4.6, Claude Sonnet 5, or Sonnet 4.6 returns 400 with a Claude Sonnet 5.5 executor. The history-editing check in the next bullet also applies to Claude Sonnet 5.5 thinking blocks (with `prefix_mismatch_behavior` unset, a request that fails it might or might not get the 400), and `block_binding` is accepted only with thinking on. See `shared/model-migration.md` -> Migrating to Claude Sonnet 5.5.
|
||||
- **Claude Fable 5.2 / Claude Mythos 5.2 / Claude Fable 5.1 / Claude Mythos 5.1 / Claude Opus 5.5 - preserved thinking / history-editing check (every account on Claude Fable 5.2 and Claude Mythos 5.2, and on Claude Mythos 5.1 on the Claude API, Vertex and Foundry; on the others, always when `prefix_mismatch_behavior` is `"error"`, and possibly when it is unset (on Bedrock and Vertex, that possible 400 applies to accounts and projects that first used Claude there on or after August 31, 2026; earlier ones might or might not get it)):** ``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. Account age doesn't rule this out, and the fix is the same work on every account. Retrying the same body never clears it; `count_tokens` can return the same 400. (In the Message Batches API the *unset* default drops the failing blocks or, on some models, can let them through, 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` (the beta is available on the Claude API, Claude Platform on AWS, Bedrock, and Vertex; Foundry unconfirmed - `shared/platform-availability.md`; 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):**
|
||||
|
||||
@@ -152,10 +152,10 @@ thinking: budget_tokens=10000, max_tokens=16000
|
||||
**Headers to check:**
|
||||
|
||||
- `retry-after`: Seconds to wait before retrying
|
||||
- `x-ratelimit-limit-*`: Your limits
|
||||
- `x-ratelimit-remaining-*`: Remaining quota
|
||||
- `anthropic-ratelimit-*-limit`: Your limits
|
||||
- `anthropic-ratelimit-*-remaining`: Remaining quota
|
||||
|
||||
**Fix:** The Anthropic SDKs automatically retry 429 and 5xx errors with exponential backoff (default: `max_retries=2`). For custom retry behavior, see the language-specific error handling examples.
|
||||
**Fix:** The Anthropic SDKs automatically retry 429 and 5xx errors with exponential backoff (default: `max_retries=2`).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -293,8 +293,10 @@ async function withBackoff(fn, retry, deadline = Infinity, tries = 5) {
|
||||
}
|
||||
try { return await fn(); } catch (e) {
|
||||
const status = e?.status ?? e?.response?.status;
|
||||
// An error event in a stream has no useful status, so read its type. Never match the message.
|
||||
const type = e?.type ?? e?.error?.error?.type ?? e?.error?.type;
|
||||
const transient = status === 429 || status === 529 || (status >= 500 && status < 600)
|
||||
|| /overloaded|rate.?limit/i.test(String(e?.message ?? ''));
|
||||
|| ['rate_limit_error', 'overloaded_error', 'api_error', 'timeout_error'].includes(type);
|
||||
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 -
|
||||
|
||||
@@ -42,7 +42,7 @@ After construction, call the client as you would `Anthropic()` - `client.message
|
||||
| Value | Env var | Notes |
|
||||
|---|---|---|
|
||||
| Project ID | `ANTHROPIC_GOOGLE_CLOUD_PROJECT`, then `GOOGLE_CLOUD_PROJECT` | If neither is set, the project that Application Default Credentials reports, when the credential type carries one. |
|
||||
| Workspace ID | `ANTHROPIC_GOOGLE_CLOUD_WORKSPACE_ID` | Required unless you set the base URL (`ANTHROPIC_GOOGLE_CLOUD_BASE_URL`): without either, the client raises an error. Organization-level routes (paths starting `/v1/organizations/`) don't need it. Starts with `wrkspc_`. In the Claude Console, under Settings > Workspaces; a developer without Console access must ask someone who has it. |
|
||||
| Workspace ID | `ANTHROPIC_GOOGLE_CLOUD_WORKSPACE_ID` | Required unless you set the base URL (`ANTHROPIC_GOOGLE_CLOUD_BASE_URL`): without either, the client raises an error. Organization-level routes (paths starting `/v1/organizations/`) and user profile routes (`/v1/user_profiles`) don't need it. Starts with `wrkspc_`. In the Claude Console, under Settings > Workspaces; a developer without Console access must ask someone who has it. |
|
||||
| Location | `ANTHROPIC_GOOGLE_CLOUD_LOCATION` | Defaults to `global`. Leave it there. |
|
||||
|
||||
A value passed to the constructor wins over the environment: `project` and `workspace_id` in Python and Ruby, `project` and `workspaceId` in TypeScript and PHP, `Project` and `WorkspaceID` in Go, `.project()` and `.workspaceId()` on `GoogleCloudBackend.builder().fromEnv()` in Java, `Project` and `WorkspaceId` on `GoogleCloudClientOptions` in C#.
|
||||
|
||||
205
skills/claude-api/shared/harness-audit.md
Normal file
205
skills/claude-api/shared/harness-audit.md
Normal file
File diff suppressed because one or more lines are too long
@@ -55,7 +55,7 @@ This file lists the URLs of the current docs on platform.claude.com and of the S
|
||||
| --- | --- | --- |
|
||||
| Create a Message | `https://platform.claude.com/docs/en/api/messages/create.md` | "Extract the response fields, the usage object including cache and thinking token counts, stop reasons, and the streaming event types" |
|
||||
| Batch Processing | `https://platform.claude.com/docs/en/build-with-claude/batch-processing.md` | "Extract batch API endpoints, request format, and polling for results" |
|
||||
| Files API | `https://platform.claude.com/docs/en/build-with-claude/files.md` | "Extract file upload, download, referencing in messages, supported types, and the migration steps from files-api-2025-04-14" |
|
||||
| Files API | `https://platform.claude.com/docs/en/build-with-claude/files.md` | "Extract file upload, download, expiration (expires_in_seconds), referencing in messages, supported types, and the migration steps from files-api-2025-04-14" |
|
||||
| Token Counting | `https://platform.claude.com/docs/en/build-with-claude/token-counting.md` | "Extract token counting API usage and examples" |
|
||||
| Rate Limits | `https://platform.claude.com/docs/en/api/rate-limits.md` | "Extract current rate limits by tier and model" |
|
||||
| Usage and Cost Analytics API | `https://platform.claude.com/docs/en/manage-claude/usage-cost-analytics-api.md` | "Extract the usage and cost endpoints, the beta header, credentials for each organization type and platform, dimensions and filters, date-range and time-bucket limits, data freshness, and the migration table from the legacy reports" |
|
||||
@@ -129,7 +129,7 @@ Use these when a managed-agents binding, behavior, or wire-level detail isn't co
|
||||
| Define Outcomes | `https://platform.claude.com/docs/en/managed-agents/define-outcomes.md` | "Extract outcome definitions, evaluation hooks, and success criteria configuration" |
|
||||
| Sessions | `https://platform.claude.com/docs/en/managed-agents/sessions.md` | "Extract session lifecycle, status transitions, idle/terminated semantics, and resume rules" |
|
||||
| Environments | `https://platform.claude.com/docs/en/managed-agents/environments.md` | "Extract environment config (cloud/networking), management endpoints, and reuse model" |
|
||||
| Self-Hosted Sandboxes | `https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes.md` | "Extract config:{type:self_hosted}, ANTHROPIC_ENVIRONMENT_KEY, EnvironmentWorker.run/handle_item, environments.work.poller(drain), beta_agent_toolset, ant beta:worker poll/run, webhook-driven wake, memory stores (ANTHROPIC_WORK_SECRET, memory_sync_interval/memory_sync_deletes)" |
|
||||
| Self-Hosted Sandboxes | `https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes.md` | "Extract config:{type:self_hosted}, ANTHROPIC_ENVIRONMENT_KEY, EnvironmentWorker.run/handle_item, environments.work.poller(drain), beta_agent_toolset, ant beta:worker poll/run, webhook-driven wake, memory stores (ANTHROPIC_WORK_SECRET, memory_sync_interval/memory_sync_deletions)" |
|
||||
| Self-Hosted Sandboxes - Security | `https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-security.md` | "Extract what the customer owns (hardening, egress, key custody, trust boundaries) vs what Anthropic cannot do" |
|
||||
| Events and Streaming | `https://platform.claude.com/docs/en/managed-agents/events-and-streaming.md` | "Extract event stream types, stream-first ordering, reconnect/dedupe, and steering patterns" |
|
||||
| Tools | `https://platform.claude.com/docs/en/managed-agents/tools.md` | "Extract built-in toolset, custom tool definitions, and tool result wire format" |
|
||||
|
||||
@@ -188,7 +188,7 @@ Individual text documents inside a store (<= 100KB each). `create` creates at a
|
||||
| `GET` | `/v1/memory_stores/{memory_store_id}/memories` | ListMemories | Returns `Memory \| MemoryPrefix`; filter by `path_prefix`, `depth` |
|
||||
| `POST` | `/v1/memory_stores/{memory_store_id}/memories` | CreateMemory | Create at `path` (SDK: `memories.create`); `409 memory_path_conflict_error` if occupied |
|
||||
| `GET` | `/v1/memory_stores/{memory_store_id}/memories/{memory_id}` | GetMemory | Read one memory (defaults to `view="full"`) |
|
||||
| `PATCH` | `/v1/memory_stores/{memory_store_id}/memories/{memory_id}` | UpdateMemory | Change `content`, `path`, or both by ID; optional `precondition` |
|
||||
| `POST` | `/v1/memory_stores/{memory_store_id}/memories/{memory_id}` | UpdateMemory | Change `content`, `path`, or both by ID; optional `precondition` |
|
||||
| `DELETE` | `/v1/memory_stores/{memory_store_id}/memories/{memory_id}` | DeleteMemory | Delete (optional `expected_content_sha256`) |
|
||||
|
||||
## Memory Versions
|
||||
@@ -423,13 +423,13 @@ Include the `request_id` when reporting issues to Anthropic - it lets us trace t
|
||||
| 401 | `authentication_error` | Invalid or missing API key |
|
||||
| 403 | `permission_error` | The API key doesn't have permission for this operation |
|
||||
| 404 | `not_found_error` | The requested resource doesn't exist |
|
||||
| 409 | `invalid_request_error` | The request conflicts with the resource's current state (e.g., sending to an archived session) |
|
||||
| 409 | `conflict_error` | The request conflicts with the resource's current state (e.g., updating an agent with a stale `version`) |
|
||||
| 413 | `request_too_large` | The request body exceeds the maximum allowed size |
|
||||
| 429 | `rate_limit_error` | Too many requests - check rate limit headers for retry timing |
|
||||
| 500 | `api_error` | An internal server error occurred |
|
||||
| 529 | `overloaded_error` | The service is temporarily overloaded - retry with backoff |
|
||||
|
||||
Note that `409 Conflict` carries `error.type: "invalid_request_error"` (there is no separate `conflict_error` type); inspect both the HTTP status and the `message` to distinguish conflicts from other invalid requests.
|
||||
Detect a conflict by HTTP status 409, never by `message`, whose text can change.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -166,8 +166,6 @@ await client.beta.sessions.events.send(session.id, {
|
||||
for await (const event of stream) { /* ... */ }
|
||||
```
|
||||
|
||||
The `Promise.all([stream, send])` shape works too, but stream-first is simpler and has the same effect - the stream starts buffering the moment it's opened.
|
||||
|
||||
---
|
||||
|
||||
## 8. File-mount gotchas
|
||||
|
||||
@@ -140,18 +140,16 @@ Practical patterns for driving a session via the events surface.
|
||||
|
||||
### Stream-first ordering
|
||||
|
||||
**Open the stream before sending events.** The stream only delivers events that occur *after* it's opened - it does not replay current state or historical events. If you send a message first and open the stream second, early events (including fast status transitions) arrive buffered in a single batch and you lose the ability to react to them in real time.
|
||||
**Open the stream before sending events.** The stream only delivers events that occur *after* it's opened - it does not replay current state or historical events. If you send a message first and open the stream second, events emitted before it opens (including fast status transitions) never arrive on that stream; list the session's events to read them.
|
||||
|
||||
```ts
|
||||
// Correct - stream and send concurrently
|
||||
const [response] = await Promise.all([
|
||||
streamEvents(sessionId), // opens SSE connection
|
||||
sendMessage(sessionId, text),
|
||||
]);
|
||||
|
||||
// Wrong - events before stream opens arrive as a single buffered batch
|
||||
// Correct - open the stream, then send
|
||||
const stream = await openStream(sessionId); // opens SSE connection
|
||||
await sendMessage(sessionId, text);
|
||||
const response = await streamEvents(sessionId);
|
||||
|
||||
// Wrong - events emitted before the stream opens never arrive on it
|
||||
await sendMessage(sessionId, text);
|
||||
const stream = await openStream(sessionId);
|
||||
```
|
||||
|
||||
**For full history,** use `GET /v1/sessions/{id}/events` (paginated list) - the stream only gives you live events from connection onward.
|
||||
@@ -188,11 +186,12 @@ def connect_with_consolidation(client, session_id):
|
||||
**You don't have to wait for a response before sending the next message.** User events are queued server-side and processed in order. This is useful for chat bridges where the user sends rapid follow-ups:
|
||||
|
||||
```ts
|
||||
const stream = await openStream(sessionId);
|
||||
// All three go into one session; agent processes them in order
|
||||
await sendMessage(sessionId, "Summarize the README");
|
||||
await sendMessage(sessionId, "Actually also check the CONTRIBUTING guide");
|
||||
await sendMessage(sessionId, "And compare the two");
|
||||
// Stream once - agent responds to all three as a coherent turn
|
||||
// Read that stream - agent responds to all three as a coherent turn
|
||||
```
|
||||
|
||||
Events can be sent up to the Session at any time. There is no need to wait on a specific session status to enqueue new events via `client.beta.sessions.events.send()`. Two exceptions: while a call is waiting on you (`stop_reason: requires_action`) or the session is paused at its budget (`budget_reached`), only settle events are accepted - a `user.message` there is a 400. See § Reaching a session budget.
|
||||
|
||||
@@ -193,7 +193,7 @@ See `shared/managed-agents-api-reference.md` -> Memory Stores / Memories / Memor
|
||||
POST /v1/memory_stores
|
||||
POST /v1/memory_stores/{memory_store_id}/archive
|
||||
GET /v1/memory_stores/{memory_store_id}/memories
|
||||
PATCH /v1/memory_stores/{memory_store_id}/memories/{memory_id}
|
||||
POST /v1/memory_stores/{memory_store_id}/memories/{memory_id}
|
||||
GET /v1/memory_stores/{memory_store_id}/memory_versions
|
||||
POST /v1/memory_stores/{memory_store_id}/memory_versions/{version_id}/redact
|
||||
```
|
||||
|
||||
@@ -162,9 +162,10 @@ TypeScript: same shape with `client.beta.webhooks.unwrap(body, {headers})`, `cli
|
||||
| `ANTHROPIC_SESSION_ID` | `work.data.id` |
|
||||
| `ANTHROPIC_WORK_ID` | `work.id` |
|
||||
| `ANTHROPIC_ENVIRONMENT_ID` | `work.environment_id` |
|
||||
| `ANTHROPIC_ENVIRONMENT_KEY` | pass through |
|
||||
| `ANTHROPIC_BASE_URL` | pass through |
|
||||
| `ANTHROPIC_WORK_SECRET` | `work.secret` - the per-session credential the worker inside needs to mount memory stores. `ant beta:worker poll --on-work` does **not** set it for the spawned script; read it from the work-item JSON on stdin (`jq -r '.secret // empty'`) and pass it in. Only into the sandbox serving that session; never log it. |
|
||||
| `ANTHROPIC_WORK_SECRET` | `work.secret` - the per-session credential the worker inside uses, for memory stores too. `ant beta:worker poll --on-work` does **not** set it for the spawned script; read it from the work-item JSON on stdin (`jq -r '.secret // empty'`) and pass it in. Only into the sandbox serving that session; never log it. |
|
||||
|
||||
Do **not** pass `ANTHROPIC_ENVIRONMENT_KEY` into the container: it gives access to every session in the environment. The worker runs on the secret alone (`ant` CLI 1.32.0, Python SDK 1.5.0, TypeScript SDK 0.125.0, Go SDK 1.72.0 or later). If its error asks for the environment key, check the version and the secret instead.
|
||||
|
||||
Skip items where `work.data.type != "session"` when you dispatch containers yourself (`handle_item` does this check for you).
|
||||
|
||||
@@ -198,20 +199,20 @@ ANTHROPIC_WORK_SECRET="$(jq -r '.secret // empty')"
|
||||
export ANTHROPIC_WORK_SECRET
|
||||
exec docker run --rm \
|
||||
-e ANTHROPIC_SESSION_ID -e ANTHROPIC_WORK_ID -e ANTHROPIC_ENVIRONMENT_ID \
|
||||
-e ANTHROPIC_ENVIRONMENT_KEY -e ANTHROPIC_BASE_URL -e ANTHROPIC_WORK_SECRET \
|
||||
-e ANTHROPIC_BASE_URL -e ANTHROPIC_WORK_SECRET \
|
||||
my-sdk-worker-image
|
||||
```
|
||||
|
||||
The per-session entrypoint is a few lines - no arguments needed, `handle_item()` reads the forwarded `ANTHROPIC_*` vars including `ANTHROPIC_WORK_SECRET`; wire signals to cancellation so a stopped container still uploads:
|
||||
|
||||
```python
|
||||
import asyncio, contextlib, os, signal
|
||||
import asyncio, contextlib, signal
|
||||
from anthropic import AsyncAnthropic
|
||||
from anthropic.lib.environments import EnvironmentWorker
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
async with AsyncAnthropic(auth_token=os.environ["ANTHROPIC_ENVIRONMENT_KEY"]) as client:
|
||||
async with AsyncAnthropic() as client: # no credential here: the worker uses the work secret
|
||||
task = asyncio.create_task(EnvironmentWorker(client, workdir="/workspace").handle_item())
|
||||
loop = asyncio.get_running_loop()
|
||||
for signum in (signal.SIGINT, signal.SIGTERM):
|
||||
@@ -232,9 +233,9 @@ The image needs a writable `/mnt/memory`; the memory directories need **not** be
|
||||
| Option | Python / TypeScript / Go | Behavior |
|
||||
|---|---|---|
|
||||
| Sync interval | `memory_sync_interval` (seconds) / `memorySyncIntervalMs` (ms) / `MemorySyncInterval` (duration) | Default 15 s, minimum 5 s. Shorter narrows the stale window at the cost of more memory-store requests. `None` / `null` / negative duration **disables memory support entirely** - stores are neither downloaded nor synced, and a session with stores attached runs without them even though its system prompt still describes them. Only disable on workers whose sessions never attach stores. While enabled, a work item that arrives without a `secret` for a session with stores **fails** rather than running memory-less. |
|
||||
| Delete propagation | `memory_sync_deletes` / `memorySyncDeletes` / `MemorySyncDeletes` | `"enabled"` (default - deletes from the store once a later sync confirms the file is still gone), `"log_only"` (same checks, only logs what it would delete - use to audit before trusting `enabled`), `"disabled"` (never deletes from the store). Go: `environments.MemorySyncDeletesEnabled` (zero value) / `LogOnly` / `Disabled`. Uploads/downloads are unaffected. |
|
||||
| Delete propagation | `memory_sync_deletions` / `memorySyncDeletions` / `MemorySyncDeletions` | `"enabled"` (default - deletes from the store once a later sync confirms the file is still gone), `"log_only"` (same checks, only logs what it would delete - use to audit before trusting `enabled`), `"disabled"` (never deletes from the store). Go: `environments.MemorySyncDeletionsEnabled` (zero value) / `LogOnly` / `Disabled`. Uploads/downloads are unaffected. |
|
||||
|
||||
For example, sync every 10 s and only *log* would-be deletes: Python `EnvironmentWorker(client, environment_id=..., environment_key=..., workdir="/workspace", memory_sync_interval=10, memory_sync_deletes="log_only")`; TypeScript `new EnvironmentWorker({ client, environmentId, environmentKey, workdir: "/workspace", memorySyncIntervalMs: 10_000, memorySyncDeletes: "log_only" })`; Go `environments.EnvironmentWorkerOptions{..., MemorySyncInterval: 10 * time.Second, MemorySyncDeletes: environments.MemorySyncDeletesLogOnly}`.
|
||||
For example, sync every 10 s and only *log* would-be deletes: Python `EnvironmentWorker(client, environment_id=..., environment_key=..., workdir="/workspace", memory_sync_interval=10, memory_sync_deletions="log_only")`; TypeScript `new EnvironmentWorker({ client, environmentId, environmentKey, workdir: "/workspace", memorySyncIntervalMs: 10_000, memorySyncDeletions: "log_only" })`; Go `environments.EnvironmentWorkerOptions{..., MemorySyncInterval: 10 * time.Second, MemorySyncDeletions: environments.MemorySyncDeletionsLogOnly}`.
|
||||
|
||||
**Read-only stores and conflicts.** For `access: "read_only"`, `write`/`edit` refuse changes under the directory (the only memory errors that reach the agent, as tool errors) and nothing uploads; the memory-store endpoints also reject writes made with the session's `secret`. `bash` edits aren't blocked locally - they never sync and the next remote change overwrites them. Conflicts resolve **in favor of the store**: if the agent changes a file that also changed remotely since the last sync, the worker keeps the store's version at the next sync, overwrites the local file, and logs a warning - `write`/`edit` still succeed and no error reaches the agent; it can re-read and re-apply.
|
||||
|
||||
@@ -278,7 +279,7 @@ These are **control-plane** calls - authenticate with `x-api-key` (not the envir
|
||||
|---|---|---|
|
||||
| `ANTHROPIC_ENVIRONMENT_KEY` | `sk-ant-oat01-...` | One environment's work queue. Generate in Console ("Generate environment key"). Pass as `auth_token=` / `authToken` on the client **and** as `environment_key=` / `environmentKey` on `EnvironmentWorker`. Store in a secrets manager; rotate on exposure. |
|
||||
| `ANTHROPIC_WEBHOOK_SIGNING_KEY` | `whsec_...` | Webhook signature verification (if using webhook-driven wake). The SDK reads this env var automatically for `client.beta.webhooks.unwrap()`. |
|
||||
| Work-item `secret` (`ANTHROPIC_WORK_SECRET`) | per-session, issued by Anthropic on the claimed work item | Posts that session's events and reads/writes the memory stores attached to it. You don't generate it; the in-process worker picks it up from the work item, and in the sandbox-per-session pattern you forward it into the sandbox yourself (or pass `work_secret=` / `workSecret` / `WorkSecret` explicitly). Treat like the environment key: only into the sandbox serving that session, never in images, shared volumes, or logs. |
|
||||
| Work-item `secret` (`ANTHROPIC_WORK_SECRET`) | per-session, issued by Anthropic on the claimed work item | Posts that session's events and reads/writes the memory stores attached to it. You don't generate it; the in-process worker picks it up from the work item, and in the sandbox-per-session pattern you forward it into the sandbox yourself (or pass `work_secret=` / `workSecret` / `WorkSecret` explicitly). Pass it only into the sandbox serving that session, never in images, shared volumes, or logs. |
|
||||
|
||||
## Security - what you own
|
||||
|
||||
|
||||
@@ -233,7 +233,7 @@ The session re-checks the config when it first initializes the tool; if a previo
|
||||
|
||||
**Multiagent layering** (see `shared/managed-agents-multiagent.md`): every list on the path to a thread applies at once - a roster agent is bound by its own lists, by those of every agent that called it, and by the coordinator's *current* lists. Allow-lists intersect and block-lists union, so a roster agent can narrow but never widen. Disjoint allow-lists leave the tool available but every call fails `url_not_allowed` (the tool description tells the model) - keep roster allow-lists inside the coordinator's. `max_content_tokens` and `user_location` are **not** combined: own value -> caller's -> coordinator's. `{"type": "self"}` entries follow the coordinator. The outcome grader (`shared/managed-agents-outcomes.md`) runs without the web tools. Updating an idle session's tools changes the coordinator's lists for every thread from its next turn; a roster agent's own lists stay as defined at session create.
|
||||
|
||||
**vs. the Messages API `web_search_20260209` / `web_fetch_20260209` tools:** same `allowed_domains` / `blocked_domains` vocabulary, but 64-entry cap, no path on `web_fetch` domains, and no `max_uses`, `citations`, or `cache_control`. If migrating from Messages API, these move from per-request to once-on-the-agent.
|
||||
**vs. the Messages API web search / web fetch server tools:** same `allowed_domains` / `blocked_domains` vocabulary, but 64-entry cap, no path on `web_fetch` domains, and no `max_uses`, `citations`, or `cache_control`. If migrating from Messages API, these move from per-request to once-on-the-agent.
|
||||
|
||||
### Custom Tools (Client-Side)
|
||||
|
||||
|
||||
@@ -541,8 +541,8 @@ If the code uses the `AnthropicBedrockMantle` client (Python `anthropic[bedrock]
|
||||
| `claude-opus-5-5` | `anthropic.claude-opus-5-5` |
|
||||
| `claude-fable-5-1` | `anthropic.claude-fable-5-1` |
|
||||
| `claude-fable-5` | `anthropic.claude-fable-5` |
|
||||
| `claude-mythos-5-1` | `anthropic.claude-mythos-5-1` (us-east-1 only, limited availability) |
|
||||
| `claude-mythos-5` | `anthropic.claude-mythos-5` |
|
||||
| `claude-mythos-5-1` | `anthropic.claude-mythos-5-1` (limited availability, verification required) |
|
||||
| `claude-mythos-5` | `anthropic.claude-mythos-5` (limited availability, verification required) |
|
||||
| `claude-opus-4-7` | `anthropic.claude-opus-4-7` |
|
||||
| `claude-sonnet-5` | `anthropic.claude-sonnet-5` |
|
||||
| `claude-sonnet-5-5` | `anthropic.claude-sonnet-5-5` |
|
||||
@@ -604,7 +604,7 @@ For cached prompts: the render order and hash inputs did not change, so existing
|
||||
|
||||
> **Model ID `claude-opus-4-7` is authoritative as written here.** When the user asks to migrate to Opus 4.7, write `model="claude-opus-4-7"` exactly. Do **not** fetch the docs to verify - this guide is the source of truth for migration target IDs. The corresponding entry exists in `shared/models.md`.
|
||||
|
||||
Claude Opus 4.7 was Anthropic's most capable model at its launch and is now the previous-generation Opus (Opus 4.8 is current - see Migrating to Opus 4.8 below). It is highly autonomous and performs exceptionally well on long-horizon agentic work, knowledge work, vision tasks, and memory tasks. This section summarizes everything that was new at the 4.7 launch and remains the layered breaking-change path for callers coming from Opus 4.6 or older. It is layered on top of the 4.6 migration above - if the caller is jumping from Opus 4.5 or older, apply the 4.6 changes first, then this section, then the 4.8 section.
|
||||
Claude Opus 4.7 was Anthropic's most capable model at its launch and has been succeeded by newer models; for the next step, see Migrating to Opus 4.8 below. It is highly autonomous and performs exceptionally well on long-horizon agentic work, knowledge work, vision tasks, and memory tasks. This section summarizes everything that was new at the 4.7 launch and remains the layered breaking-change path for callers coming from Opus 4.6 or older. It is layered on top of the 4.6 migration above - if the caller is jumping from Opus 4.5 or older, apply the 4.6 changes first, then this section, then the 4.8 section.
|
||||
|
||||
**TL;DR for someone already on Opus 4.6:** update the model ID to `claude-opus-4-7`, strip any remaining `budget_tokens` and sampling parameters (both 400 on Opus 4.7), give `max_tokens` extra headroom and re-baseline with `count_tokens()` against the new model, opt back into `thinking.display: "summarized"` if reasoning is surfaced to users, and re-tune `effort` - it matters more on 4.7 than on any prior Opus.
|
||||
|
||||
@@ -716,9 +716,9 @@ Set a generous budget for open-ended agentic tasks and tighten it for latency-se
|
||||
|
||||
### Capability improvements
|
||||
|
||||
**High-resolution vision.** Opus 4.7 is the first Claude model with high-resolution image support. Maximum image resolution is **2576 pixels on the long edge** (up from 1568px on Opus 4.6 and prior). This unlocks gains on vision-heavy workloads, especially computer use and screenshot/artifact/document understanding. Coordinates returned by the model now map 1:1 to actual image pixels, so no scale-factor math is needed.
|
||||
**High-resolution vision.** Opus 4.7 is the first Claude model with high-resolution image support. Maximum image resolution is **2576 pixels on the long edge** (up from 1568px on Opus 4.6 and prior). This unlocks gains on vision-heavy workloads, especially computer use and screenshot/artifact/document understanding. Coordinates are in the pixels of the image Claude processes: images over 2576 px or 4784 visual tokens are downscaled first (`shared/vision-coordinates.md`).
|
||||
|
||||
High-res support is **automatic on Opus 4.7** - no beta header, no client-side opt-in required. The model accepts larger inputs and returns pixel-accurate coordinates out of the box.
|
||||
High-res support is **automatic on Opus 4.7** - no beta header, no client-side opt-in required.
|
||||
|
||||
**Token cost.** Full-resolution images on Opus 4.7 can use up to ~3× more image tokens than on prior models (up to ~4784 tokens per image, vs. the previous ~1,600-token cap). If the extra fidelity isn't needed, downsample client-side before sending to control cost - but **do not add downsampling by default during a migration**. If you're not sure whether the pipeline needs the fidelity, ask the user rather than guessing. Use `count_tokens()` on representative images on Opus 4.7 to re-baseline before reacting to any measured cost shift.
|
||||
|
||||
@@ -813,7 +813,7 @@ Recommended prompt language:
|
||||
|
||||
This can be used without an actual second step, but moving confidence filtering out of the finding step often helps. If the harness has a separate verification/dedup/ranking stage, tell the model explicitly that its job at the finding stage is coverage, not filtering. If single-pass self-filtering is wanted, be concrete about the bar rather than using qualitative terms like "important" - e.g. *"report any bugs that could cause incorrect behavior, a test failure, or a misleading result; only omit nits like pure style or naming preferences."* Iterate on prompts against a subset of evals to validate recall or F1 gains.
|
||||
|
||||
**Computer use.** Computer use works across resolutions up to the new 2576px / 3.75MP maximum. Sending images at **1080p** provides a good balance of performance and cost. For particularly cost-sensitive workloads, **720p** or **1366×768** are lower-cost options with strong performance. Test to find the ideal settings for the use case; experimenting with `effort` can also help tune behavior.
|
||||
**Computer use.** Computer use works across resolutions up to the new 2576px long edge / 4784-visual-token maximum. Sending images at **1080p** provides a good balance of performance and cost. For particularly cost-sensitive workloads, **720p** or **1366×768** are lower-cost options with strong performance. Test to find the ideal settings for the use case; experimenting with `effort` can also help tune behavior.
|
||||
|
||||
---
|
||||
|
||||
@@ -841,7 +841,7 @@ Every item is tagged: **`[BLOCKS]`** items cause a 400 error, infinite loop, sil
|
||||
- [ ] **[TUNE]** Frontend/design output: specify a concrete palette/typeface, or have the model propose 4 visual directions before building (the default cream/serif house style is persistent)
|
||||
- [ ] **[TUNE]** Interactive coding products: use `effort: "xhigh"` or `"high"`, add autonomous features (e.g. an auto mode) to reduce human interactions, and specify task/intent/constraints upfront in the first turn
|
||||
- [ ] **[TUNE]** Code-review harnesses: remove or loosen "only report high-severity" / "be conservative" filters and have the model report every finding with confidence + severity; move filtering to a downstream step (4.7 follows severity filters more literally, which can depress measured recall)
|
||||
- [ ] **[TUNE]** Vision-heavy pipelines (screenshots, charts, document understanding): leave images at native resolution up to 2576px long edge for the accuracy gain; remove any scale-factor math from coordinate handling (coords are now 1:1 with pixels). No beta header / opt-in needed - high-res is automatic on Opus 4.7.
|
||||
- [ ] **[TUNE]** Vision-heavy pipelines (screenshots, charts, document understanding): leave images at native resolution, up to 2576px on the long edge and 4784 visual tokens, for the accuracy gain; for larger images see `shared/vision-coordinates.md`. No beta header / opt-in needed - high-res is automatic on Opus 4.7.
|
||||
- [ ] **[TUNE]** Computer-use pipelines: send screenshots at 1080p for a good performance/cost balance (720p or 1366×768 for cost-sensitive workloads); experiment with `effort` to tune behavior
|
||||
- [ ] **[TUNE]** Cost-sensitive image pipelines: full-res images on 4.7 use up to ~4784 tokens vs ~1,600 on prior models (~3×). Downsampling client-side before upload avoids the increase, but **do not downsample by default** - if you're unsure whether fidelity is needed, ask the user. Re-baseline with `count_tokens()` on representative images before reacting to cost shifts.
|
||||
|
||||
@@ -851,7 +851,7 @@ Every item is tagged: **`[BLOCKS]`** items cause a 400 error, infinite loop, sil
|
||||
|
||||
> **Model ID `claude-opus-4-8` is authoritative as written here.** When the user asks to migrate to Opus 4.8, write `model="claude-opus-4-8"` exactly. Do **not** fetch the docs to verify - this guide is the source of truth for migration target IDs. The corresponding entry exists in `shared/models.md`.
|
||||
|
||||
Claude Opus 4.8 is our most capable Opus-tier model - highly autonomous, with state-of-the-art long-horizon agentic execution, knowledge work, and memory. It is layered on top of the Opus 4.7 migration above. If the caller is jumping from Opus 4.6 or older, apply the 4.6 and 4.7 sections first, then this one.
|
||||
Claude Opus 4.8 is highly autonomous and strong at long-horizon agentic execution, knowledge work, and memory. It is layered on top of the Opus 4.7 migration above. If the caller is jumping from Opus 4.6 or older, apply the 4.6 and 4.7 sections first, then this one.
|
||||
|
||||
**No new breaking changes.** Opus 4.8 keeps the same request surface as Opus 4.7. The same calls that already work on 4.7 work unchanged on 4.8 - adaptive thinking only (`thinking: {type: "enabled", budget_tokens: N}` still 400s; use `{type: "adaptive"}`), sampling parameters (`temperature`, `top_p`, `top_k`) still rejected, last-assistant-turn prefills still 400, `thinking.display` still defaults to `"omitted"`, and the `low`/`medium`/`high`/`xhigh`/`max` effort levels, Task Budgets (beta), and high-resolution vision all behave as on 4.7. A 4.7 -> 4.8 migration is therefore **the model-ID swap plus prompt re-tuning** - there is no required code edit beyond the model string.
|
||||
|
||||
@@ -883,7 +883,7 @@ Phrase these as **context, not commands**. State the fact and let Claude act on
|
||||
|
||||
### Capability improvements
|
||||
|
||||
**Long-horizon agentic execution.** Opus 4.8 is state-of-the-art at long, autonomous agentic work - complex refactors and overnight coding runs that complete without human correction. To get the most out of it, **give the full task specification up front in a single well-specified initial turn and run at high effort** (`effort: "high"` or `"xhigh"`). Its long-horizon coherence comes partly from reasoning more at each step; combined with a clear up-front goal, that more-intelligent planning often produces more efficient *and* more accurate output than prior frontier models. The "clear goal up front" principle maps to two product surfaces: in Claude Code, `/goal` sets direction for the run; with **Managed Agents (CMA)**, state what "done" looks like via an **Outcome** (`user.define_outcome` with a gradeable rubric - the harness runs an iterate -> grade -> revise loop), see `shared/managed-agents-outcomes.md`.
|
||||
**Long-horizon agentic execution.** Opus 4.8 is strong at long, autonomous agentic work - complex refactors and overnight coding runs that complete without human correction. To get the most out of it, **give the full task specification up front in a single well-specified initial turn and run at high effort** (`effort: "high"` or `"xhigh"`). Its long-horizon coherence comes partly from reasoning more at each step; combined with a clear up-front goal, that more-intelligent planning often produces more efficient *and* more accurate output than prior frontier models. The "clear goal up front" principle maps to two product surfaces: in Claude Code, `/goal` sets direction for the run; with **Managed Agents (CMA)**, state what "done" looks like via an **Outcome** (`user.define_outcome` with a gradeable rubric - the harness runs an iterate -> grade -> revise loop), see `shared/managed-agents-outcomes.md`.
|
||||
|
||||
**Effort is a dimension to test, not a fixed setting.** On prior models many reached for `xhigh` reflexively to maximize intelligence. Opus 4.8 has a higher intelligence ceiling, so **start at `high` as the default and iterate** rather than defaulting to `xhigh`. Sweep `medium`, `high`, and `xhigh` on your own eval set and weigh the intelligence <-> latency <-> cost tradeoff per route - the relationship isn't monotonic: higher effort up front often *reduces* turn count and total cost on agentic work, while for some tasks `medium` delivers equally good results in less time. Reserve `max` for extremely hard, latency-insensitive cases. The per-level effort table in the **Migrating to Opus 4.7** section above applies unchanged on 4.8.
|
||||
|
||||
@@ -1058,7 +1058,7 @@ At `xhigh` or `max`, **set a large `max_tokens`** so the model has room to think
|
||||
|
||||
**Fast mode.** `speed: "fast"` (beta header `fast-mode-2026-02-01`) is supported on Claude Opus 5, priced at $10 / $50 per MTok. It is a research preview on the **Claude API only** - including Managed Agents - and is **not** available on Amazon Bedrock, Google Cloud, or Microsoft Foundry. Fast mode draws on dedicated rate limits separate from the standard Opus pools.
|
||||
|
||||
**Vision - give it tools, not more thinking.** Stronger on chart, document, and diagram understanding, and on UI and frontend visual replication. The highest-leverage change is **giving it tools to iteratively analyze, crop, and visually verify its own work**: on this model tool use is a markedly more cost-effective lever than raising thinking alone. Claude Opus 5 sits in the high-resolution tier alongside Opus 4.8 - 2576 px on the long edge, up to 4784 visual tokens per image - so coordinates map 1:1 to pixels and no scale-factor math is needed. Any prompt-side workaround you added for a prior model's vision limitations should be re-validated; several are now counterproductive.
|
||||
**Vision - give it tools, not more thinking.** Stronger on chart, document, and diagram understanding, and on UI and frontend visual replication. The highest-leverage change is **giving it tools to iteratively analyze, crop, and visually verify its own work**: on this model tool use is a markedly more cost-effective lever than raising thinking alone. Claude Opus 5 sits in the high-resolution tier alongside Opus 4.8: up to 2576 px on the long edge and 4784 visual tokens per image. Within those limits coordinates match image pixels; larger images are downscaled first, and coordinates then refer to the downscaled image. Any prompt-side workaround you added for a prior model's vision limitations should be re-validated; several are now counterproductive.
|
||||
|
||||
**Long context.** 1M-token context window as both the default *and* the maximum. Instruction following, tool calling, and reasoning stay strong across the full window.
|
||||
|
||||
@@ -1274,7 +1274,7 @@ Conversely, if you're running hard workloads at `medium` and seeing under-thinki
|
||||
|
||||
**High-resolution vision.** Claude Sonnet 5 is the first Sonnet-tier model with high-resolution image support: maximum **2576 pixels on the long edge** (up from 1568px on Sonnet 4.6). High-res images can use up to ~3× more image tokens than on Sonnet 4.6 (4784 vs 1568 tokens per image at the limit) - if the added fidelity isn't needed, downsample before sending to control token costs. No beta header or opt-in required.
|
||||
|
||||
**Computer use.** Supports the `computer_20251124` tool version (beta header `computer-use-2025-11-24`). Capability works across resolutions up to the 2576px / 3.75MP maximum; sending screenshots at **1080p** provides a good balance of performance and cost. For particularly cost-sensitive workloads, **720p** or **1366×768** are lower-cost options with strong performance. Test to find the ideal settings for the use case; experimenting with `effort` can also help tune behavior.
|
||||
**Computer use.** Supports `computer_toolset_20260801` (no beta header). The earlier `computer_20251124` (beta header `computer-use-2025-11-24`) still works. Capability works across resolutions up to the 2576px long edge / 4784-visual-token maximum; sending screenshots at **1080p** provides a good balance of performance and cost. For particularly cost-sensitive workloads, **720p** or **1366×768** are lower-cost options with strong performance. Test to find the ideal settings for the use case; experimenting with `effort` can also help tune behavior.
|
||||
|
||||
### Behavioral shifts (prompt-tunable)
|
||||
|
||||
@@ -1331,7 +1331,7 @@ Every item is tagged: **`[BLOCKS]`** items cause a 400 error or truncated output
|
||||
- [ ] **[TUNE]** Code-review harnesses with conservative-reporting instructions ("only high-severity", "don't nitpick"): switch to a coverage-first prompt (report everything with confidence + severity) and filter downstream - measured recall can otherwise fall even though bug-finding improved
|
||||
- [ ] **[TUNE]** Open-ended frontend/design briefs: specify a concrete spec, or have the model propose 3-4 visual directions and pick one (the recommended substitute for `temperature`-driven variety)
|
||||
- [ ] **[TUNE]** Interactive coding products: use `effort: "xhigh"`/`"high"`, add autonomous features (e.g. auto mode), and put task/intent/constraints in the first turn
|
||||
- [ ] **[TUNE]** Vision-heavy / computer-use pipelines: leave images at native resolution up to 2576px long edge for the accuracy gain (downsample to control image-token cost if fidelity isn't needed); for computer use, 1080p screenshots are a good performance/cost balance with `computer_20251124`
|
||||
- [ ] **[TUNE]** Vision-heavy / computer-use pipelines: leave images at native resolution up to 2576px long edge and 4784 visual tokens for the accuracy gain (downsample to control image-token cost if fidelity isn't needed); for computer use, 1080p screenshots are a good performance/cost balance with `computer_toolset_20260801`
|
||||
- [ ] **[TUNE]** Security workloads: add handling for safeguard refusals (cyber-capable topics may now be declined where Sonnet 4.6 answered)
|
||||
|
||||
---
|
||||
@@ -1410,7 +1410,7 @@ else:
|
||||
|
||||
Three ways to retry a refused request on another model, in order of preference:
|
||||
|
||||
**1. Server-side `fallbacks` parameter (beta; Claude API, Claude Platform on AWS and Claude Models on Google Cloud (Anthropic managed)) - preferred.** One round trip, a plain client, no client-side logic. Name substitute models (the supported fallback targets are `claude-opus-4-8` and `claude-opus-5`, expansion expected); on a policy decline the API runs the next model on the same request and returns its answer, with credit-style repricing applied automatically. A `stop_reason: "refusal"` on the final response means the whole chain refused.
|
||||
**1. Server-side `fallbacks` parameter (beta; Claude API and Claude Models on Google Cloud (Anthropic managed)) - preferred.** One round trip, a plain client, no client-side logic. Name substitute models (the supported fallback targets are `claude-opus-4-8` and `claude-opus-5`, expansion expected); on a policy decline the API runs the next model on the same request and returns its answer, with credit-style repricing applied automatically. A `stop_reason: "refusal"` on the final response means the whole chain refused.
|
||||
|
||||
```python
|
||||
response = client.beta.messages.create(
|
||||
@@ -1438,14 +1438,14 @@ if fallback_ran and response.stop_reason != "refusal":
|
||||
|
||||
Key semantics:
|
||||
|
||||
- **Header depends on the form you use.** The **array** form (`fallbacks: [{...}]`) takes `server-side-fallback-2026-06-01` or `-2026-07-01`; any other `server-side-fallback-*` value rejects it with a 400 (`-2026-06-09` and `-2026-06-02` were earlier previews). The **`"default"` scalar** form needs `-2026-07-01` - see § New API features under Migrating to Claude Opus 5. Rejected on the Batches API; available on the Claude API, Claude Platform on AWS and Claude Models on Google Cloud (Anthropic managed); not on Amazon Bedrock, Vertex AI, or Microsoft Foundry (use pattern 2 there - the SDK middleware). Each entry names a `model` and can override `max_tokens` (bounding that attempt's own output independently of the top-level `max_tokens`), `thinking`, `output_config`, and `speed` for that attempt only (`speed` on a research-preview model additionally requires its beta). Entries must be distinct and must be in the requested model's `allowed_fallback_models` (published on `/v1/models` when either accepted `server-side-fallback-*` header is set - not yet visible under the `fallback-credit-*` header alone, and not exposed on Amazon Bedrock, Vertex AI, or Microsoft Foundry). The request *with an entry's overrides merged in* must be valid as a direct request to that entry's model.
|
||||
- **Header depends on the form you use.** The **array** form (`fallbacks: [{...}]`) takes `server-side-fallback-2026-06-01` or `-2026-07-01`; any other `server-side-fallback-*` value rejects it with a 400 (`-2026-06-09` and `-2026-06-02` were earlier previews). The **`"default"` scalar** form needs `-2026-07-01` - see § New API features under Migrating to Claude Opus 5. Rejected on the Batches API; available on the Claude API and Claude Models on Google Cloud (Anthropic managed); not on Amazon Bedrock, Vertex AI, or Microsoft Foundry, and not documented for Claude Platform on AWS (use pattern 2 on all four - the SDK middleware). Each entry names a `model` and can override `max_tokens` (bounding that attempt's own output independently of the top-level `max_tokens`), `thinking`, `output_config`, and `speed` for that attempt only (`speed` on a research-preview model additionally requires its beta). Entries must be distinct and must be in the requested model's `allowed_fallback_models` (published on `/v1/models` when either accepted `server-side-fallback-*` header is set - not yet visible under the `fallback-credit-*` header alone, and not exposed on Amazon Bedrock, Vertex AI, or Microsoft Foundry). The request *with an entry's overrides merged in* must be valid as a direct request to that entry's model.
|
||||
- **Triggers on policy declines only** - rate limits, overloads, and server errors on the requested model are returned as-is, never falling back.
|
||||
- **Reading the response:** a `fallback` content block (`{"type": "fallback", "from": {"model": ...}, "to": {"model": ...}}`) marks each switch point in `content`; the served-by signal is a `fallback_message` entry in `usage.iterations` (don't rely on the block - sticky-served turns have none). Top-level `model` names the model that produced the message.
|
||||
- **Billing:** `usage.iterations` is the per-attempt source of truth; top-level `usage` covers only the attempt that produced the returned message. Declined-before-output attempts are reported (for whether they're billed, see [How refusals are billed](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#how-refusals-are-billed)); an attempt that declines mid-stream bills at normal rates, and fallback attempts bill at the fallback model's rates. Each attempt claims the rate limits of the model that ran it - if the fallback model is rate-limited or overloaded, the fallback attempt is not made and the preceding refusal is returned instead with `stop_details.recommended_model` naming a model to retry directly (the recommendation is a hint, not a guarantee, and is `null` when no recommendation is available) - size fallback-model limits for expected refusal volume.
|
||||
- **Sticky routing:** once a conversation falls back, later requests with `fallbacks` (streaming and non-streaming - on a stream the decision is made before it opens, so `message_start` already names the fallback model) are served directly by the fallback model for ~1 hour (best-effort; org-scoped content-hash record, not message content; not recorded for ZDR orgs). Handle the requested model being tried again at any time.
|
||||
- **Echoing fallback turns back:** after a mid-output fallback, omit `thinking`, `redacted_thinking`, and `tool_use` blocks - plus any `server_tool_use` block without its matching `server_tool_result`, and any other unrecognized model-internal block type - that appear *before* the final `fallback` block; text blocks, paired server-tool blocks, and everything after the boundary echo normally. Keep the `fallback` block exactly where it appeared, even when you omit the thinking before it: the API uses its position to validate the thinking blocks around it, and a request that echoes thinking blocks from both sides of the boundary is rejected if the block is omitted or moved. Streaming: the retry happens on the same stream and already-received content is never invalidated - a pre-output block is seamless (`message_start` names the fallback model; the `fallback` block arrives as an ordinary `content_block_start`, first in `content` - there is no special SSE event type; note `message_start` arrives only after the declined attempt, so time-to-first-byte includes it), and a mid-stream block keeps the partial, marks the boundary with the block, and continues - only the partial's `text` blocks are passed to the fallback model as continuation context (other block types stay in `content` but aren't part of it). Non-streaming mid-output declines omit the declined partial entirely.
|
||||
|
||||
**2. SDK client-side middleware - for providers without server-side fallbacks (Amazon Bedrock, Vertex AI, Microsoft Foundry).** Register it on the client and every `client.beta.messages` request (streaming included) retries refusals automatically, splicing the fallback model's events onto the open stream in the same wire shape as pattern 1 (a `fallback` content block at each boundary, per-hop `usage.iterations`). It is also a beta surface: the middleware sends the `fallback-credit-2026-07-01` header by default so retries are repriced via credit tokens (override with its `betas` option). `BetaFallbackState` pins follow-up turns to the model that accepted (the client-side analog of sticky routing) - reuse one state object per conversation:
|
||||
**2. SDK client-side middleware - for providers without documented server-side fallbacks (Claude Platform on AWS, Amazon Bedrock, Vertex AI, Microsoft Foundry).** Register it on the client and every `client.beta.messages` request (streaming included) retries refusals automatically, splicing the fallback model's events onto the open stream in the same wire shape as pattern 1 (a `fallback` content block at each boundary, per-hop `usage.iterations`). It is also a beta surface: the middleware sends the `fallback-credit-2026-07-01` header by default so retries are repriced via credit tokens (override with its `betas` option). `BetaFallbackState` pins follow-up turns to the model that accepted (the client-side analog of sticky routing) - reuse one state object per conversation:
|
||||
|
||||
```python
|
||||
from anthropic import Anthropic, BetaFallbackState, BetaRefusalFallbackMiddleware
|
||||
@@ -1460,7 +1460,7 @@ Create **one state per conversation** - it is the pinning scope; sharing one acr
|
||||
|
||||
- **TypeScript**: `betaRefusalFallbackMiddleware([...])` in the client's `middleware` array; pass `{ fallbackState: state }` (a `BetaFallbackState`) as a request option.
|
||||
- **Go**: `option.WithMiddleware(betafallback.BetaRefusalFallbackMiddleware([]anthropic.BetaFallbackParam{{Model: ...}}))` (package `lib/betafallback`); state via `betafallback.WithBetaFallbackState(&betafallback.BetaFallbackState{})` passed as a request option. Server-side equivalents: `Fallbacks: anthropic.BetaFallbacksParamUnion{OfBetaFallbackArray: []anthropic.BetaFallbackParam{...}}` + `anthropic.AnthropicBetaServerSideFallback2026_07_01`.
|
||||
- **C#**: it's a *handler* - `new AnthropicClient { Handlers = [new BetaRefusalFallbackHandler { Fallbacks = [new("claude-opus-4-8")] }] }` (namespace `Anthropic.Helpers`); state via `BetaFallbackState.Create()` scoped per call with `using (fallbackState.Use()) { ... }`. Server-side equivalents: `Fallbacks = new([new("claude-opus-4-8")])` + `AnthropicBeta.ServerSideFallback2026_07_01` (namespace `Anthropic.Models.Beta`).
|
||||
- **C#**: it's a *handler* - `new AnthropicClient { Handlers = [new BetaRefusalFallbackHandler { Fallbacks = [new("claude-opus-4-8")] }] }` (namespace `Anthropic.Helpers`); state via `BetaFallbackState.Create()` scoped per call with `using (fallbackState.Use()) { ... }`. Server-side equivalents: `Fallbacks = new([new("claude-opus-4-8")])` (on the request, `Fallbacks` is a `BetaFallbacksParam`, so a bare `[...]` list doesn't compile; only the handler above takes one) + `Betas = ["server-side-fallback-2026-07-01"]`.
|
||||
|
||||
For languages not listed (Java, Ruby, PHP) - or for a full runnable program in any language - each public SDK repo ships a fallbacks example under `examples/` (e.g. `examples/fallbacks.py`, `examples/refusal-fallback/`): fetch the repo from `shared/live-sources.md` § SDK Repositories rather than improvising the binding.
|
||||
|
||||
@@ -1567,7 +1567,7 @@ For agents that only narrate routine progress, the model's default progress narr
|
||||
- [ ] **[BLOCKS]** Remove all other `thinking` configuration (`{type: "enabled", budget_tokens: N}` returns a 400, same as on Opus 4.7/4.8); control depth with `output_config.effort` instead
|
||||
- [ ] **[BLOCKS]** If thinking content is surfaced to users or stored in logs: add `thinking: {type: "adaptive", display: "summarized"}` (the default is `"omitted"` - otherwise the rendered text is empty)
|
||||
- [ ] **[TUNE]** Re-baseline cost and latency on your own workloads - token counts are roughly unchanged from Opus 4.7/4.8 and Mythos Preview (same tokenizer); per-token pricing differs. Coming from Opus 4.6, Sonnet 4.6, Haiku 4.5, or older, token counts differ - use `count_tokens` with each model to compare
|
||||
- [ ] **[TUNE]** Add `stop_reason == "refusal"` handling before reading `response.content` (pre-output: empty, billing per [How refusals are billed](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#how-refusals-are-billed); mid-stream: billed at normal rates - discard the partial); opt into a fallback by default - server-side `fallbacks` (Claude API, Claude Platform on AWS and Claude Models on Google Cloud (Anthropic managed): `fallbacks: "default"` with `server-side-fallback-2026-07-01`, or the array form with that header or `server-side-fallback-2026-06-01`) where available, otherwise the SDK middleware or fallback credit (`fallback-credit-2026-07-01`, exact body); a bare client-side replay (history as-is; models other than Claude Fable 5.1 / Claude Mythos 5.1 (and the later Claude Fable 5.2 and Claude Mythos 5.2) drop Fable's thinking blocks) is the floor, not the recommendation
|
||||
- [ ] **[TUNE]** Add `stop_reason == "refusal"` handling before reading `response.content` (pre-output: empty, billing per [How refusals are billed](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#how-refusals-are-billed); mid-stream: billed at normal rates - discard the partial); opt into a fallback by default - server-side `fallbacks` (Claude API and Claude Models on Google Cloud (Anthropic managed): `fallbacks: "default"` with `server-side-fallback-2026-07-01`, or the array form with that header or `server-side-fallback-2026-06-01`) where available, otherwise the SDK middleware or fallback credit (`fallback-credit-2026-07-01`, exact body); a bare client-side replay (history as-is; models other than Claude Fable 5.1 / Claude Mythos 5.1 (and the later Claude Fable 5.2 and Claude Mythos 5.2) drop Fable's thinking blocks) is the floor, not the recommendation
|
||||
- [ ] **[TUNE]** If you surfaced thinking text to users, plan for the thinking output change - the raw chain of thought is never returned; render the `display: "summarized"` summary (per the [BLOCKS] item above); pass blocks back unchanged on the same model; other models drop them from the prompt (unbilled; Claude Mythos 5.1 (and the later Claude Fable 5.2 and Claude Mythos 5.2) instead read them)
|
||||
- [ ] **[TUNE]** Plan for minutes-long turns: timeouts, streaming, async check-ins, progress UX (see Behavior changes above)
|
||||
- [ ] **[TUNE]** Run an effort sweep including low/medium for routine workloads; add the no-tidying instruction if higher effort produces unrequested refactors
|
||||
@@ -1639,7 +1639,7 @@ The published docs file this and breaking change 2 together under *preserved thi
|
||||
|
||||
To find and fix these edits in an existing harness - capture its requests, diff them, measure the drops, then one diff per cause - follow `shared/preserved-thinking-migration.md` (the `preserved-thinking-migration` subcommand). This section holds the rules that guide applies.
|
||||
|
||||
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 and Managed Agents keep the prefix intact for you, and so does the Agent SDK if the system prompt you give it stays the same; **if your code builds the `messages` array itself, check it before migrating** (the three-step check is below). **Who is enforced:** on Claude Fable 5.1, new accounts **created on or after August 31, 2026**, on every platform. Enforcement scope is decided per model - Claude Opus 5.5 also enforces it for new accounts only, while on Claude Mythos 5.1 it is enforced by default whatever the account's age, on the Claude API, Google Cloud Vertex AI, and Microsoft Foundry - 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`. On models that enforce new accounts only, for accounts created earlier the API *records* the mismatch but acts on it only when the request sets `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 (the beta header alone does not opt in: it lets you set the field and, on a request that leaves the field unset, lists each failing block in `input_transformations` as `thinking_mismatch_allowed` while the model still receives it). 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 on a model, send that model a request that edits history without the beta header - a 400 that names the header means it is. Platform note: the opt-in controls (the beta header, `prefix_mismatch_behavior`, `input_transformations`) are available under the same beta name on the Claude API, Claude Platform on AWS, Amazon Bedrock, and Google Cloud Vertex AI (Claude in Amazon Bedrock: the `anthropic-beta` header; Bedrock's InvokeModel API: the `anthropic_beta` body field; Vertex: the `anthropic-beta` HTTP header - the SDKs' `betas` parameter does the right thing on each); Microsoft Foundry is unconfirmed. Wherever an endpoint rejects the header or the beta name, 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 and Managed Agents keep the prefix intact for you, and so does the Agent SDK if the system prompt you give it stays the same; **if your code builds the `messages` array itself, check it before migrating** (the three-step check is below). **Who is enforced:** on Claude Fable 5.1, a request that fails the check with `prefix_mismatch_behavior` unset might or might not get a 400. On two platforms, that 400 depends on when the account or project first used any Claude model there: on Amazon Bedrock it applies to AWS accounts that first used Claude on Bedrock on or after August 31, 2026, and on Google Cloud Vertex AI to Google Cloud projects that first used Claude there on or after that date; accounts and projects that first used Claude there earlier can get either case. Enforcement scope is decided per model - Claude Opus 5.5 is the same, while on Claude Mythos 5.1 it is enforced by default on the Claude API, Google Cloud Vertex AI, and Microsoft Foundry - so keep the history append-only, which also keeps the prompt cache warm, or set `prefix_mismatch_behavior` on every request. Otherwise handle both cases: catch the 400, and log the `thinking_mismatch_allowed` entries described next. When a request that leaves the field unset fails the check and gets no error, the mismatch is *recorded*, not acted on. Setting `thinking.block_binding.prefix_mismatch_behavior` to **any value, including `"error"`, opts the request into enforcement**, which is also how you test from any account (the beta header alone does not opt in: it lets you set the field and, on a request that leaves the field unset, lists each failing block in `input_transformations` as `thinking_mismatch_allowed` while the model still receives it). If you ship a tool or framework that people run with their own API key, test with the field set: your users' requests can get the 400 when yours don't. To see which case a request gets, send the model an edited history of its own, with a thinking block after the edit, the beta header and no field. A 400 that the same request with the unedited history doesn't get means it got the error, `thinking_mismatch_allowed` entries mean it got none, and an empty array shows nothing; the result holds for that request only. Platform note: the opt-in controls (the beta header, `prefix_mismatch_behavior`, `input_transformations`) are available under the same beta name on the Claude API, Claude Platform on AWS, Amazon Bedrock, and Google Cloud Vertex AI (Claude in Amazon Bedrock: the `anthropic-beta` header; Bedrock's InvokeModel API: the `anthropic_beta` body field; Vertex: the `anthropic-beta` HTTP header - the SDKs' `betas` parameter does the right thing on each); Microsoft Foundry is unconfirmed. Wherever an endpoint rejects the header or the beta name, 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:**
|
||||
|
||||
@@ -1651,7 +1651,7 @@ A Claude Fable 5.1 thinking block's `signature` also records the conversation pr
|
||||
|
||||
**What keeps later blocks valid:** append-only histories, including appended `role: "system"` messages and cleared turn-scoped (`clear_at`) messages or reminder text blocks left in place; removing a *leading* run of thinking blocks, oldest first (the first block in the conversation - or the first after the most recent compaction block - then the next, and so on), a trailing run, or all of them; reordering `tools` without changing them (bound as a name-sorted set) and adding a `defer_loading: true` tool nothing has referenced yet; changing any request parameter outside `system` / `tools` / `messages` (`max_tokens`, `output_config` incl. `effort`, `tool_choice`, `metadata`); adding, moving, or removing `cache_control` markers; a rotating signed URL that returns the same bytes; server-side compaction and context editing, including thinking-block clearing (they don't count as edits, because the check compares the conversation *as you sent it*, not the server's edited copy; after a compaction the checked prefix starts from the compaction block).
|
||||
|
||||
**Where the check is enforced, a request that replays an invalidated block is rejected** with a 400 `invalid_request_error`, decided before any output. Retrying the same body fails the same way; the token-counting endpoint runs the same check. (In the Message Batches API the *unset* default drops failing blocks instead of failing the item - set `"error"` explicitly if you want batch items to error.)
|
||||
**Where the check is enforced, a request that replays an invalidated block is rejected** with a 400 `invalid_request_error`, decided before any output. Retrying the same body fails the same way; the token-counting endpoint can return the same 400. (In the Message Batches API the *unset* default drops failing blocks or, on some models, can let them through, instead of failing the item - set `"error"` explicitly if you want batch items to error.)
|
||||
|
||||
```text
|
||||
messages.5.content.0: 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". That setting requires the `thinking-binding-controls-2026-08-01` value in the `anthropic-beta` header.
|
||||
@@ -1671,7 +1671,7 @@ anthropic-beta: thinking-binding-controls-2026-08-01
|
||||
"messages": [ ...full history with thinking blocks replayed verbatim... ]}
|
||||
```
|
||||
|
||||
`thinking.block_binding.prefix_mismatch_behavior` takes `"error"` or `"drop_block"`. On an enforced account the default is `"error"` with or without the header (the header only lets you set the field, and adds `input_transformations` to responses). On an account that isn't enforced, an unset field lets failing blocks through to the model, and with the header each one is listed in `input_transformations` as an entry of type `thinking_mismatch_allowed`. In the Message Batches API the unset default on an enforced account drops the failing blocks instead of failing the item; a Batches item fails as `errored` only with `prefix_mismatch_behavior: "error"` set. Set the field explicitly. With `"drop_block"` the API drops the first mismatched block **and every thinking block after it** (up to the next compaction block, if any - including blocks in an assistant turn whose `tool_use` is still waiting on its `tool_result`), the request proceeds, and each drop is reported in the response's top-level `input_transformations` array:
|
||||
`thinking.block_binding.prefix_mismatch_behavior` takes `"error"` or `"drop_block"`. With the field unset, a request that fails the check gets the 400 or, on some models, no error, with or without the header (the header only lets you set the field, and adds `input_transformations` to responses). When it gets no error, the failing blocks reach the model, and with the header each one is listed in `input_transformations` as an entry of type `thinking_mismatch_allowed`. In the Message Batches API the unset default drops the failing blocks or, on some models, can let them through, instead of failing the item; a Batches item fails as `errored` only with `prefix_mismatch_behavior: "error"` set. Set the field explicitly. With `"drop_block"` the API drops the first mismatched block **and every thinking block after it** (up to the next compaction block, if any - including blocks in an assistant turn whose `tool_use` is still waiting on its `tool_result`), the request proceeds, and each drop is reported in the response's top-level `input_transformations` array:
|
||||
|
||||
```json
|
||||
"input_transformations": [
|
||||
@@ -1685,7 +1685,7 @@ The drop applies to *that request only*: keep sending `"drop_block"` for the res
|
||||
|
||||
1. Capture the exact request bodies it sends over a few normal turns, including a compaction or a tool change if the product has them. For each pair of consecutive requests, compare the `system` prompt, the `tools` array, and the shared prefix of `messages` - they should be byte-identical up to the newly appended turns.
|
||||
2. Run a normal multi-turn session against `claude-fable-5-1` with the `thinking-binding-controls-2026-08-01` header and `prefix_mismatch_behavior: "drop_block"`, and log `input_transformations` on every response. An empty array on every turn means the history is intact, provided a deliberately edited replay on the same model and platform shows an entry; a `prefix_binding_mismatch` entry means something before the block at `path` changed since that block was produced; a `model_binding_mismatch` entry means the conversation switched models. This works from any organization wherever the controls beta is accepted (see the platform note above: if a partner endpoint rejects the beta name as unknown, use strip-and-retry; Foundry unconfirmed), because setting the field opts the request into enforcement. In CI, set `"error"` instead so an edit fails the run.
|
||||
3. Choose a production setting and **set it explicitly** rather than relying on the default (see the defaults note above): `"error"` if a prefix mismatch can only mean a bug in your code, or `"drop_block"` to degrade instead of fail - and monitor the 400s or the `input_transformations` entries either way. On an account that isn't enforced, sending the header with the field unset is a way to monitor production traffic, not one of the two settings above: failing blocks still reach the model, and each one shows up only as a `thinking_mismatch_allowed` entry in `input_transformations`.
|
||||
3. Choose a production setting and **set it explicitly** rather than relying on the default (see the defaults note above): `"error"` if a prefix mismatch can only mean a bug in your code, or `"drop_block"` to degrade instead of fail - and monitor the 400s or the `input_transformations` entries either way. Sending the header with the field unset is a way to monitor production traffic, not one of the two settings above: on a request that gets no error, the failing blocks reach the model, and each one shows up only as a `thinking_mismatch_allowed` entry in `input_transformations`. The request can also get the 400, so catch it.
|
||||
|
||||
**Making a harness compatible - replace each transcript edit with its append-only form:**
|
||||
|
||||
@@ -1698,14 +1698,14 @@ The drop applies to *that request only*: keep sending `"drop_block"` for the res
|
||||
| Compacting | Prefer server-side compaction (beta `compact-2026-01-12`; its `instructions` parameter takes your own summarization prompt) or context editing - neither counts as an edit. Client-side, **simple compaction** is the recommended shape: when the conversation grows too long, summarize it into a single message, start the next request with that summary plus the new user turn, and replay nothing else - no earlier turns, no earlier thinking blocks. Nothing carried over is tied to the old transcript; Claude models are trained on long-horizon tasks with this scheme and it performs comparably to more elaborate ones. Any compaction resets the cache, and don't compact in the middle of a tool round (an assistant turn whose `tool_use` is still waiting on its `tool_result` should go back with its thinking intact). Thinking from before the summary isn't carried forward, so the summary is all the model has of that work - tell the summarizer what to retain (the compaction prompt under Behavioral shifts, or server-side compaction's `instructions`). |
|
||||
| Referencing an image/document by URL across turns | From the first request, upload once to the Files API and send the `file_id`, or send base64: switching an earlier block from a `url` source is itself an edit. |
|
||||
|
||||
Two client-side compaction shapes **break** under the check. *Keep-tail compaction* (summarize older turns, keep the most recent turns verbatim) fails on the retained turns: their thinking blocks were created with the full history present, so replaying them after the summary returns a 400 even though the retained turns are unchanged - strip the thinking blocks from the retained turns (text and tool calls can stay) or set `"drop_block"`. *Background (async) compaction* (compact off the critical path and swap the summary in while the conversation continues) fails the same way but affects more of the transcript: by the time the summary lands, several newer turns exist above the swap point and all of their thinking blocks predate it - send `"drop_block"` on every request that still carries pre-swap thinking blocks (or strip those blocks yourself; `input_transformations` on the first response after the swap lists exactly which ones), or compact synchronously. The same applies to the compaction beta's `pause_after_compaction` flow if you re-insert assistant turns after the compaction block: remove their `thinking` blocks or send `"drop_block"`. Snipping individual turns out of the *middle* of the transcript invalidates every later thinking block, and no client-side shape avoids it - use a mid-conversation system message for the instruction change you were making, or server-side context editing for selective removal.
|
||||
Two client-side compaction shapes **break** under the check. *Keep-tail compaction* (summarize older turns, keep the most recent turns verbatim) fails on the retained turns: their thinking blocks were created with the full history present, so replaying them after the summary can return a 400 even though the retained turns are unchanged - strip the thinking blocks from the retained turns (text and tool calls can stay) or set `"drop_block"`. *Background (async) compaction* (compact off the critical path and swap the summary in while the conversation continues) fails the same way but affects more of the transcript: by the time the summary lands, several newer turns exist above the swap point and all of their thinking blocks predate it - send `"drop_block"` on every request that still carries pre-swap thinking blocks (or strip those blocks yourself; `input_transformations` on the first response after the swap lists exactly which ones), or compact synchronously. The same applies to the compaction beta's `pause_after_compaction` flow if you re-insert assistant turns after the compaction block: remove their `thinking` blocks or send `"drop_block"`. Snipping individual turns out of the *middle* of the transcript invalidates every later thinking block, and no client-side shape avoids it - use a mid-conversation system message for the instruction change you were making, or server-side context editing for selective removal.
|
||||
|
||||
### What carries over unchanged from Claude Fable 5
|
||||
|
||||
The API surface, limits, per-token pricing, tokenizer, always-on adaptive thinking, refusal handling, and `stop_details` categories all match Claude Fable 5: no `thinking` config other than `{type: "adaptive"}` (`disabled` and `budget_tokens` both 400), `display` defaults to `"omitted"` and the raw chain of thought is never returned, interleaved thinking is automatic (no header), no assistant prefill, no non-default sampling parameters, 512-token minimum cacheable prompt, mid-conversation system messages and tool changes supported. The `refusal` stop reason must be handled before reading `content` - the classifiers cover the same categories as Claude Fable 5 (a broader set than Claude Opus 5's classifiers), so expect `stop_details.category` values such as `"cyber"`, `"bio"`, and `"reasoning_extraction"`. Deltas:
|
||||
|
||||
- **Fallbacks:** server-side `fallbacks` (`"default"`, or the array form) and the SDK middleware work as on Claude Fable 5; the permitted targets are `claude-opus-4-8` and `claude-opus-5`, and per-category routing is applied server-side and not published (some categories decline with no fallback). The fallback model can't read Claude Fable 5.1's thinking blocks, so the API drops them (breaking change 2). Fallback credit works as on Claude Fable 5: Claude Fable 5.1 and Claude Mythos 5.1 both mint a `fallback_credit_token` on refusals (the token is `null` when no credit is available for a refusal, so always handle `null`), redeemable on either permitted target (pattern 3 of the refusal section in § Migrating to Claude Fable 5.1 above); the credit refunds the prompt-cache cost of switching models. A mid-stream refusal is billed at normal rates; for a refusal before any output, see [How refusals are billed](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#how-refusals-are-billed).
|
||||
- **Data retention:** Claude Fable 5.1 and Claude Mythos 5.1 are Covered Models like Claude Fable 5 - 30-day retention required, **not available under zero data retention unless expressly authorized by Anthropic**. As on Claude Fable 5, a request from an organization or workspace without 30-day retention returns `400 invalid_request_error` ("In order to access this model, your organization or workspace must have data retention enabled.") - check the retention configuration before debugging the payload. (An earlier draft of the launch docs described a 404 with the model hidden from `/v1/models`; the final wording is the 400. If you do see a 404 on the ID, check retention before anything else.) A ZDR organization that needs the model should contact its Anthropic account team (the "expressly authorized" path) or enable 30-day retention for one workspace; a ZDR org that *can* already reach the model has such an authorization, not proof the requirement is gone. (Earlier drafts of the launch docs described a time-bound enterprise exemption through 2026-12-31; that sentence was removed on Aug 28 - don't cite it.)
|
||||
- **Data retention:** Claude Fable 5.1 and Claude Mythos 5.1 are Covered Models like Claude Fable 5 - 30-day retention required, **not available under zero data retention unless expressly authorized by Anthropic**. As on Claude Fable 5, a request from an organization or workspace without 30-day retention returns `400 invalid_request_error` ("In order to access this model, your organization or workspace must have data retention enabled.") - check the retention configuration before debugging the payload. If you see a 404 on the ID instead, check retention before anything else. A ZDR organization that needs the model should contact its Anthropic account team (the "expressly authorized" path) or enable 30-day retention for one workspace; a ZDR org that *can* already reach the model has such an authorization, not proof the requirement is gone.
|
||||
- **Priority Tier:** not supported on Claude Fable 5.1 or Claude Mythos 5.1 (Claude Fable 5 is). A Claude Fable 5 caller on Priority Tier loses it on migration.
|
||||
- **Rate limits:** Claude Fable 5.1 shares one pool with Claude Fable 5 (combined traffic; the Mythos models share a separate combined limit) - re-baseline headroom if you run both during the migration.
|
||||
- **Pricing:** $10 / $50 per MTok, 5-minute cache writes $12.50, 1-hour cache writes $20, batch $5 / $25 - all as Claude Fable 5 - except **cache reads at $0.25 per MTok** (0.025x base input; cache reads cost the same multiple on Claude Mythos 5.1, Claude Fable 5.2 and Claude Mythos 5.2, 0.05x on Claude Opus 5.5 and Claude Sonnet 5.5, and 0.1x on every other model): a quarter of the Claude Fable 5 rate and half of Claude Opus 5's. Long agentic sessions that re-read a cached prefix get most of the saving; caching break-even math in `shared/prompt-caching.md` shifts accordingly - and because a miss is now much more expensive relative to a hit, keeping the cache warm matters more: per-message effort and turn-scoped system messages exist partly for that, and for idle gaps of 5-60 minutes a `max_tokens: 0` keep-alive re-send on the default 5-minute TTL is usually cheaper than the 1-hour TTL (send it with `stream` off; not with structured outputs or Batches - see `shared/prompt-caching.md` § Choosing the TTL). Expect cost per task at or under the Claude Fable 5 figures in `shared/cost-optimization.md`.
|
||||
@@ -1778,7 +1778,7 @@ From Opus 4.8 or earlier: apply § Migrating to Claude Fable 5.1 above first (Op
|
||||
|
||||
### Claude Mythos 5.1
|
||||
|
||||
`claude-mythos-5-1` is the same model as Claude Fable 5.1 - same capabilities, limits, and per-token pricing (including the $0.25/MTok cache-read rate), and the same API behavior except that the API enforces its history-editing check by default whatever the account's age on the Claude API, Vertex and Foundry; on Amazon Bedrock, not by default (breaking change 3) - offered only to verified organizations, and, apart from Claude Fable 5.2 and Claude Mythos 5.2, the only model besides Claude Fable 5.1 that reads Claude Fable 5.1's thinking blocks (it also reads Claude Mythos 5's; not the reverse). Confirm the organization's access with the account team before switching IDs. Two differences from a Claude Mythos 5 migrator's point of view: **Claude Mythos 5.1 runs safeguards** that depend on the access program the organization is approved under (Claude Mythos 5 ran none) - handle `stop_reason: "refusal"`, read `stop_details.category`, and set up fallback as on Claude Fable 5.1 (same targets, `claude-opus-4-8` and `claude-opus-5`; it mints a `fallback_credit_token` on refusals as Claude Fable 5.1 does) - and it is **not offered on Claude Platform on AWS** (Claude API, Amazon Bedrock as `anthropic.claude-mythos-5-1` in us-east-1 only with limited availability, Google Cloud, Microsoft Foundry). It shares the Mythos rate-limit pool with Claude Mythos 5.
|
||||
`claude-mythos-5-1` is the same model as Claude Fable 5.1 - same capabilities, limits, and per-token pricing (including the $0.25/MTok cache-read rate), and the same API behavior except that the API enforces its history-editing check by default on the Claude API, Vertex and Foundry (breaking change 3) - offered only to verified organizations, and, apart from Claude Fable 5.2 and Claude Mythos 5.2, the only model besides Claude Fable 5.1 that reads Claude Fable 5.1's thinking blocks (it also reads Claude Mythos 5's; not the reverse). Confirm the organization's access with the account team before switching IDs. Two differences from a Claude Mythos 5 migrator's point of view: **Claude Mythos 5.1 runs safeguards** that depend on the access program the organization is approved under (Claude Mythos 5 ran none) - handle `stop_reason: "refusal"`, read `stop_details.category`, and set up fallback as on Claude Fable 5.1 (same targets, `claude-opus-4-8` and `claude-opus-5`; it mints a `fallback_credit_token` on refusals as Claude Fable 5.1 does) - and it is **not offered on Claude Platform on AWS** (Claude API, Amazon Bedrock as `anthropic.claude-mythos-5-1` with limited availability, Google Cloud, Microsoft Foundry). It shares the Mythos rate-limit pool with Claude Mythos 5.
|
||||
|
||||
### Capability improvements versus Claude Fable 5
|
||||
|
||||
@@ -1880,8 +1880,8 @@ The second tells it to hold the scope the user set:
|
||||
- [ ] **[BLOCKS]** Remove `tool_choice: {type: "any"}` and `{type: "tool", name: ...}` (400, also on `count_tokens` and Batches) - `auto` plus the instruction in the `user` turn (or an appended `role: "system"` message when the application requires the call), `strict: true` for schema-valid arguments, structured outputs for JSON extraction; delete any retry-on-missing-tool loop that depended on forcing
|
||||
- [ ] **[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]** 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`; enforcement scope is decided per model, and Claude Opus 5.5 also enforces it for new accounts only; on Claude Mythos 5.1, accounts of any age by default on the Claude API, Vertex and Foundry, and not by default on Amazon Bedrock): 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 (`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; the controls beta is also available on Claude Platform on AWS, Bedrock and Vertex, Foundry unconfirmed - `shared/platform-availability.md`), 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]** Keep passing `thinking` blocks back unchanged on every turn, including empty ones and `redacted_thinking` - the history-editing check can reject edited history
|
||||
- [ ] **[BLOCKS]** Preserved thinking / the history-editing check (with `prefix_mismatch_behavior` unset, a possible 400, as on Claude Opus 5.5, that on Bedrock and Vertex goes by first use of Claude there: breaking change 3; any request that sets the field is enforced; enforcement scope is decided per model: on Claude Mythos 5.1, every account by default on the Claude API, Vertex and Foundry): 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 (`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; the controls beta is also available on Claude Platform on AWS, Bedrock and Vertex, Foundry unconfirmed - `shared/platform-availability.md`), 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 for both Claude Fable 5.1 and Claude Mythos 5.1 (handle a `null` token)
|
||||
- [ ] **[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 and Claude Opus 5.5) where a conversation mixes hard and routine turns - 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`+
|
||||
@@ -1971,7 +1971,7 @@ if not any(block.type == "tool_use" for block in response.content):
|
||||
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, from earlier Opus, Sonnet, and Haiku models, and, on the Claude API and Google Cloud Vertex AI, from Claude Sonnet 5.5 and Claude Haiku 5.5 - a conversation that *moves onto* `claude-opus-5-5` keeps its reasoning - but **not** from any Fable or Mythos model. In the other direction, only Claude Fable 5.1 and Claude Mythos 5.1 on the Claude API, and Claude Fable 5.2 and Claude Mythos 5.2 (platforms: § Migrating to Claude Fable 5.2, breaking change 2), 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 read Claude Opus 5.5's blocks on other platforms is not documented - the docs state 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 and Managed Agents keep the prefix intact, and so does the Agent SDK if the system prompt you give it stays the same; **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` is designed to keep the retained turns' blocks valid after the swap on the Claude API, Claude Platform on AWS, Google Cloud, and Microsoft Foundry (the docs list the parameter for Amazon Bedrock, but not for keeping those blocks valid) - 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.
|
||||
- **Conversation binding - who is enforced.** Same posture as Claude Fable 5.1: with the field unset, a request that fails the prefix check (the `system` prompt, the `tools` array, and every earlier message must be byte-identical to when the block was produced) might or might not get a 400 (on Bedrock and Vertex, the 400 applies to accounts and projects that first used Claude there on or after August 31, 2026; earlier ones might or might not get it). With no 400, the model reads the outdated thinking, so handle both cases. Setting `thinking.block_binding.prefix_mismatch_behavior` on every request (`"error"` or `"drop_block"`, beta `thinking-binding-controls-2026-08-01`) gives one result. Claude Code, claude.ai and Managed Agents keep the prefix intact, and so does the Agent SDK if the system prompt you give it stays the same; **if your code builds `messages` itself, run the three-step check before migrating** - and do it now even if your requests get no error, 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` is designed to keep the retained turns' blocks valid after the swap on the Claude API, Claude Platform on AWS, Google Cloud, and Microsoft Foundry (the docs list the parameter for Amazon Bedrock, but not for keeping those blocks valid) - 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
|
||||
@@ -2086,7 +2086,7 @@ The classifiers can still flag benign requests - the fallback opt-in is what kee
|
||||
- [ ] **[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 on the Claude API and Google Cloud: declare `{"type": "computer_toolset_20260801"}` (no beta header, no `name` / display size) instead of `computer_20251124` (Amazon Bedrock still accepts `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]** If the harness builds `messages` itself: run the preserved-thinking three-step check (§ Migrating to Claude Fable 5.1 from Claude Fable 5) - with the field unset, a failed check might or might not be a 400 (on Bedrock and Vertex it goes by first use of Claude there: "Conversation binding" above); 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` (`bio` is a new category) 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.
|
||||
@@ -2169,7 +2169,7 @@ As on Claude Fable 5.1 and Claude Opus 5.5: `tool_choice: {"type": "any"}` and `
|
||||
### Breaking change 3: thinking blocks are tied to the model and the conversation
|
||||
|
||||
- **Model binding - who reads whose blocks.** Claude Sonnet 5.5 reads thinking blocks from Claude Sonnet 5, Claude Opus 4.8, Claude Haiku 4.5, and earlier models, and, on the Claude API and Google Cloud Vertex AI, from Claude Haiku 5.5 - a conversation that moves from Claude Sonnet 5 onto `claude-sonnet-5-5` keeps its reasoning - but **not** from Claude Opus 5, Claude Opus 5.5, or any Claude Fable or Claude Mythos model. **On the Claude API and Google Cloud Vertex AI, Claude Opus 5.5 reads Claude Sonnet 5.5 blocks. Claude Fable 5.2 and Claude Mythos 5.2 read them too (platforms: § Migrating to Claude Fable 5.2, breaking change 2); no other model does.** A conversation that moves from Claude Sonnet 5.5 up to Claude Opus 5.5 on those platforms, or up to Claude Fable 5.2 or Claude Mythos 5.2 on the platforms named there, keeps its reasoning. Any other move away from Claude Sonnet 5.5 - for example a router switch or retry to another model, or a server-side fallback to Claude Sonnet 5 - runs the turns after the switch without it. 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` beta header the drop is reported in a top-level `input_transformations` array. Keep passing blocks back unchanged; don't strip them yourself.
|
||||
- **Conversation binding - the history-editing check.** The API checks that the `system` prompt, the `tools`, and every earlier message are unchanged since a block was produced. It is enforced by default for accounts created on or after August 31, 2026, 00:00 UTC (a new account is defined the same way on the Claude API and on cloud platforms): on those accounts a request that replays a block after such an edit is a 400. To drop the affected blocks instead, send the `thinking-binding-controls-2026-08-01` beta header and set `thinking.block_binding.prefix_mismatch_behavior: "drop_block"`; on older accounts, setting that field to either value opts the request in. **`block_binding` works only with `thinking: {"type": "adaptive"}`** - with `between_tools`, keep the history append-only, or strip the thinking blocks from the edited turn on. The append-only replacements (mid-conversation `role: "system"` messages, which Claude Sonnet 5.5 supports and Claude Sonnet 5 doesn't; `tool_addition` / `tool_removal`; turn-scoped reminders; server-side compaction or context editing) and the three-step check are in § Migrating to Claude Fable 5.1 from Claude Fable 5. With threshold compaction, thinking blocks from before a `compaction` block aren't carried forward, so the summary is all the model has of that earlier work - if you write your own `instructions`, say what the summary must retain - and remove the `thinking` and `redacted_thinking` blocks from any assistant turn you re-insert after a compaction block (or set `drop_block`). On-demand compaction (beta `compact-2026-09-04`) can keep the kept turns' blocks valid after you replace the summarized turns with the returned `compaction` block; the docs list this on the Claude API, Claude Platform on AWS, Google Cloud, and Microsoft Foundry, not on Amazon Bedrock.
|
||||
- **Conversation binding - the history-editing check.** The API checks that the `system` prompt, the `tools`, and every earlier message are unchanged since a block was produced. With `prefix_mismatch_behavior` unset, a request that replays a block after such an edit might or might not get a 400 (on Bedrock and Vertex, the 400 applies to accounts and projects that first used Claude there on or after August 31, 2026; earlier ones might or might not get it). With no 400, the model reads the outdated thinking, so handle both cases. To drop the affected blocks instead, send the `thinking-binding-controls-2026-08-01` beta header and set `thinking.block_binding.prefix_mismatch_behavior: "drop_block"`; setting that field to either value on every request gives one result. **`block_binding` works only with `thinking: {"type": "adaptive"}`** - with `between_tools`, keep the history append-only, or strip the thinking blocks from the edited turn on. The append-only replacements (mid-conversation `role: "system"` messages, which Claude Sonnet 5.5 supports and Claude Sonnet 5 doesn't; `tool_addition` / `tool_removal`; turn-scoped reminders; server-side compaction or context editing) and the three-step check are in § Migrating to Claude Fable 5.1 from Claude Fable 5. With threshold compaction, thinking blocks from before a `compaction` block aren't carried forward, so the summary is all the model has of that earlier work - if you write your own `instructions`, say what the summary must retain - and remove the `thinking` and `redacted_thinking` blocks from any assistant turn you re-insert after a compaction block (or set `drop_block`). On-demand compaction (beta `compact-2026-09-04`) can keep the kept turns' blocks valid after you replace the summarized turns with the returned `compaction` block; the docs list this on the Claude API, Claude Platform on AWS, Google Cloud, and Microsoft Foundry, not on Amazon Bedrock.
|
||||
- **Account binding.** A block Claude Sonnet 5.5 produced works only in the account that produced it, or in an account linked to it; another account's blocks are dropped and the request succeeds (on the Claude API and Google Cloud Vertex AI, with the `thinking-binding-controls-2026-08-01` header, each drop is listed in `input_transformations` with `reason: "organization_binding_mismatch"`). The same rule covers Claude Haiku 5.5 blocks; blocks from earlier models aren't affected.
|
||||
|
||||
### Breaking change 4: computer use needs the toolset on the Claude API and Google Cloud
|
||||
@@ -2214,7 +2214,7 @@ Claude Sonnet 5.5 declines in more categories than Claude Sonnet 5. A decline is
|
||||
|
||||
### What carries over, and what is new versus Claude Sonnet 5
|
||||
|
||||
- **New on Claude Sonnet 5.5:** mid-conversation system messages (no beta header), mid-conversation tool changes (beta), per-message effort (beta), task budgets (beta `task-budgets-2026-03-13` - but see § Behavioral shifts on interactive sessions), and tool definitions inside a mid-conversation message (beta `inline-tools-2026-09-15`) - none is available on Claude Sonnet 5.
|
||||
- **New on Claude Sonnet 5.5:** mid-conversation system messages (no beta header), mid-conversation tool changes (beta), per-message effort (beta), task budgets (beta `task-budgets-2026-03-13`), and tool definitions inside a mid-conversation message (beta `inline-tools-2026-09-15`) - none is available on Claude Sonnet 5.
|
||||
- **Prompt caching:** the minimum cacheable prompt is 512 tokens, down from 1,024 on Claude Sonnet 5 (check the prompt caching docs before quoting the exact value).
|
||||
- **Carries over:** batch processing, the Files API, PDF support, vision, structured outputs, strict tool use, threshold compaction, compaction on demand (beta `compact-2026-09-04`), and the server-side and client-side tools (computer use as in breaking change 4; on Microsoft Foundry, only what it offers when hosted on Azure).
|
||||
- **Rate limits and tiers:** its own rate-limit pool, separate from Claude Sonnet 5's and from Claude Sonnet 4.6's - re-check the tier's Claude Sonnet 5.5 limits before moving volume. Priority Tier is not supported (as on Claude Sonnet 5).
|
||||
@@ -2226,11 +2226,11 @@ None of these break code. Re-evaluate Claude Sonnet 5-specific prompt instructio
|
||||
|
||||
- **Remove workarounds for what got better.** The model is strongest on multistep agentic coding in a real repository, uses connected tools more reliably in agentic workflows, declines fewer benign requests, and holds a system-prompt role more reliably when a user pastes in a competing persona. If the Claude Sonnet 5 prompts carry workarounds for these - refusal steering, tool-call retry shims, instructions like "do not be lazy" - remove them and re-run the evals before tuning anything else.
|
||||
- **Tool use in chat and knowledge work.** On chat and knowledge-work tasks the model sometimes answers from its own knowledge or from public web results when a connected tool, skill, or internal search would serve better, and can hold off on tools until asked directly. Remove language that discourages tool use ("only use tools when strictly necessary", "minimize tool calls" - it follows these literally). Where the product should prefer connected sources (enterprise search, account research, support agents), add: *"Use the search tool to check specifics that may have changed since your training, such as what is allowed, required or charged, even when you feel confident. For researched work such as a report or a comparison, gather current sources rather than writing from your training knowledge."*
|
||||
- **Mid-turn user messages and task budgets.** The model pays close attention to where text sits relative to a tool result: a message the user typed mid-task that arrives as a mid-conversation system message placed directly after a tool result, or inside a `tool_result` block, can be read as a prompt-injection attempt (the model says so and usually ignores it or waits for confirmation). Task budgets can cause this, because the budget countdown arrives as a system message after every tool result, and so can any harness text added after the tool results on every step (a token countdown, per-step instructions or context); an occasional one-turn reminder arrives far less often - if one draws this reaction, send it less often. Deliver mid-turn user input as a user turn - a text block in the user message that carries the `tool_result` blocks, after the last `tool_result`; keep harness notices (budget countdowns, background-task completions, reminders) in a separate mid-conversation system message that follows, never in the same block as the user's words; never put user text inside a `tool_result` block; and on interactive sessions don't use a task budget (control cost with effort and `max_tokens`; keep task budgets for unattended agentic loops).
|
||||
- **Mid-turn user messages.** The model pays close attention to where text sits relative to a tool result: a message the user typed mid-task that arrives as a mid-conversation system message placed directly after a tool result, or inside a `tool_result` block, can be read as a prompt-injection attempt (the model can say so and ignore the message or ask the user to confirm it). A token countdown the harness adds after every tool result can cause this, and so can letting users send messages partway through a multistep turn, or any harness text added after the tool results on every step (per-step instructions or context); an occasional one-turn reminder arrives far less often - if one draws this reaction, send it less often. Deliver mid-turn user input as a user turn - a text block in the user message that carries the `tool_result` blocks, after the last `tool_result`; keep harness notices, such as reminders, in a separate mid-conversation system message that follows, never in the same block as the user's words; never put user text inside a `tool_result` block; and in interactive sessions where users can type mid-turn, don't add your own token or budget countdown after tool results. Task budgets (beta) add a similar countdown but haven't been seen to cause this misread; if it shows up while a task budget is set, try the session without one.
|
||||
- **Verification on coding tasks.** Mostly at `low` effort, the model sometimes reports a code change as done without a check that exercises it (no `npm install`, so the tests and type-checker never ran; only a syntax check; stopping silently when a build tool is missing). If a coding agent runs at `low`, or changes are reported complete without test or build output, add to the system prompt: *"When you change code that can be run, built, or type-checked, run a real check that exercises the change before reporting it done: the project's tests, type-checker, or build, or the changed command itself. A syntax-only check, or a check command that failed to start, does not count; if all that is missing is the project's declared dependencies, install them with its own package manager (e.g. npm install, pip install -r requirements.txt) unless told not to. Only if no real check can run here, say which one you did not run and why instead of reporting the change as done."*
|
||||
- **Tolerant tool-call handling.** The model occasionally calls a declared tool by a name that differs only in letter case (`bash` for `Bash`), or passes a known parameter under a slightly different name. Don't treat that as fatal: accept the call when the match is unambiguous, or return a `tool_result` with `is_error: true` that states the exact expected name - the model usually corrects the call on its next turn.
|
||||
- **Dense charts and technical drawings.** Give the model a way to crop, zoom, or run code on the image; it reads them markedly more accurately with such tools. On charts the tools help at every effort level and more than raising effort does (with tools at `high` it read charts more accurately than without them at `max`, at a fraction of the cost); on technical drawings they help only from `high` up, most at `xhigh` and `max`.
|
||||
- **Follow-up turns in multi-turn chat.** If the model should treat its earlier answers as settled rather than going back over them when it thinks about a new message, add at the end of the system prompt: *"Once Claude has answered something, Claude treats that answer as done. On later turns Claude's thinking goes to what the person is asking now, and Claude doesn't go back over an earlier answer unless the person asks about it or points out a problem with it."* Leave it out where earlier work should keep being re-examined - long analyses, or agentic tasks where a later step can reveal a mistake in an earlier one.
|
||||
- **Follow-up turns in multi-turn chat.** If the model should treat its earlier answers as settled rather than going back over them when it thinks about a new message, add at the end of the system prompt: *"Once Claude has answered something, Claude treats that answer as done. On later turns Claude's thinking goes to what the person is asking now, and Claude doesn't go back over an earlier answer unless the person asks about it or points out a problem with it."* Leave it out where earlier work should keep being re-examined - long analyses, or agentic tasks where a later step can reveal a mistake in an earlier one. The line may also make the model less likely to point out a mistake in an earlier answer on its own; if that matters for the application, test for it before adopting the line, especially where the history can hold answers another model wrote or earlier turns sent back without their thinking.
|
||||
|
||||
### Claude Sonnet 5.5 Migration Checklist
|
||||
|
||||
@@ -2239,13 +2239,13 @@ None of these break code. Re-evaluate Claude Sonnet 5-specific prompt instructio
|
||||
- [ ] **[BLOCKS]** Coming from Sonnet 4.6 or earlier or from Haiku 4.5: replace `budget_tokens` with an effort level and remove non-default `temperature` / `top_p` / `top_k` (on API version `2026-10-21`, remove them at any value); from Sonnet 4.5 or earlier or Haiku 4.5, also replace assistant prefills.
|
||||
- [ ] **[BLOCKS]** Read content blocks by `type` (a response can begin with `thinking` blocks) and pass `thinking` blocks back unchanged; size `max_tokens` for thinking plus the reply.
|
||||
- [ ] **[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` too.
|
||||
- [ ] **[BLOCKS]** If the harness builds `messages` itself: keep it append-only and run the preserved-thinking three-step check (§ Migrating to Claude Fable 5.1 from Claude Fable 5) - new accounts are enforced by default; `block_binding` needs adaptive thinking.
|
||||
- [ ] **[BLOCKS]** If the harness builds `messages` itself: keep it append-only and run the preserved-thinking three-step check (§ Migrating to Claude Fable 5.1 from Claude Fable 5) - with `prefix_mismatch_behavior` unset, a failed check might or might not be a 400; `block_binding` needs adaptive thinking.
|
||||
- [ ] **[BLOCKS]** On the Claude API and Google Cloud, move computer use to `computer_toolset_20260801` and update the agent loop; on Amazon Bedrock send `computer_20251124`.
|
||||
- [ ] **[BLOCKS]** Advisor tool: pair the executor with an accepted advisor (not Claude Opus 4.8 / 4.7 / 4.6, Claude Sonnet 5, or Sonnet 4.6) and expect encrypted `advisor_redacted_result` advice.
|
||||
- [ ] **[BLOCKS]** Handle `stop_reason: "refusal"` before reading `content` (five categories) and configure fallback; only `cyber` and `frontier_llm` declines are retried by server-side fallback.
|
||||
- [ ] **[TUNE]** Re-run the effort sweep and set `effort` explicitly (start at `medium` for agentic coding, `low` for chat); lower effort rather than prompting for less thinking; use per-message effort to vary it without losing the cache.
|
||||
- [ ] **[TUNE]** If the UI showed text between tool calls: `display: "updates"` (beta) or `"summarized"` with adaptive thinking, render non-empty `thinking` blocks; declare any send-message tool at session start; remove "hold all findings" instructions; if turns still go quiet, a turn-scoped reminder after about five silent steps, at most two or three times.
|
||||
- [ ] **[TUNE]** Prompts: remove workarounds (refusal steering, tool-call retry shims, "do not be lazy") and tool-discouraging language; deliver mid-turn user input as a user turn and drop task budgets on interactive sessions; add the verification paragraph for low-effort coding agents; accept or correct near-miss tool names instead of failing; give crop/zoom/code tools for dense charts and drawings; the settled-answers line for multi-turn chat where it fits.
|
||||
- [ ] **[TUNE]** Prompts: remove workarounds (refusal steering, tool-call retry shims, "do not be lazy") and tool-discouraging language; deliver mid-turn user input as a user turn, with no harness token countdown after tool results on interactive sessions; add the verification paragraph for low-effort coding agents; accept or correct near-miss tool names instead of failing; give crop/zoom/code tools for dense charts and drawings; the settled-answers line for multi-turn chat where it fits.
|
||||
- [ ] **[TUNE]** Re-baseline cost and latency at the chosen effort level (same prices as Claude Sonnet 5, except cache reads at $0.10; own rate-limit pool; no Priority Tier).
|
||||
|
||||
---
|
||||
@@ -2344,7 +2344,7 @@ Count prompts with `model` set to `claude-haiku-5-5` rather than reusing counts
|
||||
|
||||
### Breaking change 5: editing earlier turns invalidates thinking blocks
|
||||
|
||||
A Claude Haiku 5.5 thinking block stays valid only while everything sent before it is unchanged: a request that sends a thinking block back after a change to `system`, `tools`, or earlier `messages` returns a 400. Claude Haiku 4.5 doesn't run this check. It is the history-editing check Claude Fable 5.1, Claude Opus 5.5, and Claude Sonnet 5.5 run: enforced by default for accounts created on or after August 31, 2026, 00:00 UTC, and on older accounts only for requests that set `thinking.block_binding.prefix_mismatch_behavior`. Keep conversations append-only - the append-only replacements (mid-conversation `role: "system"` messages, which Claude Haiku 5.5 supports with no beta header; turn-scoped reminders; server-side compaction or context editing) and the three-step check are in § Migrating to Claude Fable 5.1 from Claude Fable 5. As on Claude Sonnet 5.5, **`block_binding` works only with `thinking: {"type": "adaptive"}`**: with `{"type": "disabled"}`, keep the history append-only, or strip the thinking blocks from the edited turn on. With threshold compaction, thinking blocks from before a `compaction` block aren't carried forward; remove the `thinking` and `redacted_thinking` blocks from any assistant turn re-inserted after a compaction block (or set `drop_block`).
|
||||
A Claude Haiku 5.5 thinking block stays valid only while everything sent before it is unchanged: a request that sends a thinking block back after a change to `system`, `tools`, or earlier `messages` can return a 400. Claude Haiku 4.5 doesn't run this check. It is the history-editing check Claude Fable 5.1, Claude Opus 5.5, and Claude Sonnet 5.5 run: with `thinking.block_binding.prefix_mismatch_behavior` unset, a request that fails it might or might not get a 400 (on Bedrock and Vertex, the 400 applies to accounts and projects that first used Claude there on or after August 31, 2026; earlier ones might or might not get it). Keep conversations append-only - the append-only replacements (mid-conversation `role: "system"` messages, which Claude Haiku 5.5 supports with no beta header; turn-scoped reminders; server-side compaction or context editing) and the three-step check are in § Migrating to Claude Fable 5.1 from Claude Fable 5. As on Claude Sonnet 5.5, **`block_binding` works only with `thinking: {"type": "adaptive"}`**: with `{"type": "disabled"}`, keep the history append-only, or strip the thinking blocks from the edited turn on. With threshold compaction, thinking blocks from before a `compaction` block aren't carried forward; remove the `thinking` and `redacted_thinking` blocks from any assistant turn re-inserted after a compaction block (or set `drop_block`).
|
||||
|
||||
### Thinking blocks stay with the account that produced them
|
||||
|
||||
@@ -2401,7 +2401,7 @@ None of these break code. Check the caller's prompts against them once the effor
|
||||
- [ ] **[BLOCKS]** Remove `temperature`, `top_p`, and `top_k`.
|
||||
- [ ] **[BLOCKS]** Replace assistant prefills and end `messages` with a user turn.
|
||||
- [ ] **[BLOCKS]** On the Claude API and Google Cloud, move computer use from `computer_20250124` to `computer_toolset_20260801`, update the agent loop, drop the `computer-use-2025-01-24` beta header, and replace `fine-grained-tool-streaming-2025-05-14` with `eager_input_streaming: true` on each tool that needs it.
|
||||
- [ ] **[BLOCKS]** If the harness changes `system`, `tools`, or earlier `messages` between requests and sends thinking blocks back: keep the conversation append-only (new accounts are enforced by default; `block_binding` needs adaptive thinking).
|
||||
- [ ] **[BLOCKS]** If the harness changes `system`, `tools`, or earlier `messages` between requests and sends thinking blocks back: keep the conversation append-only (with `prefix_mismatch_behavior` unset, a failed check might or might not be a 400; `block_binding` needs adaptive thinking).
|
||||
- [ ] **[BLOCKS]** Handle `stop_reason: "refusal"` before reading `content` (four categories; new for code coming from Claude Haiku 4.5); don't send `fallbacks` - there is no server-side fallback for this model.
|
||||
- [ ] **[TUNE]** Recount prompts with `count_tokens` against `claude-haiku-5-5`; revisit `max_tokens`, context budgets, and cost estimates (two rate cards, split at a 100K-token prompt).
|
||||
- [ ] **[TUNE]** Try two or three effort levels on your evals and set `effort` explicitly (default `medium`; `low` for chat and simple, high-volume routes; `high` for knowledge work and strict instruction following; compare `xhigh` / `max` against Claude Sonnet 5.5); use per-message effort (beta, adaptive thinking only) to vary it without losing the cache.
|
||||
@@ -2436,7 +2436,7 @@ The typed SDK constants (`Model.ClaudeFable5_2` in C#, `anthropic.ModelClaudeFab
|
||||
|
||||
### Breaking change 1: the history-editing check applies to every account
|
||||
|
||||
Each `thinking` block from Claude Fable 5.2 is valid only against the `system` prompt, `tools`, and conversation history that preceded it, as on Claude Fable 5.1. What changes is who is enforced: **on Claude Fable 5.2 and Claude Mythos 5.2, the check is enforced for every account, whatever its age**. The docs' table of results by model (`https://platform.claude.com/docs/en/build-with-claude/preserved-thinking/prefix-checks#outcomes`) applies on the Claude API and the cloud platforms in the Preserved thinking page's availability list. Claude Fable 5.1 (like Claude Opus 5.5, Claude Sonnet 5.5 and Claude Haiku 5.5) enforces it by default only for accounts created on or after August 31, 2026, while Claude Mythos 5.1 enforces it by default whatever the account's age on the Claude API, Google Cloud Vertex AI, and Microsoft Foundry. So on an older account, requests that pass on Claude Fable 5.1 can fail on Claude Fable 5.2.
|
||||
Each `thinking` block from Claude Fable 5.2 is valid only against the `system` prompt, `tools`, and conversation history that preceded it, as on Claude Fable 5.1. What changes is the result of a failed check: **on Claude Fable 5.2 and Claude Mythos 5.2, it is a 400 for every account** unless the request sets `"drop_block"`. The docs' table of results by model (`https://platform.claude.com/docs/en/build-with-claude/preserved-thinking/prefix-checks#outcomes`) applies on the Claude API and the cloud platforms in the Preserved thinking page's availability list. On Claude Fable 5.1 (like Claude Opus 5.5, Claude Sonnet 5.5 and Claude Haiku 5.5) a request that fails the check might or might not get a 400 (on Bedrock and Vertex, the 400 applies to accounts and projects that first used Claude there on or after August 31, 2026; earlier ones might or might not get it), while Claude Mythos 5.1 enforces it by default on the Claude API, Google Cloud Vertex AI, and Microsoft Foundry. So requests that pass on Claude Fable 5.1 can fail on Claude Fable 5.2.
|
||||
|
||||
A request that sends a thinking block back after an edit to `system`, `tools`, or an earlier message returns a 400 (`... The block is bound to a different conversation. ...`), and retrying the same body doesn't clear it. Nothing changes when Claude Code, claude.ai or Claude Managed Agents manages the conversation history, when the Claude Agent SDK does and the system prompt you give it stays the same, or when the code keeps `system` and `tools` the same for the whole conversation, only adds to `messages`, sends each assistant turn back exactly as returned, and does none of the things the Prefix checks page counts as a change (`https://platform.claude.com/docs/en/build-with-claude/preserved-thinking/prefix-checks#what-counts-as-an-edit`), such as sending a URL whose bytes change or an MCP tool list that isn't pinned. Otherwise:
|
||||
|
||||
@@ -2468,13 +2468,13 @@ With the advisor tool (beta), the advisor must be at least as capable as the exe
|
||||
|
||||
Apply the Claude Fable 5.1 sections as the layering paragraph says, with these Claude Fable 5.2 specifics:
|
||||
|
||||
- **From Claude Opus 5.5:** both models always think adaptively and reject forced `tool_choice`, so those parts carry over. What differs: 30-day data retention is required (an organization running Claude Opus 5.5 under ZDR gets a 400 on every request until a workspace has retention enabled); the history-editing check applies to every account, where Claude Opus 5.5 enforces it only on newer accounts; Claude Opus 5.5 can't read Claude Fable 5.2's thinking blocks (Claude Fable 5.2 reads Claude Opus 5.5's on the platforms in breaking change 2); the default effort is `high`, not `medium`, so a request that omits `effort` runs one level higher - set it explicitly; fast mode differs (keep `speed: "fast"` only where Claude Fable 5.2 supports it, per SKILL.md -> Fast Mode, and re-baseline cost; remove `speed` in Managed Agents, and wherever you remove it, remove the `fast-mode-2026-02-01` beta header too if you send it); in an organization using customer-managed encryption keys (CMEK), structured outputs aren't available (remove `strict: true` and `output_config.format` and validate in code); the price is $8 / $40 against $4 / $20, with cache reads $0.20 on both; the rate limit is separate, with lower token limits at each tier; and the advisor pairing above.
|
||||
- **From Claude Opus 5.5:** both models always think adaptively and reject forced `tool_choice`, so those parts carry over. What differs: 30-day data retention is required (an organization running Claude Opus 5.5 under ZDR gets a 400 on every request until a workspace has retention enabled); with `prefix_mismatch_behavior` unset, a request that fails the history-editing check gets a 400, where on Claude Opus 5.5 it might or might not; Claude Opus 5.5 can't read Claude Fable 5.2's thinking blocks (Claude Fable 5.2 reads Claude Opus 5.5's on the platforms in breaking change 2); the default effort is `high`, not `medium`, so a request that omits `effort` runs one level higher - set it explicitly; fast mode differs (keep `speed: "fast"` only where Claude Fable 5.2 supports it, per SKILL.md -> Fast Mode, and re-baseline cost; remove `speed` in Managed Agents, and wherever you remove it, remove the `fast-mode-2026-02-01` beta header too if you send it); in an organization using customer-managed encryption keys (CMEK), structured outputs aren't available (remove `strict: true` and `output_config.format` and validate in code); the price is $8 / $40 against $4 / $20, with cache reads $0.20 on both; the rate limit is separate, with lower token limits at each tier; and the advisor pairing above.
|
||||
- **From Claude Opus 5:** the Claude Opus 5.5 list above, except that Claude Opus 5 already defaults to `high`, doesn't run the history-editing check at all, and costs $5 / $25 (cache reads $0.50). Plus: `thinking: {type: "disabled"}` returns a 400 at every effort level (remove the field, lower effort, revisit `max_tokens`, and select content blocks by `type`); forced `tool_choice` returns a 400; text between tool calls comes back as progress-update `thinking` blocks, at most one before each tool call (set `display: "updates"` (beta, see below) or `"summarized"` and render the non-empty blocks); and the safety classifiers cover more `stop_details` categories, `"bio"` among them.
|
||||
- **From Opus 4.8 or earlier:** the Claude Opus 5 list above, plus: thinking runs on requests that omit it (thinking tokens bill as output and count toward `max_tokens`); the minimum cacheable prompt drops from 1,024 to 512 tokens; Priority Tier isn't supported; advice from the advisor tool always arrives encrypted; and `speed` must stay out of any request still sent to Claude Opus 4.8, such as a retry, because `speed: "fast"` returns an error there. From Opus 4.7 or earlier, first apply the sections listed in that model's § Destination Models row, up to and including Opus 4.8. Use this order, not the one in § Migrating to Claude Fable 5.1 from Claude Fable 5. In a CMEK organization, remove `output_format` and validate in code instead of moving to `output_config.format`.
|
||||
|
||||
### Claude Mythos 5.2
|
||||
|
||||
Moving from Claude Mythos 5.1 to Claude Mythos 5.2 follows the same steps as moving to Claude Fable 5.2, but the history-editing check changes little: on the Claude API, Google Cloud Vertex AI, and Microsoft Foundry, Claude Mythos 5.1 already returns the same 400 on every account. On Amazon Bedrock, that 400 is new with Claude Mythos 5.2: Claude Mythos 5.1 accepts edited earlier turns there. On every platform, run the three-step check against `claude-mythos-5-2` before switching. On the platforms in breaking change 2, where it is offered, Claude Mythos 5.2 reads Claude Mythos 5.1's and Claude Mythos 5's blocks. Neither reads its blocks on any platform. Coming from Claude Mythos 5, the forced `tool_choice` 400 applies too. **Rate limits:** Claude Mythos 5.2 shares one combined limit with Claude Mythos 5.1 and Claude Mythos 5, while Claude Fable 5.2 has its own limit, separate from the combined one Claude Fable 5.1 and Claude Fable 5 share - check the tier's limits before moving production traffic.
|
||||
Moving from Claude Mythos 5.1 to Claude Mythos 5.2 follows the same steps as moving to Claude Fable 5.2, but the history-editing check changes little: on the Claude API, Google Cloud Vertex AI, and Microsoft Foundry, Claude Mythos 5.1 already returns the same 400 on every account. On every platform, run the three-step check against `claude-mythos-5-2` before switching. On the platforms in breaking change 2, where it is offered, Claude Mythos 5.2 reads Claude Mythos 5.1's and Claude Mythos 5's blocks. Neither reads its blocks on any platform. Coming from Claude Mythos 5, the forced `tool_choice` 400 applies too. **Rate limits:** Claude Mythos 5.2 shares one combined limit with Claude Mythos 5.1 and Claude Mythos 5, while Claude Fable 5.2 has its own limit, separate from the combined one Claude Fable 5.1 and Claude Fable 5 share - check the tier's limits before moving production traffic.
|
||||
|
||||
### Structured outputs, safeguards and fallback
|
||||
|
||||
|
||||
@@ -77,13 +77,13 @@ curl https://api.anthropic.com/v1/models/claude-opus-4-8 \
|
||||
### Model Descriptions
|
||||
- **Claude Fable 5.2** - Anthropic's most capable model open to all customers, for demanding reasoning and long-horizon agentic work; the current Fable. Successor to Claude Fable 5.1 at a lower price ($8 / $40 per MTok; cache reads $0.20/MTok - 0.025x; 5-minute cache writes $10, 1-hour $16; batch $4 / $20). Same API surface as Claude Fable 5.1 (thinking always on, default effort `high`, no prefill, no sampling params, forced `tool_choice` 400s, `refusal` stop reason, 512-token cache minimum, same tokenizer, 1M context, 128K max output) with four breaking changes: the history-editing check is enforced for **every** account; no model released earlier reads its thinking blocks, Claude Fable 5.1 included (Claude Fable 5.2 reads theirs on the Claude API and, where offered, Google Cloud Vertex AI); the earlier `computer_20251124` computer use tool returns a 400 on every platform except Amazon Bedrock (use `computer_toolset_20260801`); and with the advisor tool a Claude Fable 5.2 executor accepts only `claude-fable-5-2` or `claude-mythos-5-2` as its advisor. Thinking blocks work only in the account that produced them or one linked to it. Structured outputs are not available in a CMEK organization. Covered Model: 30-day retention required - ZDR orgs get `400 invalid_request_error`. No Priority Tier; fast mode: SKILL.md -> Fast Mode; its own rate limit, separate from the one Claude Fable 5.1 and Claude Fable 5 share. For most workloads start with Claude Opus 5.5 and move here when evals at higher effort still fall short. See `shared/model-migration.md` -> Migrating to Claude Fable 5.2.
|
||||
- **Claude Mythos 5.2** - The same model as Claude Fable 5.2 (same capabilities, limits, per-token pricing and API behavior, the every-account history-editing check included), available only to organizations verified through Anthropic's verification programs, such as the Cyber Verification Program. Available on the Claude API and Claude Models on Google Cloud (Anthropic managed); confirm other platforms on its docs page (the docs don't list it for Claude Platform on AWS). Shares one combined rate limit with Claude Mythos 5.1 and Claude Mythos 5. Use it only when the org has that access; otherwise use `claude-fable-5-2`.
|
||||
- **Claude Fable 5.1** - The previous Fable, still served and selectable by id; prefer `claude-fable-5-2` for new 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 (and the later Claude Fable 5.2 and Claude Mythos 5.2) 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 beta is on the Claude API, Claude Platform on AWS, Bedrock, and Vertex - Foundry unconfirmed, `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 a rate-limit pool with Claude Fable 5. See `shared/model-migration.md` -> Migrating to Claude Fable 5.1 from Claude Fable 5.
|
||||
- **Claude Fable 5.1** - The previous Fable, still served and selectable by id; prefer `claude-fable-5-2` for new 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 (and the later Claude Fable 5.2 and Claude Mythos 5.2) can read them - other models drop them); and editing earlier turns invalidates thinking blocks ("preserved thinking"; edited history might or might not get a 400 (on Bedrock and Vertex, the 400 applies to accounts and projects that first used Claude there on or after August 31, 2026; earlier ones might or might not get it), and enforcement scope is decided per model; the opt-in controls beta is on the Claude API, Claude Platform on AWS, Bedrock, and Vertex - Foundry unconfirmed, `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 a rate-limit pool with Claude Fable 5. 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`) - an earlier Fable / Mythos release: same tier, limits and per-token pricing as Claude Fable 5.1, except cache reads at $1/MTok rather than $0.25; Claude Fable 5.1 adds three breaking API changes over them (see above). 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-2` for new work.
|
||||
- **Claude Mythos 5.1** - The previous Mythos: the same model as Claude Fable 5.1 (same capabilities, limits, per-token pricing, API behavior - except that the API enforces its history-editing check by default whatever the account's age on the Claude API, Vertex and Foundry; on Amazon Bedrock, not by default), offered only to verified organizations; 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. Prefer `claude-mythos-5-2` for new work where the org has access; otherwise use `claude-fable-5-2`.
|
||||
- **Claude Mythos 5.1** - The previous Mythos: the same model as Claude Fable 5.1 (same capabilities, limits, per-token pricing, API behavior - except that the API enforces its history-editing check by default on the Claude API, Vertex and Foundry), offered only to verified organizations; 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. Prefer `claude-mythos-5-2` for new work where the org has access; otherwise use `claude-fable-5-2`.
|
||||
- **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` joins `cyber` and `reasoning_extraction`). The current Opus and the default model; 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 (the Fable models remain 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.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.8** - The most capable model in the Opus 4 series - highly autonomous, strong 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** - Older 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.6** - Older Opus. Supports adaptive thinking (recommended), 128K max output tokens (requires streaming for large outputs). 1M context window.
|
||||
- **Claude Sonnet 5** - The previous Sonnet; near-Opus quality on coding and agentic work. Adaptive thinking on by default (omitting `thinking` runs adaptive); manual `budget_tokens` removed; non-default sampling parameters rejected (on API version `2026-10-21`, any value is rejected). `effort` supports `low`/`medium`/`high`/`xhigh`/`max`. New tokenizer (~30% more tokens for the same text vs Sonnet 4.6). High-resolution vision (2576px). 1M context window, 128K max output. See `shared/model-migration.md` -> Migrating to Claude Sonnet 5.
|
||||
- **Claude Sonnet 5.5** - Successor to Claude Sonnet 5 in the Sonnet line, at the same prices ($2 / $10 per MTok), except cache reads at $0.10. Same tokenizer as Claude Sonnet 5; 1M context, 128K max output. Adaptive thinking on by default; effort default `high`, with recalibrated levels. Five breaking changes: `thinking: {type: "disabled"}` returns a 400 (send `{type: "between_tools"}` at effort `high` or below to turn thinking off), forced `tool_choice` 400s, thinking blocks are tied to the model and the conversation, computer use on the Claude API and Google Cloud needs the `computer_toolset_20260801` toolset, and the advisor tool rejects Claude Opus 4.8, Claude Opus 4.7, and Claude Sonnet 5 advisors. See `shared/model-migration.md` -> Migrating to Claude Sonnet 5.5.
|
||||
|
||||
@@ -48,15 +48,15 @@ Columns: **1P** = first-party Claude API, **P-AWS** = Claude Platform on AWS (An
|
||||
| Files API | Yes | Yes | No | No | Yes | Foundry: Hosted on Anthropic deployments only - Hosted on Azure returns a 400 |
|
||||
| Models API | Yes | Yes | No | No | No | |
|
||||
| **Other** | | | | | | |
|
||||
| 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 Fable 5.2, Claude Mythos 5, Claude Mythos 5.1, Claude Mythos 5.2, Claude Sonnet 5.5, Claude Haiku 5.5; not Claude Sonnet 5. Bedrock's InvokeModel API takes them on fewer models: no ARN-versioned models and no older Mythos models |
|
||||
| Mid-conversation tool changes | beta | beta | beta | beta | No | Same models as mid-conversation system messages. By reference: beta `mid-conversation-tool-changes-2026-07-01`. By value or by reference, on the Claude API, Claude Platform on AWS and Claude Models on Google Cloud (Anthropic managed): beta `inline-tools-2026-09-15`. Bedrock: not through the InvokeModel API, per the docs |
|
||||
| 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) |
|
||||
| Mid-conversation system messages | Yes | Yes | Yes | Yes | Yes | Claude Opus 5, Claude Opus 5.5, Claude Opus 4.8, Claude Fable 5, Claude Fable 5.1, Claude Fable 5.2, Claude Mythos 5, Claude Mythos 5.1, Claude Mythos 5.2, Claude Sonnet 5.5, Claude Haiku 5.5; not Claude Sonnet 5. Bedrock's InvokeModel API takes them on fewer models: no ARN-versioned models and no older Mythos models; its Converse API takes none |
|
||||
| Mid-conversation tool changes | beta | beta | beta | beta | beta | Same models as mid-conversation system messages. By reference: beta `mid-conversation-tool-changes-2026-07-01`. By value or by reference, on the Claude API, Claude Platform on AWS, Claude Models on Google Cloud (Anthropic managed) and Microsoft Foundry: beta `inline-tools-2026-09-15`. Bedrock: not through the InvokeModel API, per the docs |
|
||||
| Turn-scoped (`clear_at`) system messages | beta | beta | beta | beta | beta | 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 | beta | beta | beta | beta | Claude Fable 5.2, Claude Mythos 5.2, Claude Fable 5.1, Claude Mythos 5.1, Claude Opus 5, Claude Opus 5.5, Claude Sonnet 5.5 and Claude Haiku 5.5 (thinking on only - a 400 with `between_tools` on the first, `disabled` on the second); beta `mid-conversation-output-config-2026-07-01`; on the Claude API and Google Cloud (Claude Fable 5.2 and Claude Mythos 5.2 where offered), open to any organization that sends the header. Claude Platform on AWS: not the Mythos models. Claude in Amazon Bedrock: Claude Fable 5.1, Claude Mythos 5.1 and Claude Opus 5.5; through the Bedrock InvokeModel API, Claude Fable 5.2, Claude Mythos 5.2, Claude Fable 5.1 and Claude Opus 5.5, with the value in the request body's `anthropic_beta` array. Foundry: all the models above, with the Fable and Mythos models on Hosted on Anthropic deployments only |
|
||||
| `thinking.display: "updates"` | beta | beta | beta | beta | beta | Claude Fable 5.2, Claude Mythos 5.2, Claude Fable 5.1, Claude Mythos 5.1, Claude Fable 5, Claude Opus 5.5, Claude Sonnet 5.5 (with adaptive thinking); 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 | beta | beta | unconfirmed | `thinking.block_binding` + `input_transformations`; beta `thinking-binding-controls-2026-08-01` (the same beta name on the Claude API, Claude Platform on AWS, Bedrock, and Vertex - Bedrock: the `anthropic-beta` header on Claude in Amazon Bedrock, the `anthropic_beta` body field on InvokeModel; Vertex: the `anthropic-beta` HTTP header); Foundry unconfirmed; wherever the header is rejected, use strip-and-retry; the history-editing enforcement itself follows the rule in `shared/model-migration.md` -> Migrating to Claude Fable 5.1 from Claude Fable 5 (on Claude Fable 5.2 and Claude Mythos 5.2 it is enforced for every account) |
|
||||
| Server-side `fallbacks` | beta | beta | No | No | No | `"default"` -> beta `server-side-fallback-2026-07-01`; array form -> either that or beta `server-side-fallback-2026-06-01` |
|
||||
| Server-side `fallbacks` | beta | unconfirmed | No | No | No | `"default"` -> beta `server-side-fallback-2026-07-01`; array form -> either that or beta `server-side-fallback-2026-06-01`. The docs page doesn't name Claude Platform on AWS, so use the SDK middleware there (`shared/model-migration.md`) |
|
||||
| Fast mode | Yes | No | No | unconfirmed | Yes | Claude Opus 5.5: $8 / $40, no beta flag; Foundry: hosted on Azure only, as a separate `claude-opus-5-5-fast` deployment. Claude Opus 5: research preview on the first-party API, beta `fast-mode-2026-02-01` in Messages API requests, $10 / $50. Claude Fable 5.2 and Claude Mythos 5.2: SKILL.md -> Fast Mode. On Vertex and Foundry they are available only if the Fast Mode page in `shared/live-sources.md` names them, which is why the Vertex cell says unconfirmed. On Vertex, read that page before adding or removing `speed`. Fast mode on the Opus models isn't available on Vertex |
|
||||
| Cache diagnostics | beta | No | No | No | No | First-party API only |
|
||||
| Cache diagnostics | Yes | unconfirmed | No | No | unconfirmed | Opt in with the `diagnostics` object; no beta header needed. The docs page doesn't list Claude Platform on AWS or Foundry, so test there before relying on it |
|
||||
| Task budgets | beta | beta | No | beta | beta | Beta header `task-budgets-2026-03-13` |
|
||||
|
||||
## Claude Models on Google Cloud (Anthropic managed)
|
||||
@@ -69,8 +69,6 @@ Before relying on a feature marked unconfirmed, check its page in `shared/live-s
|
||||
|---|---|
|
||||
| OpenTelemetry tracing - API spans (destinations) | No |
|
||||
| Fast mode | Yes on Claude Opus 5.5: set `speed: "fast"` on a plain Messages request, without the `fast-mode-2026-02-01` beta flag. In Managed Agents here, only Claude Opus 5.5 has it. Claude Opus 5 has it only on the Claude API (Messages and Managed Agents), not here. Claude Fable 5.2 and Claude Mythos 5.2: read the Fast Mode page in `shared/live-sources.md` before adding or removing `speed`. Other models are unconfirmed; Claude Opus 4.6 with `speed: "fast"` returns a 400 here |
|
||||
| Cache diagnostics | unconfirmed |
|
||||
| Task budgets | unconfirmed: the docs don't name this platform |
|
||||
| Thinking block-binding controls | unconfirmed |
|
||||
| Per-message `effort` (system message `output_config`) | beta on Claude Fable 5.2, Claude Mythos 5.2, Claude Fable 5.1, Claude Mythos 5.1, Claude Opus 5.5, Claude Opus 5, Claude Sonnet 5.5 and Claude Haiku 5.5 |
|
||||
| Managed Agents webhooks | unconfirmed |
|
||||
@@ -80,5 +78,5 @@ Before relying on a feature marked unconfirmed, check its page in `shared/live-s
|
||||
| Server-side `fallbacks` | beta, including the `"default"` form on Claude Sonnet 5.5. If the API rejects the field, drop it and use the SDK's `BetaRefusalFallbackMiddleware` (`shared/model-migration.md`) |
|
||||
| Fine-grained tool streaming | Yes - if `eager_input_streaming` returns a 400, leave it off |
|
||||
| `inference_geo` (data residency) | Yes - `"global"` by default; for US-only inference, set `"us"` on each request (1.1x price). The workspace's geo settings are read-only |
|
||||
| User profiles | Yes. `/v1/user_profiles` uses the base URL without the workspace. Older SDK releases sent these calls to the workspace URL (Ruby raised `NotImplementedError`): upgrade to the latest SDK |
|
||||
| User profiles | Yes for create, retrieve, list and update; the docs don't list delete on this platform. Use the latest SDK client, or call the organization-level base URL (see this platform's page in `shared/live-sources.md`). Older clients fail: Python before 2.3.0, TypeScript `@anthropic-ai/google-cloud-sdk` before 1.1.1, Java before 3.3.0, C# `Anthropic.GoogleCloud` before 1.0.1 and PHP before 1.3.0 send these calls to the workspace URL, Go before 2.3.0 has only `client.Beta.UserProfiles`, and Ruby before 2.3.0 raises `NotImplementedError` |
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
Preserved thinking is measured in units of **conversations that keep their reasoning, not requests that pass**. One edit to an earlier turn invalidates every thinking block after it, and the same stale block fails again on every later request that replays it - so a per-request count overstates the damage and a per-conversation count (did this conversation break, and at which turn) is the number that tells you whether a fix worked.
|
||||
|
||||
**What the check is, in one paragraph.** On models with preserved thinking (Claude Fable 5.2, Claude Mythos 5.2, Claude Fable 5.1, Claude Mythos 5.1, Claude Opus 5.5, Claude Sonnet 5.5, and Claude Haiku 5.5 today; the Preserved thinking page lists the models and the enforced accounts, and says to go append-only), each `thinking` block's `signature` records the conversation that produced it - the top-level `system` prompt, the set of `tools`, and every message before the block - and the model that produced it. When the transcript comes back, the API recomputes that record from what you sent and requires a match (a separate model check decides whether the current model can read the block at all; see "Switching models mid-conversation" in `shared/preserved-thinking-migration/causes.md`). Integrations that change nothing already sent, even indirectly, never notice. Integrations that rewrite earlier turns between requests - truncation, client-side compaction, a re-rendered system prompt, a tool list that grows when a plugin connects, a per-turn reminder injected and then stripped, old tool results trimmed later, media dropped by a size cap, a lossy round trip through the app's own message types - lose the reasoning after the edit point (`drop_block`) or fail the request (`error`). The check compares the conversation *as you sent it*, so the API's own threshold compaction and context editing never count as edits. The published explanation lives in `shared/model-migration.md` -> Migrating to Claude Fable 5.1 from Claude Fable 5 -> **Breaking change 3** (the three-step check and the append-only form of each edit; read it first if the check is new to you) - this workflow restates the rules only as a lookup, the cause table and keep list in `causes.md`; it finds which edits *this* harness makes, proves them with the API's own response, fixes them one at a time, and proves the fix the same way.
|
||||
**What the check is, in one paragraph.** On models with preserved thinking (Claude Fable 5.2, Claude Mythos 5.2, Claude Fable 5.1, Claude Mythos 5.1, Claude Opus 5.5, Claude Sonnet 5.5, and Claude Haiku 5.5 today; the Prefix checks page lists the models and says to go append-only), each `thinking` block's `signature` records the conversation that produced it - the top-level `system` prompt, the set of `tools`, and every message before the block - and the model that produced it. When the transcript comes back, the API recomputes that record from what you sent and requires a match (a separate model check decides whether the current model can read the block at all; see "Switching models mid-conversation" in `shared/preserved-thinking-migration/causes.md`). Integrations that change nothing already sent, even indirectly, never notice. Integrations that rewrite earlier turns between requests - truncation, client-side compaction, a re-rendered system prompt, a tool list that grows when a plugin connects, a per-turn reminder injected and then stripped, old tool results trimmed later, media dropped by a size cap, a lossy round trip through the app's own message types - lose the reasoning after the edit point (`drop_block`) or fail the request (`error`). The check compares the conversation *as you sent it*, so the API's own threshold compaction and context editing never count as edits. The published explanation lives in `shared/model-migration.md` -> Migrating to Claude Fable 5.1 from Claude Fable 5 -> **Breaking change 3** (the three-step check and the append-only form of each edit; read it first if the check is new to you) - this workflow restates the rules only as a lookup, the cause table and keep list in `causes.md`; it finds which edits *this* harness makes, proves them with the API's own response, fixes them one at a time, and proves the fix the same way.
|
||||
|
||||
**Where this workflow sits**: the `migrate` subcommand explains the check and lists the append-only form of each edit; this workflow is its executable form - scan, measure, fix, re-measure - for a harness that already exists. `cost-optimize` is a sibling, not a prerequisite: most edits that invalidate thinking also restart the prompt cache, so a fix here usually shows up in its cache-hit numbers too, and a prefix edit found there ("audit for mid-task cache-breakers") is the same finding as a break found here. The two disciplines are very nearly the same, so a harness already append-only for caching pays nothing extra here. Once the project has an eval, Step 3 runs as a hill-climb whose metric is the drop count - one change per round, measured, kept or reverted - and the `hillclimb` subcommand is the loop to use.
|
||||
|
||||
@@ -33,13 +33,13 @@ A tier is a property of the cause, not of one conversation: rank by tier first,
|
||||
|
||||
**Does your harness change earlier turns, the system prompt, or the tool list, even indirectly (a URL's bytes, an unpinned MCP tool list, a proxy)? If not, stop** - there is nothing to migrate; say so plainly.
|
||||
|
||||
When a replayed thinking block no longer matches on an enforced account, the default is a **400 error**. Dropping the thinking instead is opt-in, and it is not a fix: it trades a visible failure for the silent loss of that reasoning, and it has a cost - dropped blocks aren't billed, but Claude re-creates the reasoning it can no longer read, which can increase output tokens; the Claude Fable 5.2 migration guide calls it a stopgap ("Failure modes to avoid" in `causes.md`).
|
||||
When a replayed thinking block no longer matches and the API enforces the check, the default is a **400 error**. Dropping the thinking instead is opt-in, and it is not a fix: it trades a visible failure for the silent loss of that reasoning, and it has a cost - dropped blocks aren't billed, but Claude re-creates the reasoning it can no longer read, which can increase output tokens; the Claude Fable 5.2 migration guide calls it a stopgap ("Failure modes to avoid" in `causes.md`).
|
||||
|
||||
**First, establish three things - from the request and the repository where they answer it, and from the user where they don't.** This workflow is interactive by design: a capture of real request bodies, a test slice, and every live replay need the user's involvement or approval, and "which of these edits is deliberate" is a question only they can answer. State all three at the top of the report (the baseline may read "pending Step 2" at first).
|
||||
|
||||
1. **Scope.** If Claude Code, claude.ai or Claude Managed Agents manages the conversation history, or the Claude Agent SDK does and the system prompt given to it stays the same, there is nothing to migrate - say so and stop. Otherwise: if the request names files or directories, that is the scope. Otherwise it is every place the project builds the three parts of a request the check compares - the `system` prompt, the `tools` array, and the `messages` array - across every path that touches them between two requests of one conversation: the request builder, compaction or truncation, reminder or context injection, media handling, persistence and resume (anything that re-reads the conversation from a store and re-renders it), process restart and deploy, plugin or MCP connection, sub-agent transcripts, and model switching. Note distinct traffic classes (an interactive chat path and a background agent loop are different harnesses even on one key): the profile, the fixes, and every validation later run per class. A capture taken on an older model may carry request shapes Claude Fable 5.2 rejects before any check runs - `thinking.type` `enabled` or `disabled`, a forced `tool_choice` (`any` or `tool`), an assistant prefill as the last message, non-default `temperature`, `top_p` or `top_k` - so list them now as things to convert before measuring (Step 2.1 lists what the probe converts; it leaves a prefill alone, and that 400 shows in its "not evaluated" line). A `computer_20251124` tool (off Amazon Bedrock), or an advisor other than `claude-fable-5-2` / `claude-mythos-5-2`, is a 400 there too; a capture can't convert it, so measure that traffic on its current model if it runs the check. **Also establish which platform** the code targets (Claude API, Claude Platform on AWS, Amazon Bedrock, Google Cloud Vertex AI, or Microsoft Foundry) and **which model** it runs: the check applies only to models with preserved thinking. Platforms that offer these betas use the same names but take them differently ("A beta name that never arrives" in `causes.md`); read `shared/platform-availability.md` and the platform's own documentation rather than assuming. Finally establish **whether the organization is enforced today**. The rule: **on Claude Fable 5.2 and Claude Mythos 5.2 the check is enforced for every account** (no record-only mode there); on Claude Fable 5.1, Claude Opus 5.5, Claude Sonnet 5.5 and Claude Haiku 5.5 the check is enforced by default for accounts created on or after August 31, 2026, 00:00 UTC, with the same definition on the Claude API and on the cloud platforms; on Claude Mythos 5.1 it is enforced by default whatever the account's age (platforms: `shared/model-migration.md` -> Who is enforced); a request that sets `prefix_mismatch_behavior` opts in regardless of account age; and the Preserved thinking page says to go append-only, so the same code works on every account. Confirm it from the responses production already gets: an enforced account sees `input_transformations` entries (with the header) or 400s whose text says "bound to a different conversation"; an account that is not enforced yet sees no dropped blocks and no 400s until a request sets the field; with the beta header alone, its responses list each block that would fail as a `thinking_mismatch_allowed` entry (Step 2.2). The probe: send the model the code targets an edited history of its own, with a thinking block after the edit and no beta header: a 400 that names the header means the account is enforced by default on that model, a 200 means it is not (the Message Batches API returns 200 either way). To confirm a 200, resend with the beta header and still no field: the response lists every thinking block after the edit as `thinking_mismatch_allowed` (if it lists none, that proves nothing: see Step 0.5). Step 0.5 proves the enforced path - run it with a test key, never against production traffic.
|
||||
1. **Scope.** If Claude Code, claude.ai or Claude Managed Agents manages the conversation history, or the Claude Agent SDK does and the system prompt given to it stays the same, there is nothing to migrate - say so and stop. Otherwise: if the request names files or directories, that is the scope. Otherwise it is every place the project builds the three parts of a request the check compares - the `system` prompt, the `tools` array, and the `messages` array - across every path that touches them between two requests of one conversation: the request builder, compaction or truncation, reminder or context injection, media handling, persistence and resume (anything that re-reads the conversation from a store and re-renders it), process restart and deploy, plugin or MCP connection, sub-agent transcripts, and model switching. Note distinct traffic classes (an interactive chat path and a background agent loop are different harnesses even on one key): the profile, the fixes, and every validation later run per class. A capture taken on an older model may carry request shapes Claude Fable 5.2 rejects before any check runs - `thinking.type` `enabled` or `disabled`, a forced `tool_choice` (`any` or `tool`), an assistant prefill as the last message, non-default `temperature`, `top_p` or `top_k` - so list them now as things to convert before measuring (Step 2.1 lists what the probe converts; it leaves a prefill alone, and that 400 shows in its "not evaluated" line). A `computer_20251124` tool (off Amazon Bedrock), or an advisor other than `claude-fable-5-2` / `claude-mythos-5-2`, is a 400 there too; a capture can't convert it, so measure that traffic on its current model if it runs the check. **Also establish which platform** the code targets (Claude API, Claude Platform on AWS, Amazon Bedrock, Google Cloud Vertex AI, or Microsoft Foundry) and **which model** it runs: the check applies only to models with preserved thinking. Platforms that offer these betas use the same names but take them differently ("A beta name that never arrives" in `causes.md`); read `shared/platform-availability.md` and the platform's own documentation rather than assuming. Finally establish **whether production requests get the 400 today**. The rule: **on Claude Fable 5.2 and Claude Mythos 5.2 the check is enforced for every account** (no record-only mode there); on Claude Fable 5.1, Claude Opus 5.5, Claude Sonnet 5.5 and Claude Haiku 5.5, with the field unset, a request that fails the check might or might not get a 400 (on Bedrock and Vertex, the 400 applies to accounts and projects that first used Claude there on or after August 31, 2026; earlier ones might or might not get it), and one result promises nothing about later requests; on Claude Mythos 5.1 it is enforced by default (platforms: `shared/model-migration.md` -> Who is enforced); a request that sets `prefix_mismatch_behavior` opts in; and the docs say to go append-only or set the field, and otherwise to handle both cases. Confirm it from the responses production already gets: 400s from this check on some requests, or, with the beta header alone, a `thinking_mismatch_allowed` entry for each block that failed on a request that got no error (Step 2.2). The probe: send the model the code targets an edited history of its own, with a thinking block after the edit, the beta header and no field: a 400 that the same request with the unedited history doesn't get means it got the error, and `thinking_mismatch_allowed` entries mean it got none; an empty array proves nothing (see Step 0.5). The Message Batches API returns 200 either way. Step 0.5 proves the enforced path - run it with a test key, never against production traffic.
|
||||
2. **Quality bar.** Find the project's eval, test suite, or outcome checks for its model calls. The fixes in this workflow are behavior-preserving by construction (they change *how* the history is carried, not what the model is told), but two of them are not: replacing a compaction scheme, and choosing to drop thinking at a boundary. Those need the eval. If none exists, say so prominently in the report and do not stop: the drop count itself is a measurement, every fix that removes an edit is safe to propose, and the minimal eval recipe in Step 3 is the next step for the two that aren't.
|
||||
3. **Baseline.** Two numbers, both from Step 2's probe on the same test slice: the share of conversations with at least one prefix break, and the turn at which each one first breaks. Record them before any fix. The three-arm protocol in Step 2 also asks for the eval score with the current harness and preserved thinking off (that is the eval's existing number) - write it down now if it exists.
|
||||
3. **Baseline.** Two numbers, both from Step 2's probe on the same test slice: the share of conversations with at least one prefix break, and the turn at which each one first breaks. Record them before any fix. The three-arm protocol in Step 2 also asks for the eval score with the current harness (the eval's existing number, a clean baseline only if those runs got no 400s from this check) - write it down now if it exists.
|
||||
|
||||
## Step 0.5: Prove the mechanism is wired
|
||||
|
||||
@@ -117,7 +117,7 @@ The API's response is the only ground truth. The client-side diff can miss what
|
||||
|
||||
### 2.1 The request shape
|
||||
|
||||
Every request in the test slice carries the beta header and sets the behavior **explicitly** - this is what turns enforcement on for an organization that is not enforced by default, and it is what adds the report to the response:
|
||||
Every request in the test slice carries the beta header and sets the behavior **explicitly** - this is what turns enforcement on for every request, and it is what adds the report to the response:
|
||||
|
||||
```http
|
||||
POST /v1/messages
|
||||
@@ -131,7 +131,7 @@ anthropic-beta: thinking-binding-controls-2026-08-01
|
||||
|
||||
Rules that save a debugging hour:
|
||||
|
||||
- The field without the header is, today, a 400 ending in `block_binding: Extra inputs are not permitted`. That is a different 400 from the one an enforced account gets when it replays an edited history without the header, whose text says the block is "bound to a different conversation" and ends by naming the beta value the setting requires; you will meet both, and only the second one means the check ran. The header without the field does **not** turn enforcement on for an organization that is not enforced yet: no block is dropped and nothing fails. The API records the check instead and lists each block that would have failed as a `thinking_mismatch_allowed` entry (2.2) - the zero-risk way to find edits in production traffic. To measure what enforcement costs, set the field; it is the per-request opt-in.
|
||||
- The field without the header is, today, a 400 ending in `block_binding: Extra inputs are not permitted`. That 400 doesn't mean the check ran. The header without the field does **not** turn enforcement on or change what the model receives: on a request that gets no error, the API records the check and lists each block that failed as a `thinking_mismatch_allowed` entry (2.2) - the zero-risk way to find edits in production traffic. To measure what enforcement costs, set the field; it is the per-request opt-in.
|
||||
- `prefix_mismatch_behavior` takes `"error"` or `"drop_block"`. Write exactly that field name; the probe removes any other key it finds under `block_binding` and says which.
|
||||
- The object is accepted, under the header, wherever the request's `thinking` type allows it, so it can stay across a switch when every model in the route accepts it with the type sent (on a model that runs the check, `adaptive`: `enabled` is a 400 on Claude Fable 5.2, and Claude Sonnet 5.5's `"between_tools"` rejects `block_binding`, so the probe replays it as `adaptive`); on a model without preserved thinking it is a no-op that still reports model-check drops.
|
||||
- Keep everything else in the request exactly as production sends it. The probe touches only fields outside the compared prefix and prints each change: the header, this field, `max_tokens` (capped, see 2.3), `stream` (off unless asked), `tool_choice` (set to `none`, see 2.3), and the thinking configuration - a request with no `thinking` configuration is given `{"type": "adaptive"}` (on Claude Fable 5.2 that is what a request without the key already runs with), `enabled`, `between_tools` or `disabled` is rewritten to `adaptive`, `temperature` becomes 1 and `top_p` / `top_k` are removed; none of those changes the verdict. `system`, `tools` and `messages` go out exactly as captured.
|
||||
@@ -142,7 +142,7 @@ Rules that save a debugging hour:
|
||||
|
||||
Three surfaces, in order of reliability:
|
||||
|
||||
1. **`input_transformations`** (response body, top-level, sibling of `usage`) - the contract. With the header it is present on every response from a thinking-capable model: `[]` when nothing was dropped and nothing failed, otherwise one entry per block, of two types. `{"type": "thinking_dropped", "path": "messages.7.content.0", "reason": "prefix_binding_mismatch"}`: the block was removed. `thinking_mismatch_allowed` (same `path`, `reason` always `prefix_binding_mismatch`): the block failed the prefix check on a request the API does not enforce (for example, an older account on Claude Fable 5.1 with the field unset), so it reached the model unchanged and was billed; every block after the edit gets one, and a request that sets the field never does (the probe always sets the field, so it reads such an entry as the field stripped en route: turn not evaluated, run inconclusive). `path` indexes the `messages` array as you sent it. `reason` is `prefix_binding_mismatch` (your history changed - this workflow's subject) or `model_binding_mismatch` (the conversation switched to a model that cannot read the block - not a bug in your code; see "Switching models mid-conversation" in `shared/preserved-thinking-migration/causes.md`) or `organization_binding_mismatch` (a Claude Fable 5.2, Claude Mythos 5.2, Claude Sonnet 5.5 or Claude Haiku 5.5 block sent by another account - same section); the probe flags any other reason as `WARN`. Dropped blocks are not billed, whichever the reason. Ignore entries whose `type` or `reason` you don't recognize; later checks add values. When streaming, the array arrives on the `message` object in `message_start` (and again in the final `message_delta` only after a mid-stream server-side model fallback). Without the header the field is absent and drops are silent.
|
||||
1. **`input_transformations`** (response body, top-level, sibling of `usage`) - the contract. With the header it is present on every response from a thinking-capable model: `[]` when nothing was dropped and nothing failed, otherwise one entry per block, of two types. `{"type": "thinking_dropped", "path": "messages.7.content.0", "reason": "prefix_binding_mismatch"}`: the block was removed. `thinking_mismatch_allowed` (same `path`, `reason` always `prefix_binding_mismatch`): the block failed the prefix check on a request that got no error (possible on Claude Fable 5.1, for example, with the field unset), so it reached the model unchanged and was billed; every block after the edit gets one, and a request that sets the field never does (the probe always sets the field, so it reads such an entry as the field stripped en route: turn not evaluated, run inconclusive). `path` indexes the `messages` array as you sent it. `reason` is `prefix_binding_mismatch` (your history changed - this workflow's subject) or `model_binding_mismatch` (the conversation switched to a model that cannot read the block - not a bug in your code; see "Switching models mid-conversation" in `shared/preserved-thinking-migration/causes.md`) or `organization_binding_mismatch` (a Claude Fable 5.2, Claude Mythos 5.2, Claude Sonnet 5.5 or Claude Haiku 5.5 block sent by another account - same section); the probe flags any other reason as `WARN`. Dropped blocks are not billed, whichever the reason. Ignore entries whose `type` or `reason` you don't recognize; later checks add values. When streaming, the array arrives on the `message` object in `message_start` (and again in the final `message_delta` only after a mid-stream server-side model fallback). Without the header the field is absent and drops are silent.
|
||||
2. **A diagnosis header, if present.** Some responses that report a drop (or a 400 in `error` mode) also carry a response header named `anthropic-thinking-prefix-mismatch` - **which can be missed on streamed responses** (the probe's `--stream` mode may then print no "why:" line), so read it as a second check and detect from the request diff. **Anthropic has not published this header; it may change or stop without notice. Use it if present; never depend on it.** If it is there, its `pattern` and `changed_validated` fields are hints - the shape of the edit, in the same words `prefix_diff.py` uses, and the first changed path in the request - and the probe prints them on its "why:" line. Treat its absence as "no diagnosis", not "no break": the detail (kind, pattern, changed path) is only given for blocks your own organization created - for other blocks the header carries only the bare fact - and a partner cloud's proxy is not guaranteed to forward it.
|
||||
3. **The 400 text in `error` mode** - the same diagnosis as one sentence, for code that never sees headers: `messages.7.content.0: 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". Content that preceded this block when it was created is missing from this request, starting at `messages.2`.` It usually ends with one sentence naming the first changed path, as in that example (the sentence varies with the kind of edit and is sometimes absent). The request is rejected before any output; retrying the same body fails the same way (production handling: "Failure modes to avoid" in `causes.md`).
|
||||
|
||||
@@ -171,15 +171,15 @@ Replaying a request does not run the application's own tools - the capture alrea
|
||||
|
||||
### 2.4 The three-arm protocol (validation against the eval)
|
||||
|
||||
When the project has an eval, treat the migration as an A/B/C experiment on one frozen set of inputs. Arm 1 is the harness as it is today, check not enforced: the eval's existing score, no new run. Arm 2 is the same harness with `drop_block` set in the eval runner's configuration (never in production code), with `input_transformations` recorded per response and joined to each conversation's score and token usage; the join answers whether the conversations that lost reasoning scored worse or used more tokens, and by how much. Arm 3 is the harness after Step 3's fixes, again with `drop_block` set; the target is no `prefix_binding_mismatch` entries on the slice (model-check entries are counted separately: "Switching models mid-conversation" in `causes.md`) and a score within noise of Arm 1. Report the three scores, the token usage and the two drop counts side by side, per traffic class.
|
||||
When the project has an eval, treat the migration as an A/B/C experiment on one frozen set of inputs. Arm 1 is the harness as it is today: the eval's existing score, no new run (a clean baseline only if those runs got no 400s from this check). Arm 2 is the same harness with `drop_block` set in the eval runner's configuration (never in production code), with `input_transformations` recorded per response and joined to each conversation's score and token usage; the join answers whether the conversations that lost reasoning scored worse or used more tokens, and by how much. Arm 3 is the harness after Step 3's fixes, again with `drop_block` set; the target is no `prefix_binding_mismatch` entries on the slice (model-check entries are counted separately: "Switching models mid-conversation" in `causes.md`) and a score within noise of Arm 1. Report the three scores, the token usage and the two drop counts side by side, per traffic class.
|
||||
|
||||
### 2.5 Caveats that change what the measurement means
|
||||
|
||||
- **Keep-tail and background compaction have no append-only client-side form without the `compact-2026-09-04` beta.** Summarizing older turns and keeping the newest ones verbatim fails on the kept turns (their thinking was produced with the full history present); compacting off the critical path and swapping the summary in later fails the same way for every turn produced above the swap point. The choices are: server-side compaction or context editing where the product can use them; simple compaction (summary plus the new turn, nothing older replayed); keep the scheme and strip thinking from the retained turns as a deterministic, recorded strip; or keep the scheme and send `drop_block` (equivalent in effect: both lose the same reasoning; the strip is explicit, `drop_block` is one field). Measure the scheme you keep - Arm 2 tells you what it costs - record the decision, and do not assume a compaction rewrite is required. With the beta (on-demand compaction; Step 3), its append-only form is one more scheme to measure the same way, with Arm 2 as its before number.
|
||||
- **Same-name tool definition changes and tools that re-list.** Under `mid-conversation-tool-changes-2026-07-01`, `tool_addition` is by reference, so it cannot express "the same tool, now with a different description", and a connector whose tool list changes on reconnect has no natural append-only form. Strictly, one exists - declare the revised tool under a new name with `defer_loading: true`, announce it with `tool_addition`, and withdraw the old name with `tool_removal` - but where `inline-tools-2026-09-15` is not available the simpler answer, and the recommendation, is to freeze each tool's text for the life of the conversation and replay it: stale but valid. Where that beta is available, send the changed definition by value instead (Step 3).
|
||||
- **Partner clouds run the check too** (Amazon Bedrock and Google Cloud Vertex AI). The Beta headers page states that platforms that offer these betas use the same names; each beta's own page lists its platforms, and for any other platform, read that platform's own documentation and `shared/platform-availability.md` before assuming the controls are offered. On every platform the response is the only place the result is visible, and whether the diagnosis header is forwarded on a 200 is up to the platform. Where the controls are not offered the opt-in test does not apply, and recovery from a 400 is the same as Step 3's last resort: strip thinking from the rejected block onward, recorded and persisted.
|
||||
- **The Message Batches API** drops failing blocks under its unset default instead of failing the item, and sends no header; set `"error"` explicitly if batch items should fail. Whether batch results carry `input_transformations` is unverified - test one batch before relying on it.
|
||||
- **Organizations that are not enforced yet** get no dropped blocks and no 400 until a request sets the field (on Claude Fable 5.2, Claude Mythos 5.2 and, on the Claude API, Vertex and Foundry, Claude Mythos 5.1, where the check is enforced by default, the header alone still gets the 400). With the header alone they get `thinking_mismatch_allowed` entries instead, so sending the header in production and logging those entries finds the edits without changing what the model receives - a record-only pass worth running before Step 2's replay; its entries are a lower bound on what `drop_block` would remove. The field opts a replayed request in, one request at a time, with the rest of production untouched. The same fact is the production hazard: copying the field into production code lifts the exemption on every request that carries it, and every conversation that breaks today starts losing its reasoning (or failing) at once - do not do that before Step 3's fixes have landed.
|
||||
- **The Message Batches API** never fails an item on this check while the field is unset: it drops the failing blocks or, on some models, can let them through, and sends no header; set `"error"` explicitly if batch items should fail. Whether batch results carry `input_transformations` is unverified - test one batch before relying on it.
|
||||
- **A request with the field unset can get no error**: no dropped blocks and no 400 (on Claude Fable 5.2, Claude Mythos 5.2 and, on the Claude API, Vertex and Foundry, Claude Mythos 5.1, where the check is enforced by default, the header alone still gets the 400). With the header alone such requests get `thinking_mismatch_allowed` entries instead, so sending the header in production and logging those entries finds the edits without changing what the model receives - a record-only pass worth running before Step 2's replay; its entries are a lower bound on what `drop_block` would remove. The field opts a replayed request in, one request at a time, with the rest of production untouched. The same fact is the production hazard: copying the field into production code opts every request that carries it into enforcement, and every conversation that breaks today starts losing its reasoning (or failing) at once - do not do that before Step 3's fixes have landed.
|
||||
- **Two checks share the response.** A conversation that moves to a model that cannot read the block gets `model_binding_mismatch` entries; those are expected, unbilled, not a 400 in any test to date, and not a harness bug - but they are reasoning lost, so the probe counts them apart from prefix breaks and the report states them (see "Switching models mid-conversation" in `shared/preserved-thinking-migration/causes.md`). Only `prefix_binding_mismatch` is this workflow's metric.
|
||||
|
||||
## Step 3: Fix one cause per diff, re-measure, keep or revert
|
||||
@@ -216,7 +216,7 @@ Accidental edits are removed. The recipes below are the append-only forms for th
|
||||
|
||||
**Minimal eval recipe**, for the two behavior-affecting fixes when no eval exists: a frozen set of 20-30 real conversations from the capture; a per-conversation judgment that is cheapest for the workload (golden outputs to diff against, a short rubric, or an automated checker); a runner that replays one configuration and reports pass rate beside the probe's break share. Three arms, approved as one budget.
|
||||
|
||||
Finally, **the production setting is its own diff, and the last one**. Under the header, choose `"error"` or, as a stopgap, `"drop_block"`, and set it explicitly; do not leave the field unset, because the defaults differ by surface and by account age, and an unset field on an account that is not yet enforced means the check is recorded, not applied. Apply that diff only with the user's explicit approval, only after the slice shows zero new drops for every cause that was fixed, and never `"error"` in production while a measured-but-unfixed cause remains - `"error"` belongs in CI, where one multi-turn capture per traffic class replays with it so that a new prefix edit fails the build. In production, alert on the first `prefix_binding_mismatch` entry per conversation, not on the count.
|
||||
Finally, **the production setting is its own diff, and the last one**. Under the header, choose `"error"` or, as a stopgap, `"drop_block"`, and set it explicitly; do not leave the field unset, because the defaults differ by model and by surface, and an unset field can mean the check is recorded, not applied. Apply that diff only with the user's explicit approval, only after the slice shows zero new drops for every cause that was fixed, and never `"error"` in production while a measured-but-unfixed cause remains - `"error"` belongs in CI, where one multi-turn capture per traffic class replays with it so that a new prefix edit fails the build. In production, alert on the first `prefix_binding_mismatch` entry per conversation, not on the count.
|
||||
|
||||
Before the report, check the run against "Failure modes to avoid" in `shared/preserved-thinking-migration/causes.md`.
|
||||
|
||||
|
||||
@@ -13,10 +13,10 @@ A harness that routes one conversation to more than one model - a cheaper model
|
||||
- **Upgrade (an older model's blocks replayed to Claude Fable 5.1): nothing to do.** Claude Fable 5.1 reads thinking produced by Claude Opus 5 and Claude Fable 5, among other earlier models (the Preserved thinking page's "Which model switches keep the reasoning on the Claude API" section has the full list). The blocks are kept, fed to the model, counted in input tokens, and `input_transformations` is `[]`. An older model's block carries no conversation record for Claude Fable 5.1 to compare, so an edit made before such a block does not invalidate it; a conversation migrated from Claude Opus 5 can only break on the turns Claude Fable 5.1 produces from then on.
|
||||
- **Downgrade (Claude Fable 5.1's blocks replayed to Claude Opus 5 or Claude Fable 5): the reasoning is lost for that request, not the request.** The older model cannot read them, so the API leaves them out of that call, reports each one as `{"type": "thinking_dropped", "reason": "model_binding_mismatch", "path": ...}` when the beta header is on, and does not bill the dropped tokens. As of 2026-09-03 this is not a 400 in either mode, and there is no diagnosis header (that header belongs to the prefix check). Your `messages` array is never edited: the blocks stay in your history.
|
||||
- **Round trip (Claude Fable 5.1, then an older model, then Claude Fable 5.1 again): nothing is lost, provided the client keeps the history intact.** Back on Claude Fable 5.1 every block is read again - the ones from before the switch, the older model's own thinking block, and the ones minted after the return. Observed through four turns: a Claude Fable 5.1 block minted after the older model's turn is valid, and the chain of Claude Fable 5.1 blocks does not care that a turn between them came from another model. The same four-turn history sent back to the older model drops exactly the Claude Fable 5.1 blocks and keeps its own.
|
||||
- **Claude Opus 5.5 runs the same prefix check, and sits beside Claude Fable 5.1, not under it.** Everything in this file that names Claude Fable 5.1 as the model that runs the prefix check holds for Claude Opus 5.5 too (observed 2026-09-23: an edited history is a 400 in `"error"` mode, a `prefix_binding_mismatch` drop in `"drop_block"` mode, and a `thinking_mismatch_allowed` entry with the field unset). What differs is who reads whose blocks, per the Preserved thinking and Thinking pages: Claude Opus 5.5 reads thinking from Claude Opus 5, from earlier Opus, Sonnet and Haiku models, and, on the Claude API and Google Cloud Vertex AI, from Claude Sonnet 5.5 and Claude Haiku 5.5, but not from Claude Fable or Claude Mythos models; on the Claude API, Claude Fable 5.1 and Claude Mythos 5.1 read Claude Opus 5.5's blocks; Claude Fable 5.2 and Claude Mythos 5.2 read them too (platforms: `shared/model-migration.md` -> Migrating to Claude Fable 5.2 -> Breaking change 2), and no other model does. So Claude Opus 5 to Claude Opus 5.5, Claude Sonnet 5.5 or Claude Haiku 5.5 up to Claude Opus 5.5 on the Claude API and Google Cloud Vertex AI, and Claude Opus 5.5 up to Claude Fable 5.1 on the Claude API, keep the reasoning (`[]`), and per those pages so does a move up to Claude Fable 5.2 or Claude Mythos 5.2 on the platforms in `shared/model-migration.md` -> Migrating to Claude Fable 5.2 -> Breaking change 2; Claude Fable 5.1 to Claude Opus 5.5, or Claude Opus 5.5 to any other model, is a downgrade in the sense above - `model_binding_mismatch` drops, 200 in both modes.
|
||||
- **Claude Sonnet 5.5 runs the same prefix check too, and reads a different set of blocks.** Observed 2026-09-29: an edited history is a 400 in `"error"` mode, a `prefix_binding_mismatch` drop in `"drop_block"` mode, and a `thinking_mismatch_allowed` entry with the field unset. Per the Preserved thinking and Thinking pages, Claude Sonnet 5.5 reads thinking from Claude Sonnet 5, Claude Opus 4.8, Claude Haiku 4.5 and earlier models, and, on the Claude API and Google Cloud Vertex AI, from Claude Haiku 5.5, but not from Claude Opus 5, Claude Opus 5.5, or any Claude Fable or Claude Mythos model; on the Claude API and Google Cloud Vertex AI, Claude Opus 5.5 reads Claude Sonnet 5.5's blocks. Claude Fable 5.2 and Claude Mythos 5.2 read them too (platforms: `shared/model-migration.md` -> Migrating to Claude Fable 5.2 -> Breaking change 2), and no other model does. So Claude Sonnet 5 to Claude Sonnet 5.5, Claude Sonnet 5.5 up to Claude Opus 5.5 on those platforms, and Claude Sonnet 5.5 up to Claude Fable 5.2 or Claude Mythos 5.2 on the platforms named there, keep the reasoning; a move onto Claude Sonnet 5.5 from an Opus 5-series, Fable or Mythos model, or any other move away from Claude Sonnet 5.5 (a server-side fallback to Claude Sonnet 5, for example), is a downgrade in the sense above - `model_binding_mismatch` drops, 200 in both modes. Two things are specific to it. Its thinking type `"between_tools"` (it takes the place of `"disabled"`) does not accept `block_binding` - sending both is a 400 - so in that mode there is no `drop_block`: keep the history append-only, or strip the thinking blocks from the edited turn on; on an account that is not enforced by default, the beta header alone still lists blocks that would fail as `thinking_mismatch_allowed`. And its blocks stay with the account that produced them, or one linked to it: another account sending one gets the block dropped before the model sees it and the request succeeds, reported on the Claude API and Google Cloud Vertex AI, with the beta header, as `{"type": "thinking_dropped", "reason": "organization_binding_mismatch", "path": ...}` (silent without the header); blocks from earlier models are not affected. That is routing between accounts, not a history edit, and `prefix_mismatch_behavior` has no effect on it.
|
||||
- **Claude Opus 5.5 runs the same prefix check, and sits beside Claude Fable 5.1, not under it.** Everything in this file that names Claude Fable 5.1 as the model that runs the prefix check holds for Claude Opus 5.5 too (observed 2026-09-23: an edited history is a 400 in `"error"` mode, a `prefix_binding_mismatch` drop in `"drop_block"` mode, and a `thinking_mismatch_allowed` entry with the field unset, where a 400 is also possible). What differs is who reads whose blocks, per the Preserved thinking and Thinking pages: Claude Opus 5.5 reads thinking from Claude Opus 5, from earlier Opus, Sonnet and Haiku models, and, on the Claude API and Google Cloud Vertex AI, from Claude Sonnet 5.5 and Claude Haiku 5.5, but not from Claude Fable or Claude Mythos models; on the Claude API, Claude Fable 5.1 and Claude Mythos 5.1 read Claude Opus 5.5's blocks; Claude Fable 5.2 and Claude Mythos 5.2 read them too (platforms: `shared/model-migration.md` -> Migrating to Claude Fable 5.2 -> Breaking change 2), and no other model does. So Claude Opus 5 to Claude Opus 5.5, Claude Sonnet 5.5 or Claude Haiku 5.5 up to Claude Opus 5.5 on the Claude API and Google Cloud Vertex AI, and Claude Opus 5.5 up to Claude Fable 5.1 on the Claude API, keep the reasoning (`[]`), and per those pages so does a move up to Claude Fable 5.2 or Claude Mythos 5.2 on the platforms in `shared/model-migration.md` -> Migrating to Claude Fable 5.2 -> Breaking change 2; Claude Fable 5.1 to Claude Opus 5.5, or Claude Opus 5.5 to any other model, is a downgrade in the sense above - `model_binding_mismatch` drops, 200 in both modes.
|
||||
- **Claude Sonnet 5.5 runs the same prefix check too, and reads a different set of blocks.** Observed 2026-09-29: an edited history is a 400 in `"error"` mode, a `prefix_binding_mismatch` drop in `"drop_block"` mode, and a `thinking_mismatch_allowed` entry with the field unset, where a 400 is also possible. Per the Preserved thinking and Thinking pages, Claude Sonnet 5.5 reads thinking from Claude Sonnet 5, Claude Opus 4.8, Claude Haiku 4.5 and earlier models, and, on the Claude API and Google Cloud Vertex AI, from Claude Haiku 5.5, but not from Claude Opus 5, Claude Opus 5.5, or any Claude Fable or Claude Mythos model; on the Claude API and Google Cloud Vertex AI, Claude Opus 5.5 reads Claude Sonnet 5.5's blocks. Claude Fable 5.2 and Claude Mythos 5.2 read them too (platforms: `shared/model-migration.md` -> Migrating to Claude Fable 5.2 -> Breaking change 2), and no other model does. So Claude Sonnet 5 to Claude Sonnet 5.5, Claude Sonnet 5.5 up to Claude Opus 5.5 on those platforms, and Claude Sonnet 5.5 up to Claude Fable 5.2 or Claude Mythos 5.2 on the platforms named there, keep the reasoning; a move onto Claude Sonnet 5.5 from an Opus 5-series, Fable or Mythos model, or any other move away from Claude Sonnet 5.5 (a server-side fallback to Claude Sonnet 5, for example), is a downgrade in the sense above - `model_binding_mismatch` drops, 200 in both modes. Two things are specific to it. Its thinking type `"between_tools"` (it takes the place of `"disabled"`) does not accept `block_binding` - sending both is a 400 - so in that mode there is no `drop_block`: keep the history append-only, or strip the thinking blocks from the edited turn on; on a request that gets no error, the beta header alone still lists the blocks that failed as `thinking_mismatch_allowed`. And its blocks stay with the account that produced them, or one linked to it: another account sending one gets the block dropped before the model sees it and the request succeeds, reported on the Claude API and Google Cloud Vertex AI, with the beta header, as `{"type": "thinking_dropped", "reason": "organization_binding_mismatch", "path": ...}` (silent without the header); blocks from earlier models are not affected. That is routing between accounts, not a history edit, and `prefix_mismatch_behavior` has no effect on it.
|
||||
- **Claude Haiku 5.5 runs the same prefix check as well.** Per the Prefix checks page, with `prefix_mismatch_behavior` unset a failed check can be a 400 or no error at all, so handle both or set the field. Claude Haiku 4.5 doesn't run this check, so a harness that was fine there can fail here. Per the Preserved thinking and Thinking pages, Claude Haiku 5.5 reads thinking from Claude Sonnet 5, Claude Opus 4.8, Claude Haiku 4.5 and earlier models, but not from Claude Opus 5, Claude Opus 5.5, Claude Sonnet 5.5, or any Claude Fable or Claude Mythos model; on the Claude API and Google Cloud Vertex AI, Claude Opus 5.5 and Claude Sonnet 5.5 read Claude Haiku 5.5's blocks. Claude Fable 5.2 and Claude Mythos 5.2 read them too (platforms: `shared/model-migration.md` -> Migrating to Claude Fable 5.2 -> Breaking change 2), and no other model does. So Claude Haiku 4.5 to Claude Haiku 5.5, Claude Haiku 5.5 up to Claude Opus 5.5 or Claude Sonnet 5.5 on those platforms, and Claude Haiku 5.5 up to Claude Fable 5.2 or Claude Mythos 5.2 on the platforms named there, keep the reasoning; a move onto Claude Haiku 5.5 from an Opus 5-series model, Claude Sonnet 5.5, or a Fable or Mythos model, or any other move away from Claude Haiku 5.5, is a downgrade in the sense above - `model_binding_mismatch` drops, 200 in both modes. Two things carry over from Claude Sonnet 5.5. `block_binding` works only with `thinking: {"type": "adaptive"}`: with `{"type": "disabled"}` (which Claude Haiku 5.5 accepts at effort `high` or below) sending both is a 400, so in that mode there is no `drop_block` - keep the history append-only, or strip the thinking blocks from the edited turn on. And its blocks stay with the account that produced them, or one linked to it, dropped and reported the same way (`organization_binding_mismatch`).
|
||||
- **Claude Fable 5.2 and Claude Mythos 5.2 were released after all of these, and are checked on every account.** Per the Prefix checks and Preserved thinking pages: the prefix check is enforced for **every** account on both models (Claude Fable 5.1 follows the account-age rule), so an edited history is a 400 unless the request sets `"drop_block"`, and the record-only mode (`thinking_mismatch_allowed` with the field unset) is not available. On the platforms in `shared/model-migration.md` -> Migrating to Claude Fable 5.2 -> Breaking change 2 they read each other's blocks and those from Claude Opus 5.5, Claude Sonnet 5.5, Claude Haiku 5.5, Claude Fable 5.1, Claude Mythos 5.1, Claude Opus 5, Claude Fable 5, Claude Mythos 5 and earlier Opus, Sonnet and Haiku models; **no model released earlier reads theirs**. So every move onto Claude Fable 5.2 or Claude Mythos 5.2 there is an upgrade in the sense above, and every move away from them - to Claude Fable 5.1, to Claude Opus 5.5, to a refusal-fallback model - is a downgrade (`model_binding_mismatch` drops, 200 in both modes). Everything in this file that names Claude Fable 5.1 as the model that runs the prefix check holds for them, with two differences: every account is enforced, and there is no record-only mode. Their blocks also work only in the account that produced them, or one linked to it (`organization_binding_mismatch` on the Claude API and, where offered, Google Cloud Vertex AI).
|
||||
- **Claude Fable 5.2 and Claude Mythos 5.2 were released after all of these, and are checked on every account.** Per the Prefix checks and Preserved thinking pages: the prefix check is enforced for **every** account on both models (on Claude Fable 5.1 a 400 is possible but not certain), so an edited history is a 400 unless the request sets `"drop_block"`, and the record-only mode (`thinking_mismatch_allowed` with the field unset) is not available. On the platforms in `shared/model-migration.md` -> Migrating to Claude Fable 5.2 -> Breaking change 2 they read each other's blocks and those from Claude Opus 5.5, Claude Sonnet 5.5, Claude Haiku 5.5, Claude Fable 5.1, Claude Mythos 5.1, Claude Opus 5, Claude Fable 5, Claude Mythos 5 and earlier Opus, Sonnet and Haiku models; **no model released earlier reads theirs**. So every move onto Claude Fable 5.2 or Claude Mythos 5.2 there is an upgrade in the sense above, and every move away from them - to Claude Fable 5.1, to Claude Opus 5.5, to a refusal-fallback model - is a downgrade (`model_binding_mismatch` drops, 200 in both modes). Everything in this file that names Claude Fable 5.1 as the model that runs the prefix check holds for them, with one difference: with the field unset, a failed check is a 400 on every account, so there is no record-only mode. Their blocks also work only in the account that produced them, or one linked to it (`organization_binding_mismatch` on the Claude API and, where offered, Google Cloud Vertex AI).
|
||||
- **Another account's block can also be left out because of that account's standing.** Per the Preserved thinking page, the API can also leave out a thinking block that another account produced, if that account is no longer in good standing. This applies to requests to Claude Fable and Claude Mythos models, Claude Opus 5, Claude Opus 5.5, Claude Sonnet 5.5, and Claude Haiku 5.5. The request still succeeds, and the model answers without that block's reasoning. Like the account rule above, this is about where a block came from, not a history edit, so no fix in this workflow applies to it.
|
||||
- **A downgrade can hide an edit for one request.** The model check runs first, so a block the older model cannot read is never prefix-judged: a request that switches down *and* edits earlier content reports only `model_binding_mismatch`, even in `"error"` mode. The edit is still there; it surfaces on the next Claude Fable 5.1 turn as an ordinary prefix break (a 400 in `"error"` mode, `prefix_binding_mismatch` in `"drop_block"` mode). Scan and measure every turn of a mixed-model conversation, not only the turn where the switch happened.
|
||||
- **Turns from a non-Claude model** do not invalidate earlier thinking, provided they are appended after the existing history as ordinary assistant messages (`text` and `tool_use` content, no `thinking` blocks) and nothing earlier changes. Claude Fable 5.1 thinking minted after such a turn stays valid.
|
||||
@@ -61,7 +61,7 @@ With the MCP connector, a tool list that changes between requests is an edit for
|
||||
|
||||
## Append-only forms under newer betas
|
||||
|
||||
Two newer betas add an append-only form for shapes the table above marks as having none without them. On-demand compaction (`compact-2026-09-04`) has this form, where thinking in the kept turns stays valid, on the Claude API, Claude Platform on AWS, Google Cloud and Microsoft Foundry. The on-demand compaction page lists the beta for Amazon Bedrock, but the docs don't list this form there, so throughout this guide treat the beta as not available on Amazon Bedrock. The Availability section of `https://platform.claude.com/docs/en/build-with-claude/compaction-thinking-blocks` names the form's models and platforms. The Models API's `capabilities.compaction`, read with the beta header, reports on-demand compaction itself, not this form. Defining a tool inside a message (`inline-tools-2026-09-15`) is documented for the Claude API, Claude Platform on AWS and Claude Models on Google Cloud (Anthropic managed); by-reference tool changes under `mid-conversation-tool-changes-2026-07-01` are documented for those and for Claude in Amazon Bedrock (`bedrock-mantle`) and Google Cloud Vertex AI. Where a beta is not available, treat those shapes as the table says: measure and decide, freeze and replay.
|
||||
Two newer betas add an append-only form for shapes the table above marks as having none without them. On-demand compaction (`compact-2026-09-04`) has this form, where thinking in the kept turns stays valid, on the Claude API, Claude Platform on AWS, Google Cloud and Microsoft Foundry. The on-demand compaction page lists the beta for Amazon Bedrock, but the docs don't list this form there, so throughout this guide treat the beta as not available on Amazon Bedrock. The Availability section of `https://platform.claude.com/docs/en/build-with-claude/compaction-thinking-blocks` names the form's models and platforms. The Models API's `capabilities.compaction`, read with the beta header, reports on-demand compaction itself, not this form. Defining a tool inside a message (`inline-tools-2026-09-15`) is documented for the Claude API, Claude Platform on AWS, Claude Models on Google Cloud (Anthropic managed) and Microsoft Foundry; by-reference tool changes under `mid-conversation-tool-changes-2026-07-01` are documented for those and for Claude in Amazon Bedrock (`bedrock-mantle`) and Google Cloud Vertex AI. Where a beta is not available, treat those shapes as the table says: measure and decide, freeze and replay.
|
||||
|
||||
**Background and keep-tail compaction, the append-only way: on-demand compaction (beta `compact-2026-09-04`, `"compaction": {"type": "summarize"}`; the on-demand compaction page, `https://platform.claude.com/docs/en/build-with-claude/compaction-on-demand`).** Send a compaction request that carries exactly the `messages` of a request you already sent, on the conversation's model and under its `system`, `tools` and `thinking` settings, with the `compaction` field and a `max_tokens` large enough for a summary; send the beta header on it and on every request that carries the block. Exactly those messages, because the kept turns must directly follow the summarized messages and the first kept message must not be one the API would merge into the last summarized one (the same role, or a `role: "system"` message). A compaction request whose last assistant turn is still waiting on a tool result is rejected, so send the results first. Leave out `output_config.format`, `stop_sequences` and a `tool_choice` of type `any` or `tool` (the API rejects a compaction request that carries them), and never send `output_config.task_budget.remaining` on the compaction request or on any request that carries the block (a 400). The response holds one signed `compaction` block and nothing else (`stop_reason: "compaction"`). When no summary could be written there is no block: the response is still a 200 with empty `content`, and `stop_reason` is the summarization call's own - `max_tokens` (cut off), `model_context_window_exceeded` (no room for the summarization prompt), `refusal`, `tool_use`, or `end_turn` (no text) - so give `max_tokens` a few thousand tokens at least, resend with more room or fewer messages as the reason suggests, or continue without one. Custom `instructions` replace the server's summarization prompt whole (a blank value counts as absent), so ask for text only and no tool call yourself; the summarizer reads the whole conversation either way, earlier thinking included (unlike threshold compaction with custom instructions on models with preserved thinking, which leaves earlier thinking out). Keep taking turns against the full history while it runs, and do not edit anything already sent.
|
||||
|
||||
@@ -88,7 +88,7 @@ The scan and the diff will tempt you to report things the check does not care ab
|
||||
- **Measuring on a slice that never replays thinking.** The first request of every conversation replays nothing; short turns may return no thinking block; a harness that strips thinking has nothing to check. Read the replayed-thinking count before the drop count, every run.
|
||||
- **Counting entries instead of breaks.** A stale block re-fails on every later request. Report conversations with a first break and the turn it happened at; an entries-per-request number only ever goes up with conversation length.
|
||||
- **Trusting the header over the body.** The diagnosis header is best-effort and unpublished; `input_transformations` is the contract. A drop with no header is still a drop; a header-only pipeline misses every drop where the header did not arrive.
|
||||
- **Reading a header-only run as an enforcement test.** On an organization that is not enforced yet the header alone records failures as `thinking_mismatch_allowed` and drops nothing: good for finding edits in production, no measure of what enforcement costs. Set `prefix_mismatch_behavior` for that.
|
||||
- **Reading a header-only run as an enforcement test.** On a request that gets no error the header alone records failures as `thinking_mismatch_allowed` and drops nothing: good for finding edits in production, no measure of what enforcement costs. Set `prefix_mismatch_behavior` for that.
|
||||
- **Misspelling the field.** Only `block_binding.prefix_mismatch_behavior` is the documented name; the probe removes any other key it finds under `block_binding` and says which; production code should write the documented name.
|
||||
- **Reading the capture from the app's own objects.** A capture rebuilt from ORM or domain objects hides the re-serialization the check catches. Capture at the HTTP layer.
|
||||
- **Replaying someone else's conversation.** A capture from another organization still gets its blocks dropped, but it is not diagnosed, and the drop teaches nothing about the harness. Replay with a key from the organization that produced the capture.
|
||||
@@ -100,6 +100,6 @@ The scan and the diff will tempt you to report things the check does not care ab
|
||||
- **A beta name that never arrives.** Beta names are the same on every platform that accepts them, but not every platform accepts every beta, and how they are sent differs (the Beta headers page, "Beta features on other platforms", `https://platform.claude.com/docs/en/api/beta-headers#beta-features-on-other-platforms`). Claude Platform on AWS, Microsoft Foundry, Google Cloud and Claude in Amazon Bedrock (`bedrock-mantle` endpoints) take them in the `anthropic-beta` header, as the Claude API does; Amazon Bedrock's InvokeModel API reads them from the request body, not from a header - list them in the body's `anthropic_beta` array, one name per element. To send several betas, put their names in one header, separated by commas: Google Cloud reads only one `anthropic-beta` header and ignores the rest. Without `thinking-binding-controls-2026-08-01` the response has no `input_transformations` and drops are silent, which is no evidence of a clean history.
|
||||
- **Relaying the user's words as a system message on Claude Sonnet 5.5 or Claude Haiku 5.5.** The Mid-conversation system messages page: these models are trained to resist prompt injection through tool results, so they can treat a system message placed right after a tool result as untrusted text and ignore it. Append the user's words as a `text` block after the last `tool_result` in the same `user` message; keep harness notices, such as reminders, in a separate mid-conversation system message after that `user` message, and never put a notice and the user's words in the same block. Both forms are append-only, so the choice does not affect the check.
|
||||
- **An unrecorded strip.** Stripping thinking after a 400 without making the strip deterministic and recorded re-sends the refused blocks on the next turn and fails again, every turn, for the rest of the conversation.
|
||||
- **Leaving the production value unset.** Defaults differ by surface and by account age; an unset field on a not-yet-enforced account means the check is only recorded (`thinking_mismatch_allowed`), and that default changes the day the account or the model is enforced. Set it, and monitor the entries or the 400s.
|
||||
- **Assuming a new account behaves like the old one.** Except on Claude Fable 5.2, Claude Mythos 5.2 and Claude Mythos 5.1, enforcement goes by the creation date of the account that sends the request. Traffic moved to an account created on or after August 31, 2026 - a new organization, a new cloud account - is checked by default with `"error"`, so a harness whose edits went unnoticed on the older account starts returning 400s on the new one. Fix the edits, or set the field explicitly, before moving traffic.
|
||||
- **Leaving the production value unset.** Defaults differ by model and by surface; an unset field can mean the check is only recorded (`thinking_mismatch_allowed`), and a later request can get the 400 instead. Set it, and monitor the entries or the 400s.
|
||||
- **Assuming no error today means none tomorrow.** Except on Claude Fable 5.2, Claude Mythos 5.2 and Claude Mythos 5.1, a request with the field unset might or might not get the 400 (on Bedrock and Vertex, the 400 applies to accounts and projects that first used Claude there on or after August 31, 2026; earlier ones might or might not get it). One result promises nothing about later requests, including ones moved to a new organization or cloud account. A harness whose edits went unnoticed can start returning 400s, so fix the edits, or set the field explicitly.
|
||||
- **Mistaking the model check for this one.** `model_binding_mismatch` entries after a model switch are expected and unbilled; only `prefix_binding_mismatch` is a harness finding.
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -64,7 +64,7 @@ Many requests share a large fixed preamble (few-shot examples, retrieved docs, i
|
||||
|
||||
### Mid-conversation system messages
|
||||
|
||||
**Claude Opus 5, Claude Opus 5.5, Claude Opus 4.8, Claude Fable 5, Claude Fable 5.1, Claude Fable 5.2, Claude Mythos 5, Claude Mythos 5.1, Claude Mythos 5.2, Claude Sonnet 5.5, and Claude Haiku 5.5; no beta header. Not available on Claude Sonnet 5** - use top-level `system` there. (Sources conflict on Claude Sonnet 5: the model config marks it supported, but every canonical docs page omits it. Treat it as unsupported and catch the 400.) When an operator instruction arrives mid-conversation - a mode switch, updated context, dynamically injected state - send it as `{"role": "system", "content": "..."}` appended to `messages[]`, rather than editing top-level `system`. Editing top-level `system` changes the prefix ahead of the entire conversation history, so every cached turn is re-processed uncached; a `role: "system"` message sits after the history and leaves the cached prefix intact.
|
||||
**Claude Opus 5, Claude Opus 5.5, Claude Opus 4.8, Claude Fable 5, Claude Fable 5.1, Claude Fable 5.2, Claude Mythos 5, Claude Mythos 5.1, Claude Mythos 5.2, Claude Sonnet 5.5, and Claude Haiku 5.5; no beta header. Not available on Claude Sonnet 5** - use top-level `system` there. When an operator instruction arrives mid-conversation - a mode switch, updated context, dynamically injected state - send it as `{"role": "system", "content": "..."}` appended to `messages[]`, rather than editing top-level `system`. Editing top-level `system` changes the prefix ahead of the entire conversation history, so every cached turn is re-processed uncached; a `role: "system"` message sits after the history and leaves the cached prefix intact.
|
||||
|
||||
```json
|
||||
// Top-level system stays byte-identical; new instruction goes after the cached history
|
||||
@@ -78,7 +78,7 @@ Many requests share a large fixed preamble (few-shot examples, retrieved docs, i
|
||||
|
||||
This is also the prompt-injection-safe replacement for embedding operator instructions as text inside a user turn (the `<system-reminder>` pattern): both have the same caching profile, but `role: "system"` is the non-spoofable operator channel, whereas text inside user/tool content can be forged by anything that writes to user-visible input.
|
||||
|
||||
Must follow a `role: "user"` message (or an `assistant` message ending in server-tool use), and must be either the last entry in `messages` or be followed by an `assistant` turn; cannot be `messages[0]` - use top-level `system` for the initial prompt. Content is text-only. Unsupported models return a 400 (`BadRequestError`: `role 'system' is not supported on this model`); catch that error and fall back to putting the instruction in a user-turn `<system-reminder>` block.
|
||||
Must follow a `role: "user"` message (or an `assistant` message ending in server-tool use), and must be either the last entry in `messages` or be followed by an `assistant` turn; cannot be `messages[0]` - use top-level `system` for the initial prompt. Content is text-only. Decide from the model ID and the platform (`shared/platform-availability.md`) whether to send one, not by catching an error. Where they aren't supported, put the instruction in a user-turn `<system-reminder>` block.
|
||||
|
||||
**Per-turn reminders in a tool loop: turn-scoped messages, never deleted.** A reminder injected into history and removed on the next request is a history edit - the cache misses from that point and, on Claude Fable 5.2, Claude Mythos 5.2, Claude Fable 5.1, Claude Mythos 5.1, Claude Opus 5.5, Claude Sonnet 5.5, and Claude Haiku 5.5, every later thinking block is invalidated. Instead give the `role: "system"` message `clear_at: "next_user_message"` (beta `mid-conversation-system-clear-at-2026-08-21`; same models and platforms as mid-conversation system messages): it renders for one turn, then stays in the transcript cleared - costing no input tokens, not cache-eligible (`cache_control` on it is a 400; put the breakpoint on the preceding user turn), and still part of the prefix. Append a fresh copy after each `tool_result` message and leave earlier copies in place; without the beta, a `text` block after the `tool_result` blocks in the same user message, earlier copies kept. Separately, per-message effort (beta `mid-conversation-output-config-2026-07-01`; Claude Fable 5.2, Claude Mythos 5.2, Claude Fable 5.1, Claude Mythos 5.1, Claude Opus 5, Claude Opus 5.5, Claude Sonnet 5.5, and Claude Haiku 5.5 with thinking on; platforms: `shared/platform-availability.md`): a `role: "system"` message with `content: []` and `output_config: {effort: ...}` changes effort for later turns (a change placed after a turn of only `tool_result` blocks waits for the next user turn with new input) **without** the messages-cache invalidation that a top-level `effort` change causes, and on its own is exempt from the placement rules (it is accepted anywhere, but add it after everything already sent and keep it in place; next to a message with content, both follow them) - see the Invalidation hierarchy below and `shared/model-migration.md` -> Migrating to Claude Fable 5.1 from Claude Fable 5 -> New API features.
|
||||
|
||||
@@ -203,7 +203,7 @@ Language-specific access: `response.usage.cache_read_input_tokens` (Python/TS/Ru
|
||||
|
||||
If `cache_creation_input_tokens` is instead near the full conversation size on every request, either the prefix is being rewritten upstream of the breakpoint, or the write is happening for a reason payload diffing and cache diagnostics can't localize - with thinking enabled on a model that strips prior-turn thinking blocks the invalidation is server-side (§ Invalidation hierarchy), and a single turn that appends more than 20 positions (parallel tool-call runs collapse to one position - § 20-block lookback window) pushes the previous entry out of the lookback so every request rewrites the whole conversation with byte-identical payloads (§ 20-block lookback window). Rule both show-nothing cases out first from the model and the turn shape. Reads can only land on positions where a previous request wrote a breakpoint, so the usage fields say *that* the prefix broke (reads collapse, often to zero) but not where - the payload diff or cache diagnostics below localizes the exact point.
|
||||
|
||||
**Finding the invalidator.** Log several consecutive request payloads (the full JSON body) and diff adjacent pairs. In a growing conversation, adjacent payloads legitimately differ at the end (the newly appended turn); what must be byte-identical is the overlap - the previous request's prompt should reappear unchanged as a prefix of the next. Strip `cache_control` markers before diffing: the moving marker always differs between adjacent requests and is not an invalidator (previously-marked blocks are still cache hits). The first remaining divergence inside the overlapping region is the invalidation point. This catches the class of bug code review misses - nondeterministic serialization, a library reordering keys or fields, a value that changes between requests but not within one. On the Claude API, cache diagnostics (beta header `cache-diagnosis-2026-04-07`) does this comparison server-side once you opt in: send the header on **every** request - fingerprints are stored only for requests that carried it, so a one-shot retrofit fails with `previous_message_not_found` - then pass the previous response's `id` as `diagnostics.previous_message_id` and the response's `diagnostics` object names where the two requests diverged (model, system, tools, or message history). No payload logging needed. Availability: `shared/platform-availability.md`.
|
||||
**Finding the invalidator.** Log several consecutive request payloads (the full JSON body) and diff adjacent pairs. In a growing conversation, adjacent payloads legitimately differ at the end (the newly appended turn); what must be byte-identical is the overlap - the previous request's prompt should reappear unchanged as a prefix of the next. Strip `cache_control` markers before diffing: the moving marker always differs between adjacent requests and is not an invalidator (previously-marked blocks are still cache hits). The first remaining divergence inside the overlapping region is the invalidation point. This catches the class of bug code review misses - nondeterministic serialization, a library reordering keys or fields, a value that changes between requests but not within one. Where the platform has it, cache diagnostics does this comparison server-side once you opt in: include a `diagnostics` object on **every** request, with `previous_message_id: null` on the first and the previous response's `id` after that. On later turns, `diagnostics.cache_miss_reason.type` names where the two requests diverged (model, system, tools, or message history). `previous_message_not_found` (typically because the previous request left the object out, ran in another workspace, or is too old) and `unavailable` mean no comparison was made. `diagnostics: null` means nothing diverged before the last breakpoint, not that the cache hit, and `{"cache_miss_reason": null}` means the comparison wasn't ready, so check the next turn. No payload logging needed. Availability: `shared/platform-availability.md`.
|
||||
|
||||
**Unexplained writes:** `usage.cache_creation` breaks `cache_creation_input_tokens` down by TTL (`ephemeral_5m_input_tokens` / `ephemeral_1h_input_tokens`). Server tools such as web search automatically insert a 5-minute cache write after tool results when the request already uses caching - writes at a position you didn't mark; expected behavior, not an invalidator.
|
||||
|
||||
|
||||
@@ -109,46 +109,57 @@ Any `tool_choice` value can also include `"disable_parallel_tool_use": true` to
|
||||
|
||||
### Tool Runner vs Manual Loop
|
||||
|
||||
**Tool Runner (Recommended over the manual loop):** The SDK's tool runner handles the agentic loop automatically - it calls the API, detects tool use requests, executes your tool functions, feeds results back to Claude, and repeats until Claude stops calling tools. Available in Python, TypeScript, Java, Go, Ruby, PHP, and C# SDKs (beta). The Python SDK also provides MCP conversion helpers (`anthropic.lib.tools.mcp`) to convert MCP tools, prompts, and resources for use with the tool runner - see `python/claude-api/tool-use.md` for details. **Default to the tool runner** for any custom-tool agent on the Messages API.
|
||||
**Tool Runner (Recommended over the manual loop):** The SDK's tool runner handles the agentic loop automatically - it calls the API, detects tool use requests, executes your tool functions, feeds results back to Claude, and repeats until Claude stops calling tools. Available in Python, TypeScript, Java, Go, Ruby, PHP, and C# SDKs (beta). The Python SDK also provides MCP conversion helpers (`anthropic.lib.tools.mcp`) to convert MCP tools, prompts, and resources for use with the tool runner - see `python/claude-api/tool-use.md` for details. **Default to the tool runner** for any custom-tool agent on the Messages API, unless it needs human-in-the-loop approval, custom logging or conditional execution (Manual Agentic Loop, below).
|
||||
|
||||
**The tool runner is not a black box - "I need control" is rarely a reason to drop to the manual loop.** Each iteration yields the assistant message *before* the tools run and lets you intervene, so most "fine-grained control" needs are covered without hand-writing the loop:
|
||||
**The tool runner is not a black box.** Each iteration yields the assistant message *before* the tools run and lets you intervene, so many control needs are covered without hand-writing the loop:
|
||||
|
||||
- **Human-in-the-loop approval / gating** - gate in the tool's run function (return a "user declined" result instead of executing), or inspect the tool call in the yielded message and override the pending request with `set_messages_params()` / `setMessagesParams()` / `append_messages()` / `pushMessages()` to allow or deny *before* the tool executes. The runner runs your function automatically only if you don't intervene.
|
||||
- **Error interception** - inspect the tool result before it returns to Claude (`generate_tool_call_response()` / `generateToolResponse()`); stop early or handle it yourself.
|
||||
- **Result modification** - mutate the tool result before it goes back (e.g. add `cache_control` for prompt caching, or transform the output).
|
||||
- **Per-turn retries / param changes** - e.g. bump `max_tokens` and re-run a truncated turn; bound the whole loop with `max_iterations`.
|
||||
- **Streaming and compaction** are both supported. For compaction, use server-side compaction (beta `compact-2026-01-12`, a `compact_20260112` edit in `context_management`), or compact when you choose with `compact_before_next_turn()` (`anthropic` 1.7.0 and later) / `compactBeforeNextTurn()` (`@anthropic-ai/sdk` 0.127.0 and later); these two need the beta `compact-2026-09-04` instead, and the Availability section of `https://platform.claude.com/docs/en/build-with-claude/compaction-on-demand` names its models and platforms. The runner's old client-side compaction option is gone from Python 1.0.0 and from the TypeScript and Ruby releases that send API version `2026-10-21`.
|
||||
- **Human-in-the-loop approval / gating** - the exception: use the manual loop (below). If you stay on the runner, gate inside the tool's run function (return a "user declined" result instead of executing), which works in every SDK. In some SDKs you can also deny a call from the loop (a take-over): inspect the tool call in the yielded message, then send the assistant message and a `tool_result` for every call yourself. Limit the number of turns. **In Python and C# the function still runs after a take-over, and Go has no take-over**, so gate inside the function there (table below).
|
||||
|
||||
These hooks are SDK helper features, not separate API parameters - for the exact method names and worked examples, fetch the per-language SDK repo listed in `shared/live-sources.md` -> *Claude API SDK Repositories* (the tool-runner helpers live in each repo's `tools.md` / `helpers.md`). The bundled `python/claude-api/tool-use.md` and `typescript/claude-api/tool-use.md` show the basic tool-runner setup.
|
||||
These hooks are SDK helper features, not separate API parameters. Each `{lang}/claude-api/tool-use.md` shows that SDK's approval gate; other helper names are in the per-language SDK repo listed in `shared/live-sources.md` -> *Claude API SDK Repositories*.
|
||||
|
||||
| SDK | Take over from the loop | Does that stop the function? |
|
||||
|---|---|---|
|
||||
| TypeScript | `runner.pushMessages({ role: "assistant", content: message.content }, { role: "user", content: toolResults })` | Yes, if you push a `tool_result` for every call. If you push only the assistant turn, the tools still run |
|
||||
| Java | `runner.setNextParams(...)` | Yes |
|
||||
| PHP | `$runner->pushMessages(['role' => 'assistant', 'content' => $message->content], ['role' => 'user', 'content' => $toolResults])` | Yes, if you push a `tool_result` for every call. If you push only the assistant turn, the tools still run |
|
||||
| Ruby | `runner.feed_messages({ role: "assistant", content: message.content }, { role: "user", content: tool_results })` inside `each_message` | Yes, but `max_iterations` doesn't count those turns, so count them yourself |
|
||||
| Python | `runner.append_messages(message, tool_results)` | No: the function runs; leaving the loop (`break`) stops it, but the call stays pending, so call `runner.close()` before you leave |
|
||||
| C# | `runner.PushMessages(...)` | No: gate in `Run` and return a "user declined" result |
|
||||
| Go | None: `AppendMessages` doesn't take over | No: gate in the tool's handler |
|
||||
|
||||
**Don't drop to a manual loop because of these misconceptions:**
|
||||
|
||||
- The tool runner does not require Zod/Pydantic - `betaTool()` (TS) and `@beta_tool` (Python) accept raw JSON Schema; other SDKs use plain structs/maps/classes.
|
||||
- The runner makes detecting the final turn *easier*, not harder - iteration ends when Claude stops calling tools, and the last yielded message is the final response. Most SDKs also offer a one-shot variant (`runner.until_done()` / `runner.runUntilDone()` / `RunToCompletion()`).
|
||||
- Confirmation/approval gates work with the runner (see Security below).
|
||||
|
||||
**Manual Agentic Loop:** Reach for this only when you want to own the *entire* loop - you need control the runner does not expose (e.g., a custom transport, request shapes the SDK cannot build, per-token streaming on SDKs whose runner does not support it), you'd rather not take the beta dependency, or your control flow doesn't fit the runner's per-turn hooks (e.g. interleaving unrelated work mid-loop). Approval gates, logging, interception, result modification, and conditional execution do **not** require it - the tool runner covers those (above). Loop until `stop_reason == "end_turn"`, always append the full `response.content` to preserve tool_use blocks, and ensure each `tool_result` includes the matching `tool_use_id`.
|
||||
**Manual Agentic Loop:** Use this for human-in-the-loop approval, custom logging, or conditional execution, as the tool runner page recommends (`https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner.md`). Also reach for it when you want to own the *entire* loop - you need control the runner does not expose (e.g., a custom transport, request shapes the SDK cannot build, per-token streaming on SDKs whose runner does not support it), you'd rather not take the beta dependency, or your control flow doesn't fit the runner's per-turn hooks (e.g. interleaving unrelated work mid-loop). Error interception and result modification don't require it - the tool runner covers those (above). Loop while `stop_reason == "tool_use"` (any other stop except `pause_turn`, below, can cut a tool call off: don't run it), always append the full `response.content` to preserve tool_use blocks, and ensure each `tool_result` includes the matching `tool_use_id`.
|
||||
|
||||
**Stop reasons for server-side tools:** When using server-side tools (code execution, web search, etc.), the API runs a server-side sampling loop. If this loop reaches its default limit of 10 iterations, the response will have `stop_reason: "pause_turn"`. To continue, re-send the user message and assistant response and make another API request - the server will resume where it left off. Do NOT add an extra user message like "Continue." - the API detects the trailing `server_tool_use` block and knows to resume automatically.
|
||||
**Stop reasons for server-side tools:** When using server-side tools (code execution, web search, etc.), the API runs a server-side sampling loop. If this loop reaches its iteration limit, the response will have `stop_reason: "pause_turn"`. To continue, append the response to `messages` as a new assistant message, unchanged, and make another API request - the server will resume where it left off. Keep every paused response: a later response can open with the result of a tool call from an earlier one, and the API returns a 400 if that tool call is missing. Do NOT add an extra user message like "Continue." - the API detects the trailing `server_tool_use` block and knows to resume automatically.
|
||||
|
||||
```python
|
||||
# Handle pause_turn in your agentic loop
|
||||
if response.stop_reason == "pause_turn":
|
||||
messages = [
|
||||
{"role": "user", "content": user_query},
|
||||
{"role": "assistant", "content": response.content},
|
||||
]
|
||||
# Put this block right after every request, before other stop_reason checks
|
||||
for _ in range(5): # cap the resumes to prevent infinite loops
|
||||
if response.stop_reason != "pause_turn":
|
||||
break
|
||||
messages.append({"role": "assistant", "content": response.content})
|
||||
# Make another API request - server resumes automatically
|
||||
# (once a response has a container, also pass container=<last container.id>)
|
||||
response = client.messages.create(
|
||||
model="claude-opus-5-5", messages=messages, tools=tools
|
||||
model="claude-opus-5-5", max_tokens=16000, messages=messages, tools=tools
|
||||
)
|
||||
if response.stop_reason == "pause_turn":
|
||||
raise RuntimeError("giving up: turn still paused after 5 resumes")
|
||||
```
|
||||
|
||||
**Note:** the Python and TypeScript tool runners resume `pause_turn` by themselves from `anthropic` 1.1.0 and `@anthropic-ai/sdk` 0.121.0, and each resume counts toward `max_iterations`. Earlier releases end the runner on a paused turn and return it as the final message, with no error; handle `pause_turn` in a manual loop there. See each language's `tool-use.md`.
|
||||
|
||||
Set a `max_continuations` limit (e.g., 5) to prevent infinite loops. For the full guide, see: `https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons`
|
||||
If your loop already handles `pause_turn` by appending the response and sending the request again, as the Python, TypeScript and C# loops in `{lang}/claude-api/tool-use.md` do, you don't need the block above, but still cap its resumes. In a manual loop, once a response has a `container` (code execution, including the web tools' dynamic filtering), send the last `container.id` you received as `container` on every later request. A later response may have no `container`: keep the ID you have. Without it, the resumed turn runs in a new container and files written before the pause are gone. With Skills, send `container={"id": <id>, "skills": [...]}`. For the full guide, see: `https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons`
|
||||
|
||||
> **Security:** The tool runner executes your tool functions automatically whenever Claude requests them. For tools with side effects (sending emails, modifying databases, financial transactions), validate inputs and gate destructive operations behind human approval. **Both** the tool runner and the manual loop support this - with the tool runner, gate inside the tool's run function (prompt the user and return a "user declined" result instead of executing), or inspect the tool call in each yielded message and take over message history with `set_messages_params()` / `setMessagesParams()` to allow or deny *before* the tool runs (it executes your function automatically only if you don't intervene); with the manual loop you gate inline before calling the function.
|
||||
> **Security:** The tool runner executes your tool functions automatically whenever Claude requests them. For tools with side effects (sending emails, modifying databases, financial transactions), validate inputs and gate destructive operations behind human approval. Use the manual loop for this, and gate inline before calling the function. If you already use the tool runner, gate as described under Tool Runner vs Manual Loop.
|
||||
|
||||
---
|
||||
|
||||
@@ -199,7 +210,7 @@ Claude automatically gains access to `bash_code_execution` (run shell commands)
|
||||
- **Math**: sympy, mpmath
|
||||
- **Utilities**: tqdm, python-dateutil, pytz, sqlite3
|
||||
|
||||
Additional packages can be installed at runtime via `pip install`.
|
||||
No other packages can be installed at runtime: the container has no internet access.
|
||||
|
||||
### Supported File Types for Upload
|
||||
|
||||
@@ -211,7 +222,7 @@ Additional packages can be installed at runtime via `pip install`.
|
||||
|
||||
### Container Reuse
|
||||
|
||||
Reuse containers across requests to maintain state (files, installed packages, variables). Extract the `container_id` from the first response and pass it to subsequent requests.
|
||||
Reuse containers across requests to maintain state (files, and Python variables with programmatic tool calling). Extract `container.id` from a response and pass it to subsequent requests.
|
||||
|
||||
### Response Structure
|
||||
|
||||
@@ -234,27 +245,27 @@ Web search and web fetch let Claude search the web and retrieve page content. Th
|
||||
|
||||
```json
|
||||
[
|
||||
{ "type": "web_search_20260209", "name": "web_search" },
|
||||
{ "type": "web_fetch_20260209", "name": "web_fetch" }
|
||||
{ "type": "web_search_20260318", "name": "web_search" },
|
||||
{ "type": "web_fetch_20260318", "name": "web_fetch" }
|
||||
]
|
||||
```
|
||||
|
||||
### Dynamic Filtering (Claude Opus 5.5 / Claude Opus 5 / Fable 5/5.1/5.2 / Mythos 5/5.1/5.2 / Opus 4.8 / Opus 4.7 / Opus 4.6 / Claude Sonnet 5.5 / Sonnet 5 / Sonnet 4.6)
|
||||
### Dynamic Filtering (Claude 4.6 and later models, Fable and Mythos included)
|
||||
|
||||
The `web_search_20260209` and `web_fetch_20260209` versions support **dynamic filtering** - Claude writes and executes code to filter search results before they reach the context window, improving accuracy and token efficiency. Dynamic filtering is built into these tool versions and activates automatically; you do not need to separately declare the `code_execution` tool or pass any beta header.
|
||||
`web_search_20260209`, `web_fetch_20260209` and later versions support **dynamic filtering** - Claude writes and executes code to filter search results before they reach the context window, improving accuracy and token efficiency. Dynamic filtering is built into these tool versions and activates automatically; you do not need to separately declare the `code_execution` tool or pass any beta header. `web_fetch_20260309` and later also accept `use_cache: false` to bypass the fetch cache - use it only when the user asks for fresh content or the page changes quickly.
|
||||
|
||||
```json
|
||||
{
|
||||
"tools": [
|
||||
{ "type": "web_search_20260209", "name": "web_search" },
|
||||
{ "type": "web_fetch_20260209", "name": "web_fetch" }
|
||||
{ "type": "web_search_20260318", "name": "web_search" },
|
||||
{ "type": "web_fetch_20260318", "name": "web_fetch" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Without dynamic filtering, the previous `web_search_20250305` version is also available.
|
||||
|
||||
> **Note:** Only include the standalone `code_execution` tool when your application needs code execution for its own purposes (data analysis, file processing, visualization) independent of web search. Including it alongside `_20260209` web tools creates a second execution environment that can confuse the model.
|
||||
> **Note:** When your application also needs code execution for its own purposes (data analysis, file processing, visualization), include `code_execution_20260120` or later alongside web tools dated `_20260209` or later; the API rejects older code execution versions alongside them.
|
||||
|
||||
---
|
||||
|
||||
@@ -282,9 +293,9 @@ For full documentation, fetch:
|
||||
|
||||
## Mid-conversation tool changes (Beta)
|
||||
|
||||
**Beta header `inline-tools-2026-09-15` (by value or by reference) or `mid-conversation-tool-changes-2026-07-01` (by reference; the only one on Bedrock Mantle and Vertex); Claude Opus 5, Claude Opus 5.5, Claude Opus 4.8, Claude Fable 5, Claude Fable 5.1, Claude Fable 5.2, Claude Mythos 5, Claude Mythos 5.1, Claude Mythos 5.2, Claude Sonnet 5.5, and Claude Haiku 5.5 - 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.
|
||||
**Beta header `inline-tools-2026-09-15` (by value or by reference) or `mid-conversation-tool-changes-2026-07-01` (by reference; the only one on Bedrock Mantle and Vertex); Claude Opus 5, Claude Opus 5.5, Claude Opus 4.8, Claude Fable 5, Claude Fable 5.1, Claude Fable 5.2, Claude Mythos 5, Claude Mythos 5.1, Claude Mythos 5.2, Claude Sonnet 5.5, and Claude Haiku 5.5 - not Claude Sonnet 5 (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[]`. On the Claude API, Claude Platform on AWS and Claude Models on Google Cloud (Anthropic managed), `inline-tools-2026-09-15` covers these changes too, and a `tool_addition` can carry a full definition instead (below). These examples name a tool with a `tool_reference`:
|
||||
Both operations are content blocks on a `{"role": "system", ...}` message appended to `messages[]`. On the Claude API, Claude Platform on AWS, Claude Models on Google Cloud (Anthropic managed) and Microsoft Foundry, `inline-tools-2026-09-15` covers these changes too, and a `tool_addition` can carry a full definition instead (below). These examples name a tool with a `tool_reference`:
|
||||
|
||||
```python
|
||||
# Removal - must sit immediately before an assistant message, or last in messages.
|
||||
@@ -310,7 +321,7 @@ tools = [
|
||||
]
|
||||
```
|
||||
|
||||
**To change a tool's definition**, under `inline-tools-2026-09-15` (Claude API, Claude Platform on AWS, Claude Models on Google Cloud (Anthropic managed)) send a `tool_addition` whose `tool` is `{"type": "tool_definition", "definition": {...}}`: it replaces the earlier definition of that name from there on, and `tools[]` stays as first sent (`shared/preserved-thinking-migration/causes.md`). During the beta, the computer use and browser use tools can't be defined this way: declare those in `tools` and add them by reference. Without that beta, no block can change a tool under the same name: keep each tool's text frozen for the conversation and roll new text out in a new conversation. Editing the entry in `tools[]` restarts the cache and invalidates earlier thinking blocks: sending them back returns a 400 on every account on Claude Fable 5.2 and Claude Mythos 5.2, and on other models that run the check, depending on the account (`shared/error-codes.md`).
|
||||
**To change a tool's definition**, under `inline-tools-2026-09-15` (Claude API, Claude Platform on AWS, Claude Models on Google Cloud (Anthropic managed), Microsoft Foundry) send a `tool_addition` whose `tool` is `{"type": "tool_definition", "definition": {...}}`: it replaces the earlier definition of that name from there on, and `tools[]` stays as first sent (`shared/preserved-thinking-migration/causes.md`). During the beta, the computer use and browser use tools can't be defined this way: declare those in `tools` and add them by reference. Without that beta, no block can change a tool under the same name: keep each tool's text frozen for the conversation and roll new text out in a new conversation. Editing the entry in `tools[]` restarts the cache and invalidates earlier thinking blocks: sending them back returns a 400 on every account on Claude Fable 5.2 and Claude Mythos 5.2, and possibly on other models that run the check (`shared/error-codes.md`).
|
||||
|
||||
> Warning: Earlier previews used a different beta header and different block shapes; both are deprecated. Use `inline-tools-2026-09-15` or `mid-conversation-tool-changes-2026-07-01` with `tool_addition` / `tool_removal`.
|
||||
|
||||
@@ -326,14 +337,13 @@ Agent Skills package task-specific instructions and files that Claude loads when
|
||||
|
||||
Required on each request:
|
||||
|
||||
1. `client.beta.messages.create(...)` with the `code-execution-2025-08-25` beta flag (Skills is out of beta - no `skills-2025-10-02` header needed).
|
||||
1. `client.messages.create(...)` - no beta header.
|
||||
2. `container={"skills": [{"type": "anthropic", "skill_id": "<id>", "version": "latest"}]}` - the skills list selects which skills are available inside the execution container.
|
||||
3. `tools=[{"type": "code_execution_20260521", "name": "code_execution"}]` - skills execute via code execution in the container.
|
||||
|
||||
```python
|
||||
response = client.beta.messages.create(
|
||||
response = client.messages.create(
|
||||
model="claude-opus-5-5", max_tokens=16000,
|
||||
betas=["code-execution-2025-08-25"],
|
||||
container={"skills": [{"type": "anthropic", "skill_id": "pptx", "version": "latest"}]},
|
||||
tools=[{"type": "code_execution_20260521", "name": "code_execution"}],
|
||||
messages=[{"role": "user", "content": "Create a 3-slide presentation on X"}],
|
||||
@@ -375,11 +385,26 @@ Optional toolset fields: `default_config` (defaults for all tools, e.g. `{"enabl
|
||||
|
||||
## Tool Use Examples
|
||||
|
||||
You can provide sample tool calls directly in your tool definitions to demonstrate usage patterns and reduce parameter errors. This helps Claude understand how to correctly format tool inputs, especially for tools with complex schemas.
|
||||
Add `input_examples` to a tool definition to show Claude how to call it: when to include optional parameters, which formats to use, how to structure nested inputs. It is a plain field on the normal `tools` entry, so it needs no beta header and no beta namespace.
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "get_weather",
|
||||
"description": "Get the current weather for a location",
|
||||
"input_schema": {
|
||||
"type": "object",
|
||||
"properties": {"location": {"type": "string"}, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}},
|
||||
"required": ["location"]
|
||||
},
|
||||
"input_examples": [{"location": "San Francisco, CA", "unit": "fahrenheit"}, {"location": "New York, NY"}]
|
||||
}
|
||||
```
|
||||
|
||||
Validate each example against `input_schema` yourself: the API usually returns a 400 for an invalid one, but not always (for example, it may not check when the schema uses `pattern`). Examples work on user-defined tools and Anthropic-defined client tools, but not on server tools or the computer use and browser use toolsets. They add to prompt tokens: about 100 for an example with a few flat values, about 200 for one with nested objects.
|
||||
|
||||
For full documentation, fetch:
|
||||
|
||||
- URL: `https://platform.claude.com/docs/en/agents-and-tools/tool-use/implement-tool-use`
|
||||
- URL: `https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools.md`
|
||||
|
||||
---
|
||||
|
||||
@@ -399,6 +424,18 @@ For full documentation (member reference, batch actions, scaling, the `computer_
|
||||
|
||||
---
|
||||
|
||||
## Client-Side Tools: Browser Use
|
||||
|
||||
The browser use tool lets Claude drive a browser your application runs. In Python and TypeScript, start with the SDK's browser toolset class (beta), which the tool runner can drive: `https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk.md`. The rest of this section is for handling the calls yourself. The tool runs on Claude Opus 4.8 and later, Sonnet 5 and later, Haiku 5.5, and Fable and Mythos models, and isn't available in Managed Agents. It is one `tools` entry, `{"type": "browser_toolset_20260801"}`, with **no `name`** and no beta header. Claude calls the toolset's member tools (`navigate`, `read_page`, `left_click`, `type`, `screenshot`, ...), often several per turn. Each call is a `tool_use` block whose `name` is the member tool, with `"toolset_name": "browser"` and only that tool's parameters in `input`. Run them in order and return one `tool_result` per call in the next `user` message, **each echoing `"toolset_name": "browser"`**; answer every call, or the next request is rejected. If a call fails, return `is_error: true` with a description for that block, stop there, and answer every later call in the turn with `is_error: true` and the exact text `Not executed: an earlier action in this turn failed.`
|
||||
|
||||
`javascript_exec`, `file_upload`, `read_console` and `read_network` are off by default. Turn one on with `configs`, as in `{"type": "browser_toolset_20260801", "configs": {"javascript_exec": {"enabled": true}}}`, only when your executor implements it and the task needs it. `javascript_exec` runs with the page's full privileges, so use it only in sessions that hold no credentials.
|
||||
|
||||
For full documentation (member reference, batch actions, targets and coordinates, tab state), fetch:
|
||||
|
||||
- URL: `https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool.md`
|
||||
|
||||
---
|
||||
|
||||
## Context Editing
|
||||
|
||||
Context editing clears stale tool results and thinking blocks from the transcript as a long-running agent accumulates turns. Unlike compaction (which summarizes), context editing prunes - the cleared content is removed, not replaced. Use it when old tool outputs are no longer relevant and you want to keep the transcript lean without losing the conversation structure.
|
||||
|
||||
47
skills/claude-api/shared/vision-coordinates.md
Normal file
47
skills/claude-api/shared/vision-coordinates.md
Normal file
@@ -0,0 +1,47 @@
|
||||
# Image Coordinates and Resizing
|
||||
|
||||
Read this when code uses pixel coordinates Claude returns (bounding boxes, click points, UI elements), or needs the size Claude processes an image at.
|
||||
|
||||
Coordinates are pixel positions in the image Claude processes: your image after any resize, with the origin at the top left. An image within the model's limits is not resized, so coordinates match it directly. A larger one is downscaled first, so its coordinates need converting back.
|
||||
|
||||
| Tier | Models | Max long edge | Max visual tokens |
|
||||
|---|---|---|---|
|
||||
| High-resolution | Claude 4.7 and later models | 2576 px | 4784 |
|
||||
| Standard | All other models | 1568 px | 1568 |
|
||||
|
||||
An image costs `ceil(width / 28) * ceil(height / 28)` visual tokens. Claude resizes to the largest aspect-preserving size that fits both limits, and for most photos and screenshots the token limit decides, not the edge. So compute the size rather than scaling to the edge limit: on the standard tier a 1920x1080 screenshot becomes 1456x819, not 1568x882, and a 1075x1520 scan becomes 924x1307 though both sides are under 1568.
|
||||
|
||||
```python
|
||||
import math
|
||||
|
||||
def resized_size(width, height, max_edge, max_tokens):
|
||||
"""The size Claude resizes an image to, before padding. When porting, keep
|
||||
Python's round(), which sends exact halves to the even neighbor, as the API does."""
|
||||
def fits(w, h):
|
||||
return (math.ceil(w / 28) * 28 <= max_edge and math.ceil(h / 28) * 28 <= max_edge
|
||||
and math.ceil(w / 28) * math.ceil(h / 28) <= max_tokens)
|
||||
if fits(width, height):
|
||||
return width, height
|
||||
if height > width:
|
||||
h, w = resized_size(height, width, max_edge, max_tokens)
|
||||
return w, h
|
||||
aspect = width / height
|
||||
lo, hi = 1, width # lo always fits; hi never fits
|
||||
while lo + 1 < hi:
|
||||
mid = (lo + hi) // 2
|
||||
if fits(mid, max(round(mid / aspect), 1)):
|
||||
lo = mid
|
||||
else:
|
||||
hi = mid
|
||||
return lo, max(round(lo / aspect), 1)
|
||||
```
|
||||
|
||||
- **Resize before sending (most reliable).** Send the image at the size `resized_size` returns, then use the coordinates as they are on that resized image. To mark the original, scale them as in the next bullet.
|
||||
- **Or rescale what comes back.** Clamp x and y to the resized width and height, then compute `x_original = x * original_width / resized_width`, and the same for y. Use the limits of the model you called: the wrong tier silently shifts every coordinate.
|
||||
- **Padding.** Claude pads every image up to a multiple of 28 on the bottom and right. The origin doesn't move; never divide by the padded size, and don't pad it yourself.
|
||||
- **Ask for pixels.** Request absolute pixel coordinates in the prompt. Claude does poorly with normalized ones such as 0 to 1000; normalize in your own code.
|
||||
- **Turn a silent resize into an error.** Set `"transformations": {"oversized_image": "error"}` on the image block, and an image that would be resized gets a 400 naming the size that fits.
|
||||
- **Computer use and browser use.** With `computer_toolset_20260801` or `browser_toolset_20260801`, a screenshot over the limits is rejected when returned as a `tool_result`, not resized. With earlier computer tool versions, it is downscaled like any other image. Either way, resize it first, then scale coordinates back to your screen.
|
||||
- **PDFs.** Pages are rasterized server-side at sizes you don't control, so coordinates can't be reliably mapped back. Rasterize pages to images yourself.
|
||||
|
||||
Full guide: `https://platform.claude.com/docs/en/build-with-claude/vision-coordinates.md`
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
| Feature | Namespace | Key types / call |
|
||||
|---|---|---|
|
||||
| User profiles | beta | `client.beta.userProfiles.create(...)` / `.retrieve(id)` / `.list()`. Pass the returned profile id on `client.beta.messages.create`. Requires a beta header - check the SDK's beta-headers reference for the current flag. |
|
||||
| User profiles | non-beta | `client.userProfiles.create(...)` / `.retrieve(id)` / `.list()`. Pass the returned profile id as `user_profile_id` on `client.messages.create`. |
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -24,6 +24,8 @@ const client = new Anthropic();
|
||||
|
||||
// Explicit API key (only when you must inject a specific key)
|
||||
const client = new Anthropic({ apiKey: "your-api-key" });
|
||||
|
||||
const client = new Anthropic({ defaultHeaders: { "anthropic-workspace-id": "wrkspc_..." } }); // key not scoped to one workspace
|
||||
```
|
||||
|
||||
---
|
||||
@@ -371,7 +373,7 @@ if (fallbackRan && response.stop_reason !== "refusal") {
|
||||
}
|
||||
```
|
||||
|
||||
A `stop_reason: "refusal"` on the final response means the whole chain refused. This array form takes `server-side-fallback-2026-06-01` or `-2026-07-01`; the `fallbacks: "default"` scalar form needs `-2026-07-01` (see `shared/model-migration.md` -> Migrating to Claude Opus 5 -> New API features). Any other `server-side-fallback-*` value returns a 400. The parameter is rejected on the Batches API and unavailable on Amazon Bedrock, Vertex AI, and Microsoft Foundry - register the client-side `betaRefusalFallbackMiddleware` on the client there instead. Full semantics (sticky routing, billing, streaming, echoing fallback turns back): `shared/model-migration.md` -> Migrating to Claude Fable 5.1 -> `refusal` stop reason.
|
||||
A `stop_reason: "refusal"` on the final response means the whole chain refused. This array form takes `server-side-fallback-2026-06-01` or `-2026-07-01`; the `fallbacks: "default"` scalar form needs `-2026-07-01` (see `shared/model-migration.md` -> Migrating to Claude Opus 5 -> New API features). Any other `server-side-fallback-*` value returns a 400. The Batches API rejects the parameter. It is unavailable on Amazon Bedrock, Vertex AI and Microsoft Foundry, and the docs don't list it for Claude Platform on AWS - register the client-side `betaRefusalFallbackMiddleware` on the client there instead. Full semantics (sticky routing, billing, streaming, echoing fallback turns back): `shared/model-migration.md` -> Migrating to Claude Fable 5.1 -> `refusal` stop reason.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -78,17 +78,24 @@ for await (const result of await client.messages.batches.results(
|
||||
)) {
|
||||
switch (result.result.type) {
|
||||
case "succeeded":
|
||||
console.log(
|
||||
`[${result.custom_id}] ${result.result.message.content[0].text.slice(0, 100)}`,
|
||||
);
|
||||
for (const block of result.result.message.content) {
|
||||
if (block.type === "text") {
|
||||
console.log(`[${result.custom_id}] ${block.text.slice(0, 100)}`);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case "errored":
|
||||
if (result.result.error.type === "invalid_request") {
|
||||
case "errored": {
|
||||
const apiError = result.result.error.error;
|
||||
if (apiError.type === "invalid_request_error") {
|
||||
console.log(`[${result.custom_id}] Validation error - fix and retry`);
|
||||
} else {
|
||||
console.log(`[${result.custom_id}] Server error - safe to retry`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "canceled":
|
||||
console.log(`[${result.custom_id}] Canceled`);
|
||||
break;
|
||||
case "expired":
|
||||
console.log(`[${result.custom_id}] Expired - resubmit`);
|
||||
break;
|
||||
|
||||
@@ -33,6 +33,22 @@ console.log(`File ID: ${uploaded.id}`);
|
||||
console.log(`Size: ${uploaded.size_bytes} bytes`);
|
||||
```
|
||||
|
||||
### Set an Expiry
|
||||
|
||||
`expires_in_seconds` sets when a file expires: a whole number of seconds from 3,600 (1 hour) to 7,776,000 (90 days), counted from the upload. It can't be changed later.
|
||||
|
||||
```typescript
|
||||
const temporary = await client.files.upload({
|
||||
file: await toFile(fs.createReadStream("report.pdf"), undefined, {
|
||||
type: "application/pdf",
|
||||
}),
|
||||
expires_in_seconds: 86400,
|
||||
});
|
||||
console.log(`Expires at: ${temporary.expires_at}`);
|
||||
```
|
||||
|
||||
`expires_at` is `null` for a file with no expiry. Use `client.files` with no beta header, as here: requests that send `files-api-2025-04-14` don't get this field back. A message that references an expired file fails. Expiry isn't a guaranteed-deletion control: before relying on it for data handling, read File expiration in `https://platform.claude.com/docs/en/build-with-claude/files.md`.
|
||||
|
||||
---
|
||||
|
||||
## Use a File in Messages
|
||||
@@ -80,6 +96,13 @@ for (const f of files.data) {
|
||||
}
|
||||
```
|
||||
|
||||
### Get File Metadata
|
||||
|
||||
```typescript
|
||||
const meta = await client.files.retrieveMetadata("file_011CNha8iCJcU1wXNR6q4V8w");
|
||||
console.log(meta.filename, meta.size_bytes);
|
||||
```
|
||||
|
||||
### Delete a File
|
||||
|
||||
```typescript
|
||||
|
||||
@@ -66,7 +66,7 @@ Zod is optional - `betaTool()` from `@anthropic-ai/sdk/helpers/beta/json-schema`
|
||||
|
||||
### Server tools with the tool runner
|
||||
|
||||
The runner's `tools` array accepts raw server-tool definitions (`web_search_20260209`, `web_fetch_20260209`, code execution) alongside runnable tools - pass the literal tool object; server tools run on Anthropic's servers, so there is no `run` function.
|
||||
The runner's `tools` array accepts raw server-tool definitions (`web_search_20260318`, `web_fetch_20260318`, code execution) alongside runnable tools - pass the literal tool object; server tools run on Anthropic's servers, so there is no `run` function.
|
||||
|
||||
**`pause_turn`:** a long-running server-tool turn can stop with `stop_reason: "pause_turn"`. From `@anthropic-ai/sdk` 0.121.0 the runner sends a paused turn back by itself so the server continues it. Earlier releases end the loop on a paused turn and return it as the final message, with no error; upgrade, or use the manual loop below, which handles `pause_turn` explicitly.
|
||||
|
||||
@@ -74,7 +74,7 @@ The runner's `tools` array accepts raw server-tool definitions (`web_search_2026
|
||||
const runner = client.beta.messages.toolRunner({
|
||||
model: "claude-opus-5-5",
|
||||
max_tokens: 16000,
|
||||
tools: [getWeather, { type: "web_search_20260209", name: "web_search", max_uses: 5 }],
|
||||
tools: [getWeather, { type: "web_search_20260318", name: "web_search", max_uses: 5 }],
|
||||
messages: [{ role: "user", content: "Compare this week's forecasts for Paris across two sources" }],
|
||||
});
|
||||
const finalMessage = await runner.runUntilDone(); // resumes paused turns itself (0.121.0 and later)
|
||||
@@ -82,11 +82,44 @@ const finalMessage = await runner.runUntilDone(); // resumes paused turns itself
|
||||
|
||||
Each resume counts toward `max_iterations`, so a capped run can still end paused - check `finalMessage.stop_reason` before trusting the result.
|
||||
|
||||
### Denying a tool call in the runner
|
||||
|
||||
For human approval, use the manual loop below. If you use the runner, it yields each assistant message before it runs that message's tools. To deny a call, push the assistant turn and a `tool_result` for every tool call in it: the runner sends those and never calls `run`. Pass `max_iterations` so a model that keeps retrying can't loop forever.
|
||||
|
||||
```typescript
|
||||
const runner = client.beta.messages.toolRunner({
|
||||
model: "claude-opus-5-5",
|
||||
max_tokens: 16000,
|
||||
max_iterations: 10,
|
||||
tools: [sendEmail],
|
||||
messages: [{ role: "user", content: "Email the report to the team" }],
|
||||
});
|
||||
|
||||
for await (const message of runner) {
|
||||
const calls = message.content.filter(
|
||||
(b): b is Anthropic.Beta.Messages.BetaToolUseBlock => b.type === "tool_use",
|
||||
);
|
||||
if (calls.length === 0 || userApproved(calls)) continue; // the runner runs the tools, or the loop ends
|
||||
runner.pushMessages(
|
||||
{ role: "assistant", content: message.content },
|
||||
{
|
||||
role: "user",
|
||||
content: calls.map((b) => ({
|
||||
type: "tool_result" as const,
|
||||
tool_use_id: b.id,
|
||||
content: "user declined",
|
||||
is_error: true,
|
||||
})),
|
||||
},
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Manual Agentic Loop
|
||||
|
||||
Prefer the tool runner above to a manual loop. Drop to a manual loop only when you need control the runner does not expose (e.g., a custom transport, request shapes the SDK cannot build, or avoiding a beta dependency - the runner is beta, and it supports per-token streaming via `stream: true`). Human-in-the-loop approval does *not* require a manual loop - gate inside the tool's `run()` function (return a "user declined" result) or inspect pending `tool_use` blocks and call `setMessagesParams()` between iterations.
|
||||
For human-in-the-loop approval, custom logging or conditional execution, use the manual loop. If you stay on the runner, put the approval check inside the tool's `run()` function (return a "user declined" result), or deny the call with `pushMessages()` (see Denying a tool call in the runner). For everything else, prefer the tool runner, and drop to a manual loop only when you need control the runner does not expose (e.g., a custom transport, request shapes the SDK cannot build, or avoiding a beta dependency - the runner is beta, and it supports per-token streaming via `stream: true`).
|
||||
|
||||
If you do need a manual loop:
|
||||
|
||||
@@ -105,9 +138,11 @@ while (true) {
|
||||
messages: messages,
|
||||
});
|
||||
|
||||
if (response.stop_reason === "end_turn") break;
|
||||
// Run tools only on tool_use: any other stop can cut a tool call off
|
||||
if (response.stop_reason !== "tool_use" && response.stop_reason !== "pause_turn") break;
|
||||
|
||||
// Server-side tool hit iteration limit; append assistant turn and re-send to continue
|
||||
// (once a response has a `container`, send its ID on every later request)
|
||||
if (response.stop_reason === "pause_turn") {
|
||||
messages.push({ role: "assistant", content: response.content });
|
||||
continue;
|
||||
@@ -316,7 +351,7 @@ const response = await client.messages.create({
|
||||
|
||||
Version-suffixed `type` literals; `name` is fixed per interface. Web search and code execution are server-executed; bash and text editor are client-executed (you handle the `tool_use` locally - see `shared/tool-use-concepts.md`). Pass plain object literals - the `ToolUnion` type is satisfied structurally. **The `name`/`type` pair must match the interface**: mixing `str_replace_based_edit_tool` (20250728 name) with `text_editor_20250124` (which expects `str_replace_editor`) is a TS2322.
|
||||
|
||||
**Don't type-annotate as `Tool[]`** - `Tool` is just the custom-tool variant. Let structural typing infer from the `tools` param, or annotate as `Anthropic.Messages.ToolUnion[]` if you must:
|
||||
**Don't type-annotate as `Tool[]`** - `Tool` is just the custom-tool variant. Let structural typing infer from the `tools` param, or annotate as `Anthropic.Messages.ToolUnion[]` if you must. A `tools` array hoisted into a `const` widens `type` and `name` to `string` and fails to compile (TS2769), so write `const tools: Anthropic.Messages.ToolUnion[] = [...]` there:
|
||||
|
||||
```typescript
|
||||
// Good: let inference work - no annotation
|
||||
@@ -326,7 +361,7 @@ const response = await client.messages.create({
|
||||
tools: [
|
||||
{ type: "text_editor_20250728", name: "str_replace_based_edit_tool" },
|
||||
{ type: "bash_20250124", name: "bash" },
|
||||
{ type: "web_search_20260209", name: "web_search" },
|
||||
{ type: "web_search_20260318", name: "web_search" },
|
||||
{ type: "code_execution_20260120", name: "code_execution" },
|
||||
],
|
||||
messages: [{ role: "user", content: "..." }],
|
||||
@@ -342,8 +377,8 @@ const response = await client.messages.create({
|
||||
| `ToolTextEditor20250429` | `str_replace_based_edit_tool` | `text_editor_20250429` |
|
||||
| `ToolTextEditor20250728` | `str_replace_based_edit_tool` | `text_editor_20250728` |
|
||||
| `ToolBash20250124` | `bash` | `bash_20250124` |
|
||||
| `WebSearchTool20260209` | `web_search` | `web_search_20260209` |
|
||||
| `WebFetchTool20260209` | `web_fetch` | `web_fetch_20260209` |
|
||||
| `WebSearchTool20260318` | `web_search` | `web_search_20260318` |
|
||||
| `WebFetchTool20260318` | `web_fetch` | `web_fetch_20260318` |
|
||||
| `CodeExecutionTool20260120` | `code_execution` | `code_execution_20260120` |
|
||||
|
||||
**Don't mix beta and non-beta types**: if you call `client.beta.messages.create()`, the response `content` is `BetaContentBlock[]` - you cannot pass that to a non-beta `ContentBlockParam[]` without narrowing each element.
|
||||
@@ -631,19 +666,18 @@ const response = await client.messages.create({
|
||||
|
||||
## Agent Skills
|
||||
|
||||
Enable an Anthropic-managed skill (e.g., `pptx`) via `container.skills` + the `code_execution` tool on the beta path. Both beta headers are required. Outputs land as files in the response content - download by file ID via the Files API.
|
||||
Enable an Anthropic-managed skill (e.g., `pptx`) via `container.skills` + the `code_execution` tool, with no beta header. Outputs land as files in the response content - download by file ID via the Files API.
|
||||
|
||||
```typescript
|
||||
const response = await client.beta.messages.create({
|
||||
const response = await client.messages.create({
|
||||
model: "claude-opus-5-5",
|
||||
max_tokens: 16000,
|
||||
container: {
|
||||
skills: [{ type: "anthropic", skill_id: "pptx", version: "latest" }],
|
||||
},
|
||||
tools: [{ type: "code_execution_20260521", name: "code_execution" }],
|
||||
betas: ["code-execution-2025-08-25"],
|
||||
messages: [{ role: "user", content: "Create a 3-slide deck about X." }],
|
||||
});
|
||||
// Find the file_id in response.content, then:
|
||||
// await client.beta.files.download(fileId)
|
||||
// await client.files.download(fileId)
|
||||
```
|
||||
|
||||
@@ -150,7 +150,7 @@ await client.beta.sessions.events.send(
|
||||
);
|
||||
```
|
||||
|
||||
> Tip: **Stream-first:** Open the stream *before* (or concurrently with) sending the message. The stream only delivers events that occur after it opens - stream-after-send means early events arrive buffered in one batch. See [Steering Patterns](../../shared/managed-agents-events.md#steering-patterns).
|
||||
> Tip: **Stream-first:** Open the stream *before* sending the message. The stream only delivers events that occur after it opens. See [Steering Patterns](../../shared/managed-agents-events.md#steering-patterns).
|
||||
|
||||
---
|
||||
|
||||
@@ -187,19 +187,11 @@ await client.beta.sessions.events.send(
|
||||
## Stream Events (SSE)
|
||||
|
||||
```typescript
|
||||
// Stream-first: open stream and send concurrently
|
||||
const [events] = await Promise.all([
|
||||
collectStream(session.id),
|
||||
client.beta.sessions.events.send(
|
||||
session.id,
|
||||
{ events: [{ type: "user.message", content: [{ type: "text", text: "..." }] }] },
|
||||
),
|
||||
]);
|
||||
|
||||
// Standalone stream iteration:
|
||||
const stream = await client.beta.sessions.events.stream(
|
||||
session.id,
|
||||
);
|
||||
// Stream-first: open stream, then send while stream is live
|
||||
const stream = await client.beta.sessions.events.stream(session.id);
|
||||
await client.beta.sessions.events.send(session.id, {
|
||||
events: [{ type: "user.message", content: [{ type: "text", text: "..." }] }],
|
||||
});
|
||||
|
||||
loop: for await (const event of stream) {
|
||||
switch (event.type) {
|
||||
@@ -375,7 +367,7 @@ for (const f of files.data) {
|
||||
// Download and save to disk
|
||||
const resp = await client.beta.files.download(f.id);
|
||||
const buffer = Buffer.from(await resp.arrayBuffer());
|
||||
fs.writeFileSync(f.filename, buffer);
|
||||
fs.writeFileSync(f.id, buffer); // not f.filename: the agent chose it, so it could be a path
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
Reference in New Issue
Block a user