One read of Claude Developer Platformapi-20261022T020713Z
168 pages moved out of 808 read.
Pages moved
168
significant first
Pages read
808
in this capture
Captured
02:07 UTC
Corpus hash
f3f082ef7981
index-hash
What this read moved
1-25 of 168, page 1 of 7This capture is too large to show at once. Changes 1-25 of 168 are below, significant first; the rest are on the following screens.
about-claude/models/optimizing-for-cost-and-intelligence Changed · +5 / -4 lines
from line 61
6161* Deep in a task, a well-built loop pays full price on under 1% of its input.
6262* Below about 80%, look for something breaking the cache (see [What breaks the cache](https://platform.claude.com/docs/en/about-claude/models/optimizing-for-cost-and-intelligence#what-breaks-the-cache)).
6363
64Across Anthropic's measured runs, cache reads are routinely the largest single component of task cost, making caching worth more than most model-choice decisions. Anthropic priced the DeepResearch Bench II[7](https://platform.claude.com/docs/en/about-claude/models/optimizing-for-cost-and-intelligence#refs) runs with and without caching:
64Anthropic priced the DeepResearch Bench II[7](https://platform.claude.com/docs/en/about-claude/models/optimizing-for-cost-and-intelligence#refs) runs with and without caching:
6565
6666<Frame>
6767 
from line 319
319319
320320* Each model generation responds to prompts differently, so a prompt accumulates text written for a model you no longer use.
321321* The usual case is over-specific instruction added to compensate for an older model: "verify twice," "be maximally thorough," a mandatory step-by-step procedure, or a hand-rolled reasoning scratchpad.
322* A newer model follows such instructions to the letter, producing extra tool rounds and extra writing, so the bill goes up with no gain in accuracy.
322* A newer model follows such instructions to the letter, producing extra tool rounds and extra writing that you pay for with no gain in accuracy.
323323
324324The audit is one command. The [Claude API skill](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/claude-api-skill) that ships with Claude Code has a `prompt-audit` command that reads a project's prompts and request code and reports what was written for a different model:
325325
from line 424
424424
425425### Upgrade the model
426426
427If you are a model or two behind, the cheapest lever is the model string. In Anthropic's measurements, each newer model solved at least as many tasks as the one before it, usually for less per solved task. The chart plots recent Claude models on the SWE-bench Pro[3](https://platform.claude.com/docs/en/about-claude/models/optimizing-for-cost-and-intelligence#refs) subset, where every model ran through the same test setup, and on Terminal-Bench 3[20](https://platform.claude.com/docs/en/about-claude/models/optimizing-for-cost-and-intelligence#refs); the table lists what each upgrade changed:
427If you are a model or two behind, the cheapest lever is the model string. In Anthropic's measurements, each newer model solved at least as many tasks as the one before it, usually for less per solved task. The chart plots recent Claude models on two benchmarks in which an agent works alone on one written task and tests check the result: the SWE-bench Pro[3](https://platform.claude.com/docs/en/about-claude/models/optimizing-for-cost-and-intelligence#refs) subset, where every model ran through the same test setup, and Terminal-Bench 3[20](https://platform.claude.com/docs/en/about-claude/models/optimizing-for-cost-and-intelligence#refs). The table lists what each upgrade changed:
428428
429429<Frame>
430430 
from line 444
444444
445445**When it pays.**
446446
447* The size of the saving depends on the work. From Claude Opus 5 to Claude Opus 5.5, it is 78% per solved task on the SWE-bench Pro subset and 40% on typical workloads ([Introducing Claude Opus 5.5](https://www.anthropic.com/news/claude-opus-5-5)). From Claude Sonnet 5 to Claude Sonnet 5.5, it is 87% on the same subset and up to 30% for most work ([Introducing Claude Sonnet 5.5](https://www.anthropic.com/news/claude-sonnet-5-5)).
447448* Where older models already solve most tasks, the cost of each attempt decides the saving: on the SWE-bench Pro subset, Claude Opus 5.5 scores about the same as Claude Opus 5 for 78% less per solved task.
448449* Where older models mostly fail, the pass rate decides the saving: on Terminal-Bench 3[20](https://platform.claude.com/docs/en/about-claude/models/optimizing-for-cost-and-intelligence#refs), the upgrade from Claude Opus 4.8 to Claude Opus 5 raises tasks solved from 15% to 41% and costs 56% less per solved task.
449450* Measure the upgrade on your own workload before assuming it saves. The saving is not guaranteed: on DeepResearch Bench II[7](https://platform.claude.com/docs/en/about-claude/models/optimizing-for-cost-and-intelligence#refs), Claude Fable 5.1 costs more per task than Claude Fable 5 because the new model does more work per task there, although the input and output prices are the same and the cache read is 4x cheaper.
from line 862
861862| Data files through code execution | 92% on a data task of 25 questions, with prompt caching off | A gain: 25 of 25 correct instead of 7 | Faster | [Trim input and context tokens](https://platform.claude.com/docs/en/about-claude/models/optimizing-for-cost-and-intelligence#trim-input-and-context-tokens) |
862863| Batch API | 50% | None | Results within 24 hours | [Batch work that can wait](https://platform.claude.com/docs/en/about-claude/models/optimizing-for-cost-and-intelligence#batch-work-that-can-wait) |
863864| Prompt audit against the current model | 14% on both model upgrades tested | None; a gain on one | Faster (fewer tool rounds) | [Audit prompts against the current model](https://platform.claude.com/docs/en/about-claude/models/optimizing-for-cost-and-intelligence#audit-prompts-against-the-current-model) |
864| Upgrade the model | Usually less per solved task: up to 87% less on a coding benchmark | None; a gain on most | Neutral | [Upgrade the model](https://platform.claude.com/docs/en/about-claude/models/optimizing-for-cost-and-intelligence#upgrade-the-model) |
865| Upgrade the model | Usually less: up to 40% less on typical workloads, and up to 87% less per solved task on a coding benchmark | None; a gain on most | Neutral | [Upgrade the model](https://platform.claude.com/docs/en/about-claude/models/optimizing-for-cost-and-intelligence#upgrade-the-model) |
865866| Lower effort | On long coding tasks, `medium` cost about 30% to 52% less than `high`, and `low` about two thirds less | Up to 15 points lower, depending on the task; none on one research agent | Faster | [Tune effort](https://platform.claude.com/docs/en/about-claude/models/optimizing-for-cost-and-intelligence#tune-effort) |
866867| Re-run failures | About 40% less than running everything at `high`, at the same pass rate or slightly better | None | A second attempt on the tasks that fail | [Re-run failures at higher effort](https://platform.claude.com/docs/en/about-claude/models/optimizing-for-cost-and-intelligence#re-run-failures-at-higher-effort) |
867868| Ask for shorter answers | About 13% less, from 39% fewer output tokens | None | Faster | [Set budgets and output caps](https://platform.claude.com/docs/en/about-claude/models/optimizing-for-cost-and-intelligence#set-budgets-and-output-caps) |
about-claude/pricing Changed · +48 / -48 lines
from line 84
8484
8585[Claude Platform on AWS](https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws) bills through AWS Marketplace using Claude Consumption Units (CCUs). Anthropic rates your token usage in USD at standard per-model, per-feature rates, applies any negotiated discount, converts the result to CCUs at $0.01 USD per CCU, and reports the CCU quantity to AWS Marketplace hourly. Your AWS bill shows a single CCU line item.
8686
87| Concept | Details |
88| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
89| **Billing unit** | Claude Consumption Unit (CCU) |
90| **CCU price** | $0.01 per CCU (fixed; discounts apply at token-to-CCU conversion, not to the CCU price) |
91| **Conversion** | Token usage rated in USD at standard per-model, per-feature rates (same as [Claude API pricing](https://platform.claude.com/docs/en/about-claude/pricing#model-pricing)), then converted to CCUs at $0.01 per CCU |
92| **Billing cadence** | Hourly metering to AWS Marketplace; monthly invoices |
93| **Payment model** | Arrears only (postpaid); no prepaid credits |
94| **Discounts** | Applied as fewer CCUs metered |
95| **Tax** | Pre-tax metering; AWS Marketplace handles tax |
96| **Cost visibility** | Real-time breakdown in the Claude Console (access through the AWS Console); AWS Cost Explorer shows aggregated CCU |
87| Concept | Details |
88| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
89| **Billing unit** | Claude Consumption Unit (CCU) |
90| **CCU price** | $0.01 USD per CCU (fixed; discounts apply at token-to-CCU conversion, not to the CCU price) |
91| **Conversion** | Token usage rated in USD at standard per-model, per-feature rates (same as [Claude API pricing](https://platform.claude.com/docs/en/about-claude/pricing#model-pricing)), then converted to CCUs at $0.01 USD per CCU |
92| **Billing cadence** | Hourly metering to AWS Marketplace; monthly invoices |
93| **Payment model** | Arrears only (postpaid); no prepaid credits |
94| **Discounts** | Applied as fewer CCUs metered |
95| **Tax** | Pre-tax metering; AWS Marketplace handles tax |
96| **Cost visibility** | Real-time breakdown in the Claude Console (access through the AWS Console); AWS Cost Explorer shows aggregated CCU |
9797
9898**CCU:** Claude Consumption Unit. A CCU is a unit of measure used solely for Marketplace Platform invoicing. If Customer accesses the Services through certain Marketplace Platforms (e.g., Claude Platform on AWS), usage will be invoiced in Claude Consumption Units ("CCU") rather than per MTok. One hundred (100) CCU represents $1.00 USD of fees owed for the Services, calculated at the applicable prices on [claude.com/pricing#api](https://claude.com/pricing#api), after application of any discounts.
9999
from line 113
113113
114114[Claude in Microsoft Foundry](https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry) bills through the Azure Marketplace using Claude Consumption Units (CCUs). Anthropic rates your token usage in USD at standard per-model, per-feature rates, applies any negotiated discount, converts the result to CCUs at $0.01 USD per CCU, and reports the CCU quantity to the Azure Marketplace hourly. Your Azure bill shows a single CCU line item.
115115
116| Concept | Details |
117| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
118| **Billing unit** | Claude Consumption Unit (CCU) |
119| **CCU price** | $0.01 per CCU (fixed; discounts apply at token-to-CCU conversion, not to the CCU price) |
120| **Conversion** | Token usage rated in USD at standard per-model, per-feature rates (same as [Claude API pricing](https://platform.claude.com/docs/en/about-claude/pricing#model-pricing)), then converted to CCUs at $0.01 per CCU |
121| **Billing cadence** | Hourly metering to the Azure Marketplace; monthly invoices |
122| **Payment model** | Arrears only (postpaid); no prepaid credits |
123| **Discounts** | Applied as fewer CCUs metered |
124| **Tax** | Pre-tax metering; Azure Marketplace handles tax |
125| **Cost visibility** | Azure Cost Management shows aggregated CCU |
116| Concept | Details |
117| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
118| **Billing unit** | Claude Consumption Unit (CCU) |
119| **CCU price** | $0.01 USD per CCU (fixed; discounts apply at token-to-CCU conversion, not to the CCU price) |
120| **Conversion** | Token usage rated in USD at standard per-model, per-feature rates (same as [Claude API pricing](https://platform.claude.com/docs/en/about-claude/pricing#model-pricing)), then converted to CCUs at $0.01 USD per CCU |
121| **Billing cadence** | Hourly metering to the Azure Marketplace; monthly invoices |
122| **Payment model** | Arrears only (postpaid); no prepaid credits |
123| **Discounts** | Applied as fewer CCUs metered |
124| **Tax** | Pre-tax metering; Azure Marketplace handles tax |
125| **Cost visibility** | Azure Cost Management shows aggregated CCU |
126126
127127**CCU:** Claude Consumption Unit. A CCU is a unit of measure used solely for Marketplace Platform invoicing. If Customer accesses the Services through certain Marketplace Platforms (e.g., Claude Platform on AWS, Claude in Microsoft Foundry), usage will be invoiced in Claude Consumption Units ("CCU") rather than per MTok. One hundred (100) CCU represents $1.00 USD of fees owed for the Services, calculated at the applicable prices on [claude.com/pricing#api](https://claude.com/pricing#api), after application of any discounts.
128128
from line 300
300300
301301Code execution usage is tracked in the response:
302302
303```json
303```text wrap
304304{
305305 "usage": {
306306 "input_tokens": 105,
from line 329
329329
330330Web search usage is charged in addition to token usage:
331331
332```json
332```text wrap
333333{
334334 "usage": {
335335 "input_tokens": 105,
from line 343
343343}
344344```
345345
346Web search is available on the Claude API for **$10 USD per 1,000 searches**, plus standard token costs for search-generated content. Web search results retrieved throughout a conversation are counted as input tokens, in search iterations executed during a single turn and in subsequent conversation turns.
346Web search is available on the Claude API for **$10 USD per 1,000 searches**, plus standard token costs for search-generated content. Web search results retrieved throughout a conversation are counted as input tokens, in search iterations run during a single turn and in subsequent conversation turns.
347347
348348Each web search counts as one use, regardless of the number of results returned. If an error occurs during web search, the web search will not be billed.
349349
from line 351
351351
352352Web fetch usage has **no additional charges** beyond standard token costs:
353353
354```json
354```text wrap
355355{
356356 "usage": {
357357 "input_tokens": 25039,
from line 416
416416
417417### Tokens
418418
419All tokens consumed by a Claude Managed Agents session are billed at the rates shown in [Model pricing](https://platform.claude.com/docs/en/about-claude/pricing#model-pricing). [Prompt caching](https://platform.claude.com/docs/en/about-claude/pricing#prompt-caching) multipliers apply identically. Web search triggered inside a session incurs the standard $10 USD per 1,000 searches. On [Claude Platform on AWS](https://platform.claude.com/docs/en/about-claude/pricing#claude-platform-on-aws-pricing), session token and runtime charges convert to Claude Consumption Units at the standard rate. [Fast mode](https://platform.claude.com/docs/en/about-claude/pricing#fast-mode-pricing) premium pricing applies when an agent's `model.speed` is set to `"fast"`.
419All tokens consumed by a Claude Managed Agents session are billed at the rates shown in [Model pricing](https://platform.claude.com/docs/en/about-claude/pricing#model-pricing). [Prompt caching multipliers](https://platform.claude.com/docs/en/about-claude/pricing#prompt-caching) apply identically. Web search triggered inside a session incurs the standard $10 USD per 1,000 searches. On Claude Platform on AWS, session token and runtime charges convert to Claude Consumption Units at the standard rate (see [Claude Platform on AWS pricing](https://platform.claude.com/docs/en/about-claude/pricing#claude-platform-on-aws-pricing)). [Fast mode premium pricing](https://platform.claude.com/docs/en/about-claude/pricing#fast-mode-pricing) applies when an agent's `model.speed` is set to `"fast"`.
420420
421421The [data residency multiplier](https://platform.claude.com/docs/en/about-claude/pricing#data-residency-pricing) also applies: when an agent's `model.inference_geo` is pinned to `"us"`, tokens consumed by sessions running that agent are billed at 1.1x the standard rates, the same multiplier that applies to US-only inference on the Messages API.
422422
from line 429
429429
430430### Session runtime
431431
432| SKU | Rate | Metering |
433| --------------- | ---------------------- | ------------------------- |
434| Session runtime | $0.08 per session-hour | `running` status duration |
432| SKU | Rate | Metering |
433| --------------- | -------------------------- | ------------------------- |
434| Session runtime | $0.08 USD per session-hour | `running` status duration |
435435
436436Runtime is measured to the millisecond and accrues only while the session's status is `running`. Time spent `idle` (waiting for your next message or a tool confirmation), `rescheduling`, or `terminated` does not count toward runtime.
437437
from line 443
443443
444444A 1-hour coding session using Claude Opus 5.5 that consumes 50,000 input tokens and 15,000 output tokens:
445445
446| Line item | Calculation | Cost |
447| --------------- | ------------------------ | --------- |
448| Input tokens | 50,000 × $4 / 1,000,000 | $0.20 |
449| Output tokens | 15,000 × $20 / 1,000,000 | $0.30 |
450| Session runtime | 1.0 hour × $0.08 | $0.08 |
451| **Total** | | **$0.58** |
446| Line item | Calculation | Cost |
447| --------------- | ------------------------ | ------------- |
448| Input tokens | 50,000 × $4 / 1,000,000 | $0.20 USD |
449| Output tokens | 15,000 × $20 / 1,000,000 | $0.30 USD |
450| Session runtime | 1.0 hour × $0.08 | $0.08 USD |
451| **Total** | | **$0.58 USD** |
452452
453453If prompt caching is active and 40,000 of the input tokens are cache reads:
454454
455| Line item | Calculation | Cost |
456| --------------------- | ------------------------------ | ---------- |
457| Uncached input tokens | 10,000 × $4 / 1,000,000 | $0.04 |
458| Cache read tokens | 40,000 × $4 × 0.05 / 1,000,000 | $0.008 |
459| Output tokens | 15,000 × $20 / 1,000,000 | $0.30 |
460| Session runtime | 1.0 hour × $0.08 | $0.08 |
461| **Total** | | **$0.428** |
455| Line item | Calculation | Cost |
456| --------------------- | ------------------------------ | -------------- |
457| Uncached input tokens | 10,000 × $4 / 1,000,000 | $0.04 USD |
458| Cache read tokens | 40,000 × $4 × 0.05 / 1,000,000 | $0.008 USD |
459| Output tokens | 15,000 × $20 / 1,000,000 | $0.30 USD |
460| Session runtime | 1.0 hour × $0.08 | $0.08 USD |
461| **Total** | | **$0.428 USD** |
462462
463463## Additional pricing considerations
464464
from line 491
491491
492492Volume discounts might be available for high-volume users. These are negotiated on a case-by-case basis.
493493
494* Standard usage tiers use the pricing shown in [Model pricing](https://platform.claude.com/docs/en/about-claude/pricing#model-pricing)
495* Enterprise customers can [contact sales](mailto:[email protected]) for custom pricing
496* Academic and research discounts might be available
494* Standard usage tiers use the pricing shown in [Model pricing](https://platform.claude.com/docs/en/about-claude/pricing#model-pricing).
495* Enterprise customers can [contact sales](mailto:[email protected]) for custom pricing.
496* Academic and research discounts might be available.
497497
498498### Enterprise pricing
499499
from line 508
508508
509509## Billing and payment
510510
511* Billing is based on actual monthly usage
512* All payments are in USD
513* Credit card and invoicing options available
514* Usage tracking available in the Claude Console at [platform.claude.com](https://platform.claude.com/)
511* Billing is based on actual monthly usage.
512* All payments are in USD.
513* Credit card and invoicing options are available.
514* Usage tracking is available in the Claude Console at [platform.claude.com](https://platform.claude.com/).
515515
516516## Frequently asked questions
517517
about-claude/use-case-guides/content-moderation Changed · +3 / -3 lines
from line 37
3737 Once a traditional ML approach has been established, changing it is a laborious and data-intensive undertaking. On the other hand, as your product or customer needs evolve, Claude can easily adapt to changes or additions to moderation policies without extensive relabeling of training data.
3838 </Accordion>
3939
40 <Accordion title="You require interpretable reasoning for your moderation decisions">
40 <Accordion title="You need interpretable reasoning for your moderation decisions">
4141 If you want to provide users or regulators with clear explanations behind moderation decisions, Claude can generate detailed and coherent justifications. This transparency is important for building trust and ensuring accountability in content moderation practices.
4242 </Accordion>
4343
from line 45
4545 Traditional ML approaches typically require separate models or extensive translation processes for each supported language. Human moderation requires hiring a workforce fluent in each supported language. Claude’s multilingual capabilities allow it to classify content in various languages without the need for separate models or extensive translation processes, streamlining moderation for global customer bases.
4646 </Accordion>
4747
48 <Accordion title="You require multimodal support">
48 <Accordion title="You need multimodal support">
4949 Claude's multimodal capabilities allow it to analyze and interpret content across both text and images. This makes it a versatile tool for comprehensive content moderation in environments where different media types need to be evaluated together.
5050 </Accordion>
5151</AccordionGroup>
from line 879
879879
880880Content moderation is a classification problem. Thus, you can use the same techniques outlined in the Claude Cookbook's [classification recipe](https://platform.claude.com/cookbook/capabilities-classification-guide) to determine the accuracy of your content moderation system.
881881
882One additional consideration is that instead of treating content moderation as a binary classification problem, you can instead create multiple categories to represent various risk levels. Creating multiple risk levels allows you to adjust the aggressiveness of your moderation. For example, you might want to automatically block user queries that are deemed high risk, whereas users with many medium risk queries are flagged for human review.
882One additional consideration is that instead of treating content moderation as a binary classification problem, you can create multiple categories to represent various risk levels. Creating multiple risk levels allows you to adjust the aggressiveness of your moderation. For example, you might want to automatically block user queries that are deemed high risk, whereas users with many medium risk queries are flagged for human review.
883883
884884<CodeGroup exclude="shell">
885885 ```python Python
about-claude/use-case-guides/customer-support-chat Changed · +4 / -4 lines
from line 187
187187
188188The choice of model depends on the trade-offs among cost, accuracy, and response time.
189189
190For customer support chat, Claude Opus 5.5 is well suited to balance intelligence, latency, and cost, including the most complex support scenarios that require deep reasoning across long, multistep conversations. However, for instances where you have conversation flow with multiple prompts including RAG, tool use, or long-context prompts, Claude Haiku 5.5 might be more suitable to optimize for latency. [Effort](https://platform.claude.com/docs/en/build-with-claude/effort) is its main control for speed: `low` is the fastest level, suited to chat and short tool tasks.
190For customer support chat, Claude Opus 5.5 is well suited to balance intelligence, latency, and cost, including the most complex support scenarios that require deep reasoning across long, multistep conversations. However, for instances where you have a conversation flow with multiple prompts including RAG, tool use, or long-context prompts, Claude Haiku 5.5 might be more suitable to optimize for latency. [Effort](https://platform.claude.com/docs/en/build-with-claude/effort) is its main control for speed: `low` is the fastest level, suited to chat and short tool tasks.
191191
192192### Build a strong prompt
193193
from line 349
349349"""
350350```
351351
352You will also want to include any important instructions outlining dos and don'ts for how Claude should interact with the customer. This might draw from brand guardrails or support policies.
352Also include any important instructions outlining dos and don'ts for how Claude should interact with the customer. This might draw from brand guardrails or support policies.
353353
354354```python
355355ADDITIONAL_GUARDRAILS = """Please adhere to the following guardrails:
from line 1075
10751075
10761076### Build your user interface
10771077
1078Test deploying this code with Streamlit using a main method. This `main()` function sets up a Streamlit-based chat interface. Streamlit is a Python framework, so this part of the walkthrough is shown in Python only; the ChatBot class shown earlier is the piece you can port to any language.
1078Test deploying this code with Streamlit using a main function. This `main()` function sets up a Streamlit-based chat interface. Streamlit is a Python framework, so this part of the walkthrough is shown in Python only; the ChatBot class shown earlier is the piece you can port to any language.
10791079
10801080Do this in a file called `app.py`:
10811081
from line 1152
11521152* [Reduce hallucination](https://platform.claude.com/docs/en/test-and-evaluate/strengthen-guardrails/reduce-hallucinations): Implement fact-checking mechanisms and [citations](https://platform.claude.com/cookbook/misc-using-citations) to ground responses in provided information.
11531153* Cross-check information: Verify that the agent's responses align with your company's policies and known facts.
11541154* Avoid contractual commitments: Ensure the agent doesn't make promises or enter into agreements it's not authorized to make.
1155* [Mitigate jailbreaks](https://platform.claude.com/docs/en/test-and-evaluate/strengthen-guardrails/mitigate-jailbreaks): Use methods such as harmlessness screens and input validation to prevent users from exploiting model vulnerabilities, aiming to generate inappropriate content.
1155* [Mitigate jailbreaks](https://platform.claude.com/docs/en/test-and-evaluate/strengthen-guardrails/mitigate-jailbreaks): Use methods such as harmlessness screens and input validation to prevent users from exploiting model vulnerabilities to generate inappropriate content.
11561156* Avoid mentioning competitors: Implement a competitor mention filter to maintain brand focus and not mention any competitor's products or services.
11571157* [Increase output consistency](https://platform.claude.com/docs/en/test-and-evaluate/strengthen-guardrails/increase-consistency): Prevent Claude from changing style or going out of character, even during long, complex interactions.
11581158* Remove personally identifiable information (PII): Unless explicitly required and authorized, strip out any PII from responses.
about-claude/use-case-guides/ticket-routing Changed · +5 / -5 lines
from line 28
2828 </Accordion>
2929
3030 <Accordion title="Your classification rules are based on semantic understanding">
31 Traditional ML approaches often rely on bag-of-words models or simple pattern matching. Claude excels at understanding and applying underlying rules when classes are defined by conditions rather than examples.
31 Traditional ML approaches often rely on bag-of-words models or simple pattern matching. Claude excels at applying underlying rules when classes are defined by conditions rather than examples.
3232 </Accordion>
3333
3434 <Accordion title="You need interpretable reasoning for classification decisions">
from line 203
203203 </Accordion>
204204
205205 <Accordion title="First-contact resolution rate">
206 This measures the percentage of tickets resolved during the first interaction with the customer. Higher rates indicate efficient routing and well-prepared support teams. Industry benchmarks typically range from 70–75 percent, with top performers achieving rates of 80 percent or higher.
206 This measures the percentage of tickets resolved during the first interaction with the customer. Higher rates indicate efficient routing and well-prepared support teams. Industry benchmarks typically range from 70 to 75 percent, with top performers achieving rates of 80 percent or higher.
207207 </Accordion>
208208
209209 <Accordion title="Average handling time">
from line 689
689689
690690It’s hard to know how well your prompt works without deploying it in a test production setting and [running evaluations](https://platform.claude.com/docs/en/test-and-evaluate/develop-tests).
691691
692Build the deployment structure. Start by defining the function signature for wrapping the call to Claude. Extend the function you started writing earlier, which takes `ticket_contents` (typescript, csharp, go, java: `ticketContents`; php: `$ticketContents`) as input, so that it now returns the reasoning and the intent as output. If you have an existing automation using traditional ML, you'll want to follow that method signature instead.
692Build the deployment structure. Start by defining the function signature for wrapping the call to Claude. Extend the function you started writing earlier, which takes `ticket_contents` (typescript, csharp, go, java: `ticketContents`; php: `$ticketContents`) as input, so that it now returns the reasoning and the intent as output. If you have an existing automation using traditional ML, you'll want to follow that signature instead.
693693
694694<CodeGroup exclude="shell">
695695 <CodeGroupItem language="cURL">
from line 1033
10331033* Accuracy
10341034* Cost per classification
10351035
1036You may need to assess Claude on other axes depending on which factors are important to you.
1036You might need to assess Claude on other axes depending on which factors are important to you.
10371037
10381038To assess this, first modify the script so that it compares the predicted intent with the actual intent. Then have it return the API call's token usage, from which you can calculate cost.
10391039
from line 1478
14781478 <Accordion title="Claude prioritizes emotion over intent">
14791479 When customers express dissatisfaction, Claude might prioritize addressing the emotion over solving the underlying problem.
14801480
1481 * **Solution:** Provide Claude with directions on when to prioritize customer sentiment or not. It can be something as simple as “Ignore all customer emotions. Focus only on analyzing the intent of the customer’s request and what information the customer might be asking for.”
1481 * **Solution:** Provide Claude with directions on when to prioritize customer sentiment or not. For example: “Ignore all customer emotions. Focus only on analyzing the intent of the customer’s request and what information the customer might be asking for.”
14821482 </Accordion>
14831483
14841484 <Accordion title="Multiple issues cause issue prioritization confusion">
agents-and-tools/agent-skills/best-practices Changed · +8 / -8 lines
from line 254
254254
255255**Practical guidance:**
256256
257* Keep `SKILL.md` body under 500 lines for optimal performance
258* Split content into separate files when approaching this limit
259* Use the following patterns to organize instructions, code, and resources effectively
257* Keep the `SKILL.md` body under 500 lines for optimal performance.
258* Split content into separate files when approaching this limit.
259* Use the following patterns to organize instructions, code, and resources effectively.
260260
261261#### Visual overview: From simple to complex
262262
from line 812
812812* **Testing with Claude B** (the agent using the Skill to perform real work)
813813* **Observing Claude B's behavior** and bringing insights back to Claude A
814814
8151. **Use the Skill in real workflows:** Give Claude B (with the Skill loaded) actual tasks, not test scenarios
8151. **Use the Skill in real workflows:** Give Claude B (with the Skill loaded) actual tasks, not test scenarios.
816816
8172. **Observe Claude B's behavior:** Note where it struggles, succeeds, or makes unexpected choices
8172. **Observe Claude B's behavior:** Note where it struggles, succeeds, or makes unexpected choices.
818818
819819 **Example observation:** "When I asked Claude B for a regional sales report, it wrote the query but forgot to filter out test accounts, even though the Skill mentions this rule."
820820
from line 822
822822
8238234. **Review Claude A's recommendations:** Claude A might recommend reorganizing to make rules more prominent, using stronger language such as "MUST filter" instead of "always filter," or restructuring the workflow section.
824824
8255. **Apply and test changes:** Update the Skill with Claude A's refinements, then test again with Claude B on similar requests
8255. **Apply and test changes:** Update the Skill with Claude A's refinements, then test again with Claude B on similar requests.
826826
8278276. **Repeat based on usage:** Continue this observe-refine-test cycle as you encounter new scenarios. Each iteration improves the Skill based on real agent behavior, not assumptions.
828828
from line 1137
11371137
11381138### Token budgets
11391139
1140Keep `SKILL.md` body under 500 lines for optimal performance. If your content exceeds this, split it into separate files using the progressive disclosure patterns described earlier. For architectural details, see [How Skills work](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview#how-skills-work).
1140Keep the `SKILL.md` body under 500 lines for optimal performance. If your content exceeds this, split it into separate files using the progressive disclosure patterns described earlier. For architectural details, see [How Skills work](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview#how-skills-work).
11411141
11421142## Checklist for effective Skills
11431143
agents-and-tools/mcp-connector Changed · +4 / -4 lines
from line 498
498498
499499### MCP tool use block
500500
501```json
501```text wrap
502502{
503503 "type": "mcp_tool_use",
504504 "id": "mcptoolu_014Q35RayjACSWkSj4X2yov1",
from line 510
510510
511511### MCP tool result block
512512
513```json
513```text wrap
514514{
515515 "type": "mcp_tool_result",
516516 "tool_use_id": "mcptoolu_014Q35RayjACSWkSj4X2yov1",
from line 530
530530
531531When the API asks an MCP server for its tools while producing a response, the response starts with an `mcp_tool_listing` block for that server, one block for each server it asked:
532532
533```json
533```text wrap
534534{
535535 "type": "mcp_tool_listing",
536536 "mcp_server_name": "example-mcp",
from line 1996
19961996
199719971. **New beta header:** Change from `mcp-client-2025-04-04` to `mcp-client-2025-11-20`.
199819982. **Tool configuration moved:** Tool configuration now lives in the `tools` array as MCPToolset objects, not in the MCP server definition.
19993. **More flexible configuration:** New pattern supports allowlisting, denylisting, and per-tool configuration.
19993. **More flexible configuration:** The new pattern supports allowlisting, denylisting, and per-tool configuration.
20002000
20012001### Migration steps
20022002
agents-and-tools/tool-use/advisor-tool Changed · +13 / -13 lines
from line 292
292292
293293The `caching` object has the shape `{"type": "ephemeral", "ttl": "5m" | "1h"}`. Unlike `cache_control` on content blocks, this is not a breakpoint marker. It is an on/off switch. The server determines where cache boundaries go.
294294
295The advisor tool also accepts the generic properties available on any tool definition: `cache_control`, `allowed_callers`, `defer_loading`, and `strict` (covered in [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)). See the [Tool reference](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference#tool-definition-properties) for their semantics.
295The advisor tool also accepts the generic properties available on any tool definition: `cache_control`, `allowed_callers`, `defer_loading`, and `strict` (covered in [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)). See [Tool definition properties](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference#tool-definition-properties) in the Tool reference for their semantics.
296296
297297## Response structure
298298
from line 300
300300
301301When the advisor is called, a `server_tool_use` block is followed by an `advisor_tool_result` block in the assistant's content. The following example shows the plaintext `advisor_result` variant returned by a Claude Opus 4.8 advisor. The [Quick start](https://platform.claude.com/docs/en/agents-and-tools/tool-use/advisor-tool#quick-start) uses Claude Opus 5.5, which returns the encrypted `advisor_redacted_result` variant instead; see [Result variants](https://platform.claude.com/docs/en/agents-and-tools/tool-use/advisor-tool#result-variants) for both shapes side by side.
302302
303```json
303```text
304304{
305305 "role": "assistant",
306306 "content": [
from line 349
349349
350350With `"model": "claude-opus-4-8"`, the advice is plaintext:
351351
352```json
352```text
353353{
354354 "type": "advisor_tool_result",
355355 "tool_use_id": "srvtoolu_abc123",
from line 362
362362
363363With `"model": "claude-opus-5-5"`, the advice is encrypted:
364364
365```json
365```text
366366{
367367 "type": "advisor_tool_result",
368368 "tool_use_id": "srvtoolu_abc123",
from line 383
383383
384384If the advisor call fails, the result carries an error:
385385
386```json
386```text wrap
387387{
388388 "type": "advisor_tool_result",
389389 "tool_use_id": "srvtoolu_abc123",
from line 1235
12351235
12361236Advisor calls run as a separate sub-inference billed at the advisor model's rates. Usage is reported in the `usage.iterations[]` array:
12371237
1238```json
1238```text wrap
12391239{
12401240 "usage": {
12411241 "input_tokens": 1760,
from line 1555
15551555
15561556The executor can search the web, call the advisor, and use your custom tools in the same turn. The advisor's plan can inform which tools the executor reaches for next.
15571557
1558| Feature | Interaction |
1559| ------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1560| [Batch processing](https://platform.claude.com/docs/en/build-with-claude/batch-processing) | Supported. `usage.iterations` is reported per item. |
1561| [Token counting](https://platform.claude.com/docs/en/build-with-claude/token-counting) | Returns the executor's first-iteration input tokens only. For a rough advisor estimate, call `client.beta.messages.count_tokens()` (typescript: `client.beta.messages.countTokens()`; go, csharp: `client.Beta.Messages.CountTokens()`; java: `client.beta().messages().countTokens()`; php: `$client->beta->messages->countTokens()`; cli: `ant beta:messages count-tokens`; curl: `POST /v1/messages/count_tokens`) with `model` set to the advisor model and the same messages. |
1562| [Context editing](https://platform.claude.com/docs/en/build-with-claude/context-editing) | `clear_tool_uses` is not fully compatible with advisor tool blocks. With `clear_thinking`, see the earlier caching warning. |
1563| `pause_turn` | A dangling advisor call ends the response with `stop_reason: "pause_turn"` and a `server_tool_use` block with no result when no client `tool_use` block is awaiting your result in the same turn. The advisor runs on resumption. If the executor also called one of your tools in that turn, the response ends with `stop_reason: "tool_use"` instead, and the pending advisor call runs at the start of your next request, after you send the `tool_result` blocks. See [Resuming a paused turn](https://platform.claude.com/docs/en/agents-and-tools/tool-use/advisor-tool#resuming-a-paused-turn), [Mixing server tools and client tools in one turn](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools#mixing-server-tools-and-client-tools-in-one-turn), and [Server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools#the-server-side-loop-and-pause-turn). |
1558| Feature | Interaction |
1559| ------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1560| [Batch processing](https://platform.claude.com/docs/en/build-with-claude/batch-processing) | Supported. `usage.iterations` is reported per item. |
1561| [Token counting](https://platform.claude.com/docs/en/build-with-claude/token-counting) | Returns the executor's first-iteration input tokens only. For a rough advisor estimate, call `client.beta.messages.count_tokens()` (typescript: `client.beta.messages.countTokens()`; go, csharp: `client.Beta.Messages.CountTokens()`; java: `client.beta().messages().countTokens()`; php: `$client->beta->messages->countTokens()`; cli: `ant beta:messages count-tokens`; curl: `POST /v1/messages/count_tokens`) with `model` set to the advisor model and the same messages. |
1562| [Context editing](https://platform.claude.com/docs/en/build-with-claude/context-editing) | `clear_tool_uses` is not fully compatible with advisor tool blocks. With `clear_thinking`, see the earlier caching warning. |
1563| `pause_turn` | A dangling advisor call ends the response with `stop_reason: "pause_turn"` and a `server_tool_use` block with no result when no client `tool_use` block is awaiting your result in the same turn. The advisor runs on resumption. If the executor also called one of your tools in that turn, the response ends with `stop_reason: "tool_use"` instead, and the pending advisor call runs at the start of your next request, after you send the `tool_result` blocks. See [Resuming a paused turn](https://platform.claude.com/docs/en/agents-and-tools/tool-use/advisor-tool#resuming-a-paused-turn), [Mixing server tools and client tools in one turn](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools#mixing-server-tools-and-client-tools-in-one-turn), and [The server-side loop and pause\_turn](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools#the-server-side-loop-and-pause-turn). |
15641564
15651565## Best practices
15661566
from line 1762
17621762
17631763When the advisor does hit the cap, the result block carries `stop_reason: "max_tokens"` on both [result variants](https://platform.claude.com/docs/en/agents-and-tools/tool-use/advisor-tool#result-variants), whichever advisor model you use. Use `stop_reason` to detect truncated advice and decide whether to raise the cap or let the executor proceed with partial guidance. The API also appends `[Advisor output truncated at max_tokens=2048.]` (naming your cap) to the advice text, so the executor receives the truncation notice in its own context; with a plaintext `advisor_result` advisor that marker is visible to your client as well. Both signals appear only when you set `max_tokens` on the tool definition.
17641764
1765```json
1765```text
17661766{
17671767 "type": "advisor_tool_result",
17681768 "tool_use_id": "srvtoolu_abc123",
agents-and-tools/tool-use/browser-use-sdk Changed · +5 / -5 lines
from line 20
2020
2121## Use a driver from a provider
2222
23With a driver from a provider, such as one under [Partner integrations](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#partner-integrations), you can build an agent in a few lines of code. The provider in this example is made up. Replace `example_browser_provider` (typescript: `example-browser-provider`) and `ExampleBrowser` with [a real provider's](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#partner-integrations) package and driver class, and set them up as the provider's docs describe.
23With a driver from a provider, such as one under [Partner integrations](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#partner-integrations), you can build an agent in a few lines of code. The provider in this example is made up. Replace `example_browser_provider` (typescript: `example-browser-provider`) and `ExampleBrowser` with a real provider's package and driver class, and set them up as the provider's docs describe.
2424
2525<CodeGroup exclude="shell:cURL, shell:CLI, csharp, go, java, php, ruby">
2626 ```python Python
from line 587
587587<Warning>
588588 Without a URL policy, the SDK checks no URL, and the API doesn't filter the URLs Claude opens. Even with a policy, a link Claude clicks or a redirect can take the browser to loopback (`localhost`, `127.0.0.1`), to link-local addresses such as the cloud metadata address `169.254.169.254`, and to private network ranges. [Egress rules on the container](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#put-egress-policy-on-the-container) can block the link-local and private addresses. Rules enforced outside the container can't block loopback.
589589
590 The SDK doesn't check a URL's scheme, so your driver must refuse every scheme it doesn't mean to open, such as `javascript:`, `view-source:`, `data:`, and `file:`. Most drivers need only `http` and `https`. The example policy later in this section allows only `http` and `https` URLs, plus `about:blank`.
590 The SDK doesn't check a URL's scheme, so your driver must refuse every scheme that you don't intend it to open, such as `javascript:`, `view-source:`, `data:`, and `file:`. Most drivers need only `http` and `https`. The example policy later in this section allows only `http` and `https` URLs, plus `about:blank`.
591591
592592 A `file:` URL lets Claude read files on the browser host. A `javascript:` URL runs script in the current page, even when `javascript_exec` is off. Egress rules don't stop either one.
593593</Warning>
from line 669
669669* Links Claude clicks, forms it submits, redirects, and the requests a page makes on its own. Only your driver sees them. See [Intercept requests in the driver](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#intercept-requests-in-the-driver).
670670* Hostnames and URLs that come from page content, which an attacker can choose.
671671* Parsing each URL the way the browser does, not finding the hostname with a plain string split.
672* URL schemes. The SDK doesn't check them, so refuse every scheme your driver doesn't mean to open.
672* URL schemes. The SDK doesn't check them, so refuse every scheme that you don't intend your driver to open.
673673* Egress rules on the container, for what no URL check can see. See [Put egress policy on the container](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#put-egress-policy-on-the-container).
674674
675675If you pass `url_policy=None` (typescript: `urlPolicy: null`), the SDK refuses every `navigate` to a URL, so a `None` (typescript: `null`) read from your configuration can't leave URLs unchecked by accident. In TypeScript, `undefined` leaves the option unset, the same as not passing it.
from line 914
914914* **Browser-only options:** The class has no [URL policy](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#write-a-url-policy), no [file policy](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#confine-uploads-and-downloads), and no [state report](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#report-browser-state).
915915* **`configs`:** Every tool you implement is on by default. The per-tool settings are listed under [Tool parameters](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#tool-parameters).
916916* **`confirm`:** If your class implements `type`, `key`, or `hold_key`, the constructor raises a configuration error unless you pass a `confirm` callable or turn those tools off with `configs`. A class that overrides `execute` counts as implementing all three.
917* **Skipped calls:** After a failed computer call, the tool runner answers the turn's later computer calls with `Not executed: an earlier computer action in this turn failed.` Browser calls get a different text. In a loop you write, answer the skipped computer calls with that exact text ([Batch actions](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#batch-actions)).
917* **Skipped calls:** After a failed computer call, the tool runner answers the turn's later computer calls with `Not executed: an earlier computer action in this turn failed.` Browser calls get a different text. In a loop you write, answer the skipped computer calls with that exact text ([Batch actions in the computer use tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#batch-actions)).
918918* **`execute`:** In TypeScript, an `execute` override types `name` as `BetaComputerMemberName` and `input` as `BetaComputerMemberInput`. Both come from `@anthropic-ai/sdk/resources/beta`.
919919* **Error text:** The SDK doesn't hide local paths in a computer tool's error text or in the text a tool returns. Claude reads both, cut at 4,096 characters. Catch exceptions in your tools, and raise `ToolError` (throw it in TypeScript) with your own text.
920920
from line 1191
119111914. Refuse input your desktop shouldn't honor, such as a point outside the screenshot, a `wait` of several minutes, or a very large `repeat` or `scroll_amount`. Raise `ToolError` (throw it in TypeScript) instead of moving the value into range.
119211925. Treat everything on the screen as untrusted, including window titles and clipboard text. Don't run it or pass it on unchecked.
11931193
1194The SDK applies step 2 through the callable you pass. The other steps are up to your driver and your deployment. The precautions under [Security considerations](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#security-considerations) apply as well.
1194The SDK applies step 2 through the callable you pass. The other steps are up to your driver and your deployment. The precautions under [Security considerations for the computer use tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#security-considerations) apply as well.
11951195
11961196The following `confirm` asks a person before any keyboard input, through your own `ask_user` (typescript: `askUser`) function, and approves every other call. `context.member` (typescript: `ctx.member`) is the tool's name. To have a person approve clicks too, set `ASK_FIRST` to `KEYBOARD | CLICKS` (typescript: `new Set([...KEYBOARD, ...CLICKS])`).
11971197
agents-and-tools/tool-use/browser-use-tool Changed · +3 / -3 lines
from line 205
205205
206206Claude's first response ends with `stop_reason: "tool_use"` and carries one or more member `tool_use` blocks, each naming a member tool in `name` and carrying `"toolset_name": "browser"`:
207207
208```json Output
208```text Output
209209{
210210 "id": "msg_01HCDu4XSTLzTAcodEQ58vDo",
211211 "type": "message",
from line 1054
10541054
10551055A turn with several member calls is a batch action: run the calls in the order they appear, stop at the first failure, and answer every later call with `is_error: true` and the exact text `Not executed: an earlier action in this turn failed.` A batch uses the same response shape as [parallel tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/parallel-tool-use); the difference is that you run the blocks in order rather than concurrently. Here Claude clicks the search box it found earlier, types a query, and presses Enter in one turn:
10561056
1057```json
1057```text wrap
10581058{
10591059 "role": "assistant",
10601060 "content": [
from line 1263
12631263* `paths` are file paths on the executor's filesystem, for deployments where the executor can read your application's files directly (the same condition under which you populate a download's `path`).
12641264* `document_ids` are identifiers for files your application has staged for the browser, for deployments where it can't. Your application defines what the identifiers mean; scope their resolution the way you scope `paths`, to files staged for this task.
12651265
1266```json
1266```text wrap
12671267{
12681268 "type": "tool_use",
12691269 "id": "toolu_01N7gVzFEfZjLjgsYwnrPgrF",
agents-and-tools/tool-use/build-a-tool-using-agent Changed · +8 / -8 lines
## Ring 5: The tool runner SDK abstraction ## Ring 5: The Tool Runner SDK abstraction
from line 4
44description: A guided walkthrough from a single tool call to a production-ready agentic loop.
55---
66
7This tutorial builds a calendar-management agent in five concentric rings. Each ring is a complete, runnable program that adds exactly one concept to the ring before it. By the end you will have written the agentic loop by hand and then replaced it with the Tool Runner SDK abstraction.
7This tutorial builds a calendar-management agent in five concentric rings. Each ring is a complete, runnable program that adds exactly one concept to the ring before it. By the end you will have written the agentic loop by hand and then replaced it with the tool runner SDK abstraction.
88
99The example tool is `create_calendar_event`. Its schema uses nested objects, arrays, and optional fields, so you will see how Claude handles realistic input shapes rather than a single flat string.
1010
from line 3311
33113311
33123312The `is_error` flag is the only difference from a successful result. Claude receives the flag and the error text, and responds accordingly. See [Handle tool calls](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls) for the full error-handling reference.
33133313
3314## Ring 5: The Tool Runner SDK abstraction
3314## Ring 5: The tool runner SDK abstraction
33153315
3316Rings 2 through 4 wrote the same loop by hand: call the API, check `stop_reason`, run tools, append results, repeat. The Tool Runner does this for you. Define each tool as a function, pass the list to `client.beta.messages.tool_runner()` (typescript: `client.beta.messages.toolRunner()`; java: `client.beta().messages().toolRunner()`; php: `$client->beta->messages->toolRunner()`; csharp: `client.Beta.Messages.ToolRunner()`; go: `client.Beta.Messages.NewToolRunner()`), and retrieve the final message once the loop completes. Error wrapping, result formatting, and conversation management are handled internally.
3316Rings 2 through 4 wrote the same loop by hand: call the API, check `stop_reason`, run tools, append results, repeat. The tool runner does this for you. Define each tool as a function, pass the list to `client.beta.messages.tool_runner()` (typescript: `client.beta.messages.toolRunner()`; java: `client.beta().messages().toolRunner()`; php: `$client->beta->messages->toolRunner()`; csharp: `client.Beta.Messages.ToolRunner()`; go: `client.Beta.Messages.NewToolRunner()`), and retrieve the final message once the loop completes. Error wrapping, result formatting, and conversation management are handled internally.
33173317
33183318The SDK provides a helper that turns an ordinary function into a runnable tool and derives the input schema from its signature; the following example shows the idiomatic form.
33193319
33203320<CodeGroup exclude="shell:cURL, shell:CLI">
33213321 <CodeGroupItem language="cURL">
3322 The Tool Runner is a helper in the [Claude SDK](https://platform.claude.com/docs/en/cli-sdks-libraries/overview). Raw HTTP requests have no equivalent.
3322 The tool runner is a helper in the [Claude SDK](https://platform.claude.com/docs/en/cli-sdks-libraries/overview). Raw HTTP requests have no equivalent.
33233323 </CodeGroupItem>
33243324
33253325 <CodeGroupItem language="CLI">
3326 The Tool Runner is a helper in the [Claude SDK](https://platform.claude.com/docs/en/cli-sdks-libraries/overview). The `ant` CLI has no equivalent.
3326 The tool runner is a helper in the [Claude SDK](https://platform.claude.com/docs/en/cli-sdks-libraries/overview). The `ant` CLI has no equivalent.
33273327 </CodeGroupItem>
33283328
33293329 ```python Python
from line 3935
39353935
39363936## What you built
39373937
3938You started with a single hardcoded tool call and ended with a production-shaped agent that handles multiple tools, parallel calls, and errors, then collapsed all of that into the Tool Runner. Along the way you saw every piece of the tool-use protocol: `tool_use` blocks, `tool_result` blocks, `tool_use_id` matching, `stop_reason` checking, and `is_error` signaling.
3938You started with a single hardcoded tool call and ended with a production-shaped agent that handles multiple tools, parallel calls, and errors, then collapsed all of that into the tool runner. Along the way you saw every piece of the tool-use protocol: `tool_use` blocks, `tool_result` blocks, `tool_use_id` matching, `stop_reason` checking, and `is_error` signaling.
39393939
39403940## Next steps
39413941
from line 3944
39443944 Schema specification and best practices.
39453945 </Card>
39463946
3947 <Card href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner" title="Tool Runner">
3947 <Card href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner" title="Tool runner">
39483948 The full SDK abstraction reference.
39493949 </Card>
39503950
agents-and-tools/tool-use/code-execution-tool Changed · +7 / -7 lines
from line 938
938938
939939### Bash command response
940940
941```json Output
941```text Output
942942{
943943 "type": "server_tool_use",
944944 "id": "srvtoolu_01B3C4D5E6F7G8H9I0J1K2L3",
from line 964
964964
965965**View file:**
966966
967```json Output
967```text Output wrap
968968{
969969 "type": "server_tool_use",
970970 "id": "srvtoolu_01C4D5E6F7G8H9I0J1K2L3M4",
from line 990
990990
991991**Create file:**
992992
993```json Output
993```text Output wrap
994994{
995995 "type": "server_tool_use",
996996 "id": "srvtoolu_01D5E6F7G8H9I0J1K2L3M4N5",
from line 1013
10131013
10141014**Edit file (str\_replace):**
10151015
1016```json Output
1016```text Output wrap
10171017{
10181018 "type": "server_tool_use",
10191019 "id": "srvtoolu_01E6F7G8H9I0J1K2L3M4N5O6",
from line 1060
10601060
10611061**Common errors (all tools):**
10621062
1063```json Output
1063```text Output wrap
10641064{
10651065 "type": "bash_code_execution_tool_result",
10661066 "tool_use_id": "srvtoolu_01VfmxgZ46TiHbmXgy928hQR",
from line 1443
14431443
14441444With [streaming](https://platform.claude.com/docs/en/build-with-claude/streaming) enabled (`"stream": true`), you'll receive code execution events as they occur. The sub-tool input streams as `input_json_delta` events, and each result block arrives whole in a single `content_block_start` event:
14451445
1446```sse
1446```text
14471447event: content_block_start
14481448data: {"type": "content_block_start", "index": 1, "content_block": {"type": "server_tool_use", "id": "srvtoolu_xyz789", "name": "bash_code_execution"}}
14491449
from line 1475
14751475
14761476Code execution usage is tracked in the response:
14771477
1478```json
1478```text wrap
14791479{
14801480 "usage": {
14811481 "input_tokens": 105,
agents-and-tools/tool-use/computer-use-tool Changed · +11 / -11 lines
from line 277
277277
278278When Claude acts on the desktop, the response has a `stop_reason` of `tool_use` and contains one or more member `tool_use` blocks, each naming a member tool and carrying `"toolset_name": "computer"`. Partway through this task, after Claude has received a screenshot of the desktop, a response might look like this:
279279
280```json Output
280```text Output wrap
281281{
282282 "id": "msg_01UZ3bXcQH8mTqNhVfL9eK2p",
283283 "type": "message",
from line 347
347347
348348A response with a three-action batch looks like this:
349349
350```json
350```text wrap
351351{
352352 "role": "assistant",
353353 "content": [
from line 437
437437
438438Computer use requires a sandboxed computing environment where Claude can safely interact with applications and the web. This environment includes:
439439
4401. **Virtual display:** A virtual X11 display server (using Xvfb) that renders the desktop interface Claude sees through screenshots and controls with mouse/keyboard actions.
4401. **Virtual display:** A virtual X11 display server (using Xvfb) that renders the desktop interface that Claude receives as screenshots and controls with mouse/keyboard actions.
441441
4424422. **Desktop environment:** A lightweight UI with window manager (Mutter) and panel (Tint2) running on Linux, which provides a consistent graphical interface for Claude to interact with.
443443
from line 706
706706### Optimize model performance with prompting
707707
7087081. Specify simple, well-defined tasks and provide explicit instructions for each step.
7092. Claude sometimes assumes outcomes of its actions without explicitly checking their results. To prevent this you can prompt Claude with `After each step, take a screenshot and carefully evaluate if you have achieved the right outcome. State in one sentence what the screenshot shows and whether the step succeeded. If it didn't, try again. Only when you confirm a step was executed correctly should you move on to the next one.`
7092. Claude sometimes acts as if its actions succeeded without explicitly checking their results. To prevent this, you can prompt Claude with `After each step, take a screenshot and carefully evaluate if you have achieved the right outcome. State in one sentence what the screenshot shows and whether the step succeeded. If it didn't, try again. Only when you confirm a step was executed correctly should you move on to the next one.`
7107103. Some UI elements (such as dropdowns and scrollbars) might be tricky for Claude to manipulate using mouse movements. If you experience this, try prompting the model to use keyboard shortcuts.
7117114. For repeatable tasks or UI interactions, include example screenshots and tool calls of successful outcomes in your prompt.
7127125. If you need the model to log in, provide it with the username and password in your prompt inside XML tags such as `<robot_credentials>`. Using computer use within applications that require login increases the risk of bad outcomes as a result of prompt injection. Review [Mitigate jailbreaks and prompt injections](https://platform.claude.com/docs/en/test-and-evaluate/strengthen-guardrails/mitigate-jailbreaks) before providing the model with login credentials.
from line 761
761761
762762 Shift+click at a position, for example, to extend a selection. Unlike `hold_key`, `text` holds the modifiers only for the duration of that click or scroll:
763763
764 ```json
764 ```text wrap
765765 {
766766 "type": "tool_use",
767767 "id": "toolu_01Qg8m3XqC5aRy7tD2eS4jUg",
from line 773
773773
774774 Drag from one point to another:
775775
776 ```json
776 ```text wrap
777777 {
778778 "type": "tool_use",
779779 "id": "toolu_01Ed6j9VnA3yPw5rB8cQ2gSe",
from line 788
788788
789789 Scroll down three clicks of the wheel:
790790
791 ```json
791 ```text wrap
792792 {
793793 "type": "tool_use",
794794 "id": "toolu_01Yc5h8UmZ2xNv4qA7bP9fRd",
from line 804
804804
805805 Press Tab four times:
806806
807 ```json
807 ```text wrap
808808 {
809809 "type": "tool_use",
810810 "id": "toolu_01Sb4g7TkY9wLu3pX6zM8eQc",
from line 816
816816
817817 Zoom in to inspect a region at full resolution:
818818
819 ```json
819 ```text wrap
820820 {
821821 "type": "tool_use",
822822 "id": "toolu_01Kf7k2WpB4zQx6sC9dR3hTf",
from line 828
828828
829829 Report the cursor position. Answer this call with a short text result that gives the position in screenshot pixels, for example, `X=512, Y=384`:
830830
831 ```json
831 ```text wrap
832832 {
833833 "type": "tool_use",
834834 "id": "toolu_01Ekh3vqB6yTs2mNc4Rw8pLd",
from line 1597
15971597Screenshots and zoom images that you return to the computer use toolset must already fit within your model's [image size limits](https://platform.claude.com/docs/en/build-with-claude/vision#evaluate-image-size): the toolset takes no display dimensions and the API doesn't downscale for you, so an oversized `tool_result` image is rejected with a validation error. Because Claude returns coordinates in the pixel space of the image it receives, keep the scale factor you used so you can map those coordinates back to your screen.
15981598
15991599<Note>
1600 Limits vary by model. Claude Opus 4.7 and later models, including every model that supports `computer_toolset_20260801`, accept up to 2576 pixels on the long edge and 4,784 visual tokens total (`⌈width / 28⌉ × ⌈height / 28⌉`, approximately 3.75 megapixels); earlier models accept up to 1568 pixels on the long edge and approximately 1.15 megapixels total (see [Resolution and token cost](https://platform.claude.com/docs/en/build-with-claude/vision#evaluate-image-size) for each model's tier). The following example uses the earlier-model 1568 px / 1.15 MP limits. For a high-resolution-tier model, size to the visual-token limit rather than a pixel total, for example with the resize helper in [Resize your image before uploading](https://platform.claude.com/docs/en/build-with-claude/vision-coordinates#resize-your-image-before-uploading).
1600 Limits vary by model. Claude Opus 4.7 and later models, including every model that supports `computer_toolset_20260801`, accept up to 2,576 pixels on the long edge and 4,784 visual tokens total (`⌈width / 28⌉ × ⌈height / 28⌉`, approximately 3.75 megapixels); earlier models accept up to 1,568 pixels on the long edge and approximately 1.15 megapixels total (see [Resolution and token cost](https://platform.claude.com/docs/en/build-with-claude/vision#evaluate-image-size) for each model's tier). The following example uses the earlier-model 1,568 px / 1.15 MP limits. For a high-resolution-tier model, size to the visual-token limit rather than a pixel total, for example with the resize helper in [Resize your image before uploading](https://platform.claude.com/docs/en/build-with-claude/vision-coordinates#resize-your-image-before-uploading).
16011601</Note>
16021602
16031603If your screen is larger than the limit, resize each screenshot before returning it and scale Claude's returned coordinates back to the original screen space. Because the toolset takes no display dimensions, the resize and the coordinate scaling in your application code are all you need:
agents-and-tools/tool-use/overview Changed · +3 / -3 lines
from line 627
627627The current weather in San Francisco is 15 degrees Celsius with partly cloudy skies.
628628```
629629
630[Handle tool calls](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls) covers each step in detail, including result formatting and error signaling; [Parallel tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/parallel-tool-use) covers responses that call several tools at once. To skip writing this round trip yourself, use [Tool Runner](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner): the SDK runs your tools and sends the results back automatically.
630[Handle tool calls](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls) covers each step in detail, including result formatting and error signaling; [Parallel tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/parallel-tool-use) covers responses that call several tools at once. To skip writing this round trip yourself, use the [tool runner](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner): the SDK runs your tools and sends the results back automatically.
631631
632632For the full conceptual model including the agentic loop and when to choose each approach, see [How tool use works](https://platform.claude.com/docs/en/agents-and-tools/tool-use/how-tool-use-works).
633633
from line 654
654654
655655 For example, given a `get_weather` tool that requires a `location` parameter, if you ask Claude "What's the weather?" without specifying a location, Claude (particularly Claude Sonnet) might guess values you didn't supply:
656656
657 ```json JSON
657 ```text JSON wrap
658658 {
659659 "type": "tool_use",
660660 "id": "toolu_01A09q90qw90lq917835lq9",
from line 791
791791
792792When you send a tool use prompt, like any other API request, the response includes both input and output token counts in the reported `usage` metrics.
793793
794Some server tools add usage-based charges on top of tokens: see [Web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool#usage-and-pricing) and [Code execution tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool#usage-and-pricing) for their rates.
794Some server tools add usage-based charges on top of tokens: see [Web search tool usage and pricing](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool#usage-and-pricing) and [Code execution tool usage and pricing](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool#usage-and-pricing) for their rates.
795795
796796## Next steps
797797
agents-and-tools/tool-use/programmatic-tool-calling Changed · +8 / -8 lines
from line 376
376376This approach is particularly useful for:
377377
378378* **Large data processing:** Filter or aggregate tool results before they reach Claude's context.
379* **Multistep workflows:** Save tokens and latency by calling tools serially or in a loop without sampling Claude in-between tool calls.
379* **Multistep workflows:** Save tokens and latency by calling tools serially or in a loop without sampling Claude between tool calls.
380380* **Conditional logic:** Make decisions based on intermediate tool results.
381381
382382<Note>
from line 422
422422
423423**Direct call (traditional tool use):**
424424
425```json
425```text wrap
426426{
427427 "type": "tool_use",
428428 "id": "toolu_abc123",
from line 434
434434
435435**Programmatic call:**
436436
437```json
437```text wrap
438438{
439439 "type": "tool_use",
440440 "id": "toolu_xyz789",
from line 480
480480
481481Claude writes code that calls your tool. The API pauses and returns:
482482
483```json Output
483```text Output
484484{
485485 "role": "assistant",
486486 "content": [
from line 1160
11601160
11611161Once the code execution completes, Claude provides the final response:
11621162
1163```json Output
1163```text Output
11641164{
11651165 "content": [
11661166 {
from line 1249
12491249
12501250When code execution calls a tool:
12511251
1252```json
1252```text wrap
12531253{
12541254 "type": "tool_use",
12551255 "id": "toolu_abc123",
from line 1283
12831283
12841284When all tool calls are satisfied and code completes:
12851285
1286```json
1286```text
12871287{
12881288 "type": "code_execution_tool_result",
12891289 "tool_use_id": "srvtoolu_xyz789",
from line 1310
13101310
13111311If your tool result doesn't arrive within about 4 minutes, the pending call raises a `TimeoutError` inside Claude's running code. Claude receives the error in `stderr` and typically retries the call:
13121312
1313```json
1313```text
13141314{
13151315 "type": "code_execution_tool_result",
13161316 "tool_use_id": "srvtoolu_abc123",
agents-and-tools/tool-use/server-tools Changed · +3 / -3 lines
from line 10
1010
1111The `server_tool_use` block appears in Claude's response when a server-executed tool runs. Its `id` field uses the `srvtoolu_` prefix to distinguish it from client tool calls:
1212
13```json
13```text wrap
1414{
1515 "type": "server_tool_use",
1616 "id": "srvtoolu_01A2B3C4D5E6F7G8H9",
from line 405
405405 With [programmatic tool calling](https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling), the same response shape means something different. The client `tool_use` block comes from code that is running in the `code_execution` tool rather than from Claude directly, and its `caller` field names the `code_execution` block that called it. That code has already started: it is paused waiting for your `tool_result` blocks, and sending them resumes the execution instead of starting a deferred tool. The `code_execution` block's own result block arrives once the code completes, which can take more than one round of tool results. The follow-up user message itself is the same in both cases; with programmatic tool calling, also pass back the `id` from the response's `container` field, as that page shows.
406406</Note>
407407
408```json
408```text wrap
409409{
410410 "stop_reason": "tool_use",
411411 "content": [
from line 446
446446
447447The API attaches your results to the still-open assistant turn, runs the deferred server tool (for paused code execution, resumes it), and then lets Claude continue. For a server tool Claude called directly, the next response starts with the result block that answers the previous response's `server_tool_use` `id`, followed by the newly generated content and a fresh `stop_reason`:
448448
449```json
449```text wrap
450450{
451451 "stop_reason": "end_turn",
452452 "content": [
agents-and-tools/tool-use/text-editor-tool Changed · +13 / -13 lines
from line 274
274274<Accordion title="Example view commands">
275275 Example for viewing a file:
276276
277 ```json
277 ```text wrap
278278 {
279279 "type": "tool_use",
280280 "id": "toolu_01A09q90qw90lq917835lq9",
from line 288
288288
289289 Example for viewing a directory:
290290
291 ```json
291 ```text wrap
292292 {
293293 "type": "tool_use",
294294 "id": "toolu_02B19r91rw91mr917835mr9",
from line 313
313313* `new_str`: The new text to insert in place of the old text
314314
315315<Accordion title="Example str_replace command">
316 ```json
316 ```text wrap
317317 {
318318 "type": "tool_use",
319319 "id": "toolu_01A09q90qw90lq917835lq9",
from line 339
339339* `file_text`: The content to write to the new file
340340
341341<Accordion title="Example create command">
342 ```json
342 ```text
343343 {
344344 "type": "tool_use",
345345 "id": "toolu_01A09q90qw90lq917835lq9",
from line 365
365365* `insert_text`: The text to insert
366366
367367<Accordion title="Example insert command">
368 ```json
368 ```text
369369 {
370370 "type": "tool_use",
371371 "id": "toolu_01A09q90qw90lq917835lq9",
from line 560
560560
561561Claude uses the text editor tool first to view the file:
562562
563```json Output
563```text Output
564564{
565565 "id": "msg_01XAbCDeFgHiJkLmNoPQrStU",
566566 "model": "claude-opus-5-5",
from line 1021
10211021
10221022Claude identifies the syntax error and uses the `str_replace` command to fix it:
10231023
1024```json Output
1024```text Output
10251025{
10261026 "id": "msg_01VwXyZAbCdEfGhIjKlMnO",
10271027 "model": "claude-opus-5-5",
from line 1461
14611461
14621462Finally, Claude provides a complete explanation of the fix:
14631463
1464````json Output
1464````text Output
14651465{
14661466 "id": "msg_01IjKlMnOpQrStUvWxYzAb",
14671467 "model": "claude-opus-5-5",
from line 2258
22582258
22592259Here are some ideas for how to use the text editor tool in more convenient and powerful ways:
22602260
2261* **Integrate with your development workflow:** Build the text editor tool into your development tools or IDE
2262* **Create a code review system:** Have Claude review your code and make improvements
2263* **Build a debugging assistant:** Create a system where Claude can help you diagnose and fix issues in your code
2264* **Implement file format conversion:** Let Claude help you convert files from one format to another
2265* **Automate documentation:** Set up workflows for Claude to automatically document your code
2261* **Integrate with your development workflow:** Build the text editor tool into your development tools or IDE.
2262* **Create a code review system:** Have Claude review your code and make improvements.
2263* **Build a debugging assistant:** Create a system where Claude can help you diagnose and fix issues in your code.
2264* **Implement file format conversion:** Let Claude help you convert files from one format to another.
2265* **Automate documentation:** Set up workflows for Claude to automatically document your code.
22662266
22672267The text editor tool allows Claude to work directly with your code base, supporting workflows from debugging to automated documentation.
22682268
agents-and-tools/tool-use/tool-search-tool Changed · +5 / -5 lines
from line 604
604604
605605When Claude uses the tool search tool, the response includes the following block types:
606606
607```json JSON
607```text JSON
608608{
609609 "role": "assistant",
610610 "content": [
from line 693
693693
694694**All tools deferred:**
695695
696```json
696```text
697697{
698698 "type": "error",
699699 "error": {
from line 705
705705
706706**Missing tool definition:**
707707
708```json
708```text wrap
709709{
710710 "type": "error",
711711 "error": {
from line 719
719719
720720When a tool search operation fails during execution, the API returns a 200 response with the error in the body:
721721
722```json JSON
722```text JSON
723723{
724724 "type": "tool_search_tool_result",
725725 "tool_use_id": "srvtoolu_01ABC123",
from line 793
793793
794794With streaming enabled, you'll receive tool search events as part of the stream:
795795
796```sse
796```text
797797event: content_block_start
798798data: {"type": "content_block_start", "index": 1, "content_block": {"type": "server_tool_use", "id": "srvtoolu_xyz789", "name": "tool_search_tool_regex"}}
799799
agents-and-tools/tool-use/web-fetch-tool Changed · +5 / -5 lines
from line 522
522522
523523Here's an example response structure:
524524
525```json Output
525```text Output
526526{
527527 "role": "assistant",
528528 "content": [
from line 606
606606
607607For PDF documents, content is returned as base64-encoded data:
608608
609```json Output
609```text Output wrap
610610{
611611 "type": "web_fetch_tool_result",
612612 "tool_use_id": "srvtoolu_02",
from line 631
631631
632632When the web fetch tool encounters an error, the Claude API returns a 200 (success) response with the error represented in the response body. Claude receives the error result and continues the turn. For example:
633633
634```json Output
634```text Output wrap
635635{
636636 "type": "web_fetch_tool_result",
637637 "tool_use_id": "srvtoolu_a93jad",
from line 958
958958
959959With streaming enabled, fetch events are part of the stream with a pause during content retrieval:
960960
961```sse Output
961```text Output
962962event: message_start
963963data: {"type": "message_start", "message": {"id": "msg_abc123", "type": "message"}}
964964
from line 991
991991
992992Web fetch usage has **no additional charges** beyond standard token costs:
993993
994```json
994```text wrap
995995{
996996 "usage": {
997997 "input_tokens": 25039,
agents-and-tools/tool-use/web-search-tool Changed · +7 / -7 lines
from line 459
459459* `type`: The type of location (must be `approximate`)
460460* `city`: The city name
461461* `region`: The region or state
462* `country`: The two-letter [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code. The API rejects unsupported country codes with a 400 error.
463* `timezone`: The [IANA time zone ID](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones).
462* `country`: The two-letter [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code (the API rejects an unsupported code with a 400 error)
463* `timezone`: The [IANA time zone ID](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones)
464464
465465On Claude Managed Agents, the `web_search` entry of the agent toolset accepts a `user_location` object with the same fields. The API rejects an unsupported `country` code with a 400 error when you create or update the agent, or when you create or update a session that supplies the setting. See the [web tool settings](https://platform.claude.com/docs/en/managed-agents/tools-web-restrictions#settings).
466466
from line 488
488488
489489Here's an example response structure:
490490
491```json Output
491```text Output
492492{
493493 "role": "assistant",
494494 "content": [
from line 583
583583
584584When the web search tool encounters an error (such as hitting rate limits), the Claude API still returns a 200 (success) response. The error is represented within the response body using the following structure:
585585
586```json Output
586```text Output wrap
587587{
588588 "type": "web_search_tool_result",
589589 "tool_use_id": "srvtoolu_a93jad",
from line 621
621621
622622With streaming enabled, you'll receive search events as part of the stream. There is a pause while the search runs:
623623
624```sse Output
624```text Output
625625event: message_start
626626data: {"type": "message_start", "message": {"id": "msg_abc123", "type": "message"}}
627627
from line 656
656656
657657Web search usage is charged in addition to token usage:
658658
659```json
659```text wrap
660660{
661661 "usage": {
662662 "input_tokens": 105,
from line 670
670670}
671671```
672672
673Web search is available on the Claude API for **$10 USD per 1,000 searches**, plus standard token costs for search-generated content. Web search results retrieved throughout a conversation are counted as input tokens, in search iterations executed during a single turn and in subsequent conversation turns.
673Web search is available on the Claude API for **$10 USD per 1,000 searches**, plus standard token costs for search-generated content. Web search results retrieved throughout a conversation are counted as input tokens, in search iterations run during a single turn and in subsequent conversation turns.
674674
675675Each web search counts as one use, regardless of the number of results returned. If an error occurs during web search, the web search will not be billed.
676676
api/errors Changed · +3 / -3 lines
from line 57
5757
5858The API always returns errors as JSON, with a top-level `error` object that always includes a `type` and `message` value. The response also includes a `request_id` field for easier tracking and debugging. For example:
5959
60```json JSON
60```text JSON wrap
6161{
6262 "type": "error",
6363 "error": {
from line 422
422422 ```
423423</CodeGroup>
424424
425See [Streaming messages](https://platform.claude.com/docs/en/build-with-claude/streaming#get-the-final-message-without-handling-events) for more details.
425See [Get the final message without handling events](https://platform.claude.com/docs/en/build-with-claude/streaming#get-the-final-message-without-handling-events) for more details.
426426
427427## Common validation errors
428428
from line 430
430430
431431Claude 4.6 and later models and [Claude Mythos Preview](https://anthropic.com/glasswing) do not support prefilling assistant messages. Sending a request with a prefilled last assistant message to any of these models returns a 400 `invalid_request_error`:
432432
433```json
433```text
434434{
435435 "type": "error",
436436 "error": {
build-with-claude/batch-processing Changed · +4 / -4 lines
from line 421
421421
422422When a batch is first created, the response has a processing status of `in_progress`.
423423
424```json Output
424```text Output wrap
425425{
426426 "id": "msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d",
427427 "type": "message_batch",
from line 917
917917
918918The results are in `.jsonl` format, where each line is a valid JSON object representing the result of a single request in the Message Batch. For each streamed result, you can do something different depending on its `custom_id` and result type. Here is an example set of results:
919919
920```jsonl .jsonl file
920```text .jsonl file
921921{"custom_id":"my-second-request","result":{"type":"succeeded","message":{"id":"msg_014VwiXbi91y3JMjcpyGBHX5","type":"message","role":"assistant","model":"claude-opus-5-5","content":[{"type":"text","text":"Hello again! It's nice to see you. How can I assist you today? Is there anything specific you'd like to chat about or any questions you have?"}],"stop_reason":"end_turn","stop_sequence":null,"usage":{"input_tokens":11,"output_tokens":36}}}}
922922{"custom_id":"my-first-request","result":{"type":"succeeded","message":{"id":"msg_01FqfsLoHwgeFbguDgpz48m7","type":"message","role":"assistant","model":"claude-opus-5-5","content":[{"type":"text","text":"Hello! How can I assist you today? Feel free to ask me any questions or let me know if there's anything you'd like to chat about."}],"stop_reason":"end_turn","stop_sequence":null,"usage":{"input_tokens":10,"output_tokens":34}}}}
923923```
from line 1016
10161016
10171017The response shows the batch in a `canceling` state:
10181018
1019```json Output
1019```text Output wrap
10201020{
10211021 "id": "msgbatch_013Zva2CMHLNnXjNJJKqJ2EF",
10221022 "type": "message_batch",
from line 1837
18371837 </Accordion>
18381838
18391839 <Accordion title="Can I update a batch after it's been submitted?">
1840 No, once a batch has been submitted, it cannot be modified. If you need to make changes, you should cancel the current batch and submit a new one. Note that cancellation might not take immediate effect.
1840 No, once a batch has been submitted, it cannot be modified. If you need to make changes, cancel the current batch and submit a new one. Note that cancellation might not take immediate effect.
18411841 </Accordion>
18421842
18431843 <Accordion title="Are there Message Batches API rate limits and do they interact with the Messages API rate limits?">
build-with-claude/citations Changed · +6 / -6 lines
from line 374
374374### Token costs
375375
376376* Enabling citations incurs a slight increase in input tokens because of system prompt additions and document chunking.
377* However, the citations feature is very efficient with output tokens. Internally, the model outputs citations in a standardized format that are then parsed into cited text and document location indices. The `cited_text` field is provided for convenience and does not count toward output tokens.
377* However, the citations feature is very efficient with output tokens. Internally, the model outputs citations in a standardized format, and those citations are then parsed into cited text and document location indices. The `cited_text` field is provided for convenience and does not count toward output tokens.
378378* When passed back in subsequent conversation turns, `cited_text` is also not counted toward input tokens.
379379
380380### Feature compatibility
from line 974
974974</Tabs>
975975
976976<Accordion title="Example plain text citation">
977 ```json
977 ```text
978978 {
979979 "type": "char_location",
980980 "cited_text": "The exact text being cited", // not counted toward output tokens
from line 1790
17901790</Tabs>
17911791
17921792<Accordion title="Example PDF citation">
1793 ```json
1793 ```text
17941794 {
17951795 "type": "page_location",
17961796 "cited_text": "The exact text being cited", // not counted toward output tokens
from line 2109
21092109</CodeGroup>
21102110
21112111<Accordion title="Example citation">
2112 ```json
2112 ```text
21132113 {
21142114 "type": "content_block_location",
21152115 "cited_text": "The exact text being cited", // not counted toward output tokens
from line 2127
21272127
21282128When citations are enabled, responses include multiple text blocks with citations:
21292129
2130```json
2130```text wrap
21312131{
21322132 "content": [
21332133 { "type": "text", "text": "According to the document, " },
from line 2206
22062206
22072207<AccordionGroup>
22082208 <Accordion title="Example streaming events">
2209 ```sse
2209 ```text
22102210 event: message_start
22112211 data: {"type": "message_start", ...}
22122212
build-with-claude/claude-on-amazon-bedrock-legacy Changed · +3 / -3 lines
from line 796
796796**Regional endpoints (CRIS):**
797797
798798* Route traffic through specific geographic regions
799* Required for data residency and compliance requirements
800* Available for US, EU, Japan, and Asia-Pacific
801* 10 percent pricing premium reflects infrastructure costs for dedicated regional capacity
799* Are required for data residency and compliance requirements
800* Are available for US, EU, Japan, and Asia-Pacific
801* Carry a 10 percent pricing premium that reflects infrastructure costs for dedicated regional capacity
802802
803803### Implementation
804804
build-with-claude/claude-on-vertex-ai Changed · +5 / -5 lines
from line 419
419419**Multi-region endpoints:**
420420
421421* Dynamically route requests across regions within a geographic area (currently `us` and `eu`)
422* Useful when you need data residency within a broad geography but want higher availability than a single region
423* 10 percent pricing premium over global endpoints
424* Only supports pay-as-you-go traffic (provisioned throughput requires regional endpoints)
422* Are useful when you need data residency within a broad geography but want higher availability than a single region
423* Carry a 10 percent pricing premium over global endpoints
424* Only support pay-as-you-go traffic (provisioned throughput requires regional endpoints)
425425
426426**Regional endpoints:**
427427
428428* Route traffic through specific geographic regions
429* Required for single-region data residency, strict compliance mandates, or provisioned throughput
429* Are required for single-region data residency, strict compliance mandates, or provisioned throughput
430430* Support both pay-as-you-go and provisioned throughput
431* 10 percent pricing premium reflects infrastructure costs for dedicated regional capacity
431* Carry a 10 percent pricing premium that reflects infrastructure costs for dedicated regional capacity
432432
433433### Implementation
434434