fix(deps): update dependency @anthropic-ai/sdk to v0.51.0
This PR contains the following updates:
| Package | Change | Age | Adoption | Passing | Confidence |
|---|---|---|---|---|---|
| @anthropic-ai/sdk | 0.40.1 -> 0.51.0 |
Release Notes
anthropics/anthropic-sdk-typescript (@βanthropic-ai/sdk)
v0.51.0
Full Changelog: sdk-v0.50.4...sdk-v0.51.0
Features
- bedrock: support skipAuth on Bedrock client to bypass local auth requirements (b661c5f)
Bug Fixes
- bedrock: support model names with slashes (cb5fa8a)
Chores
- package: remove engines (f0378ec)
v0.50.4
Full Changelog: sdk-v0.50.3...sdk-v0.50.4
Bug Fixes
- stream: correctly accumulate usage (c55b4f0)
v0.50.3
Full Changelog: sdk-v0.50.2...sdk-v0.50.3
Bug Fixes
- client: always overwrite when merging headers (657912a)
- client: always overwrite when merging headers (bf70c9f)
v0.50.2
Full Changelog: sdk-v0.50.1...sdk-v0.50.2
Bug Fixes
- ci: bump publish workflow to node 20 (306a081)
Chores
Documentation
- update readme (ef0c60a)
v0.50.1
Full Changelog: sdk-v0.50.0...sdk-v0.50.1
v0.41.0
Full Changelog: sdk-v0.40.1...sdk-v0.41.0
Features
- api: adds web search capabilities to the Claude API (fae7e52)
Chores
- ci: bump node version for release workflows (3502747)
Documentation
Configuration
π Schedule: Branch creation - Tuesday through Thursday ( * * * * 2-4 ) (UTC), Automerge - At any time (no schedule defined).
π¦ Automerge: Disabled by config. Please merge this manually once you are satisfied.
β» Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.
π Ignore: Close this PR and you won't be reminded about this update again.
- [ ] If you want to rebase/retry this PR, check this box
This PR was generated by Mend Renovate. View the repository job log.
openai debug - [puLL-Merge] - anthropics/[email protected]
Diff
diff --git .github/workflows/ci.yml .github/workflows/ci.yml
index f2f42e06..a021391c 100644
--- .github/workflows/ci.yml
+++ .github/workflows/ci.yml
@@ -72,7 +72,7 @@ jobs:
- name: Set up Node
uses: actions/setup-node@v4
with:
- node-version: '18'
+ node-version: '20'
- name: Bootstrap
run: ./scripts/bootstrap
diff --git .github/workflows/publish-npm.yml .github/workflows/publish-npm.yml
index b18decdf..7be59d8e 100644
--- .github/workflows/publish-npm.yml
+++ .github/workflows/publish-npm.yml
@@ -20,7 +20,7 @@ jobs:
- name: Set up Node
uses: actions/setup-node@v4
with:
- node-version: '18'
+ node-version: '20'
- name: Install dependencies
run: |
diff --git .release-please-manifest.json .release-please-manifest.json
index d2fc4414..5ee5f3b3 100644
--- .release-please-manifest.json
+++ .release-please-manifest.json
@@ -1,5 +1,5 @@
{
- ".": "0.40.1",
+ ".": "0.41.0",
"packages/vertex-sdk": "0.7.0",
"packages/bedrock-sdk": "0.12.6"
}
diff --git .stats.yml .stats.yml
index 30b9556d..5aa47f53 100644
--- .stats.yml
+++ .stats.yml
@@ -1,4 +1,4 @@
configured_endpoints: 21
-openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/anthropic%2Fanthropic-ea0576fceb17a0976feca9aa03aa426984d6fe1390f2bcdbf9de0212a81c8334.yml
-openapi_spec_hash: d2d7ec2a7a35a1ed2443c3b690c802c4
-config_hash: 9d5b992847099d8fe5a5c09e66adbe5f
+openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/anthropic%2Fanthropic-7015ea2d98991d6c2e7931c521e36448778fe868cc1b8a21173898d67b14b819.yml
+openapi_spec_hash: 2007ff815a3f39af8cebe1976d50f17d
+config_hash: 4d0dcf47d77eae22d34624d2ac0f0b46
diff --git CHANGELOG.md CHANGELOG.md
index 85f0e40f..53bbc93d 100644
--- CHANGELOG.md
+++ CHANGELOG.md
@@ -1,5 +1,24 @@
# Changelog
+## 0.41.0 (2025-05-07)
+
+Full Changelog: [sdk-v0.40.1...sdk-v0.41.0](https://github.com/anthropics/anthropic-sdk-typescript/compare/sdk-v0.40.1...sdk-v0.41.0)
+
+### Features
+
+* **api:** adds web search capabilities to the Claude API ([fae7e52](https://github.com/anthropics/anthropic-sdk-typescript/commit/fae7e521568d9659e376d13c4e4a6c320b13b1d4))
+
+
+### Chores
+
+* **ci:** bump node version for release workflows ([3502747](https://github.com/anthropics/anthropic-sdk-typescript/commit/350274792ed3d9b7ea237ee60876883373344016))
+
+
+### Documentation
+
+* add examples to tsdocs ([19a9285](https://github.com/anthropics/anthropic-sdk-typescript/commit/19a928512b1616f2cac9c82f02e7bd9a158dab95))
+* **readme:** fix typo ([735574e](https://github.com/anthropics/anthropic-sdk-typescript/commit/735574e23b7956cbfd0c05d0374079391d5d4e96))
+
## 0.40.1 (2025-04-28)
Full Changelog: [sdk-v0.40.0...sdk-v0.40.1](https://github.com/anthropics/anthropic-sdk-typescript/compare/sdk-v0.40.0...sdk-v0.40.1)
diff --git README.md README.md
index cafba323..9e6e15bb 100644
--- README.md
+++ README.md
@@ -183,9 +183,9 @@ for await (const entry of results) {
}
```
-## Tool use beta
+## Tool use
-This SDK provides beta support for tool use, aka function calling. More details can be found in [the documentation](https://docs.anthropic.com/claude/docs/tool-use).
+This SDK provides support for tool use, aka function calling. More details can be found in [the documentation](https://docs.anthropic.com/claude/docs/tool-use).
## AWS Bedrock
@@ -220,7 +220,7 @@ async function main() {
main();
```
-Error codes are as followed:
+Error codes are as follows:
| Status Code | Error Type |
| ----------- | -------------------------- |
diff --git api.md api.md
index 2010bc5f..78a2bac0 100644
--- api.md
+++ api.md
@@ -29,8 +29,10 @@ Types:
- <code><a href="./src/resources/messages/messages.ts">CitationContentBlockLocationParam</a></code>
- <code><a href="./src/resources/messages/messages.ts">CitationPageLocation</a></code>
- <code><a href="./src/resources/messages/messages.ts">CitationPageLocationParam</a></code>
+- <code><a href="./src/resources/messages/messages.ts">CitationWebSearchResultLocationParam</a></code>
- <code><a href="./src/resources/messages/messages.ts">CitationsConfigParam</a></code>
- <code><a href="./src/resources/messages/messages.ts">CitationsDelta</a></code>
+- <code><a href="./src/resources/messages/messages.ts">CitationsWebSearchResultLocation</a></code>
- <code><a href="./src/resources/messages/messages.ts">ContentBlock</a></code>
- <code><a href="./src/resources/messages/messages.ts">ContentBlockParam</a></code>
- <code><a href="./src/resources/messages/messages.ts">ContentBlockSource</a></code>
@@ -56,6 +58,9 @@ Types:
- <code><a href="./src/resources/messages/messages.ts">RawMessageStreamEvent</a></code>
- <code><a href="./src/resources/messages/messages.ts">RedactedThinkingBlock</a></code>
- <code><a href="./src/resources/messages/messages.ts">RedactedThinkingBlockParam</a></code>
+- <code><a href="./src/resources/messages/messages.ts">ServerToolUsage</a></code>
+- <code><a href="./src/resources/messages/messages.ts">ServerToolUseBlock</a></code>
+- <code><a href="./src/resources/messages/messages.ts">ServerToolUseBlockParam</a></code>
- <code><a href="./src/resources/messages/messages.ts">SignatureDelta</a></code>
- <code><a href="./src/resources/messages/messages.ts">StopReason</a></code>
- <code><a href="./src/resources/messages/messages.ts">TextBlock</a></code>
@@ -84,6 +89,15 @@ Types:
- <code><a href="./src/resources/messages/messages.ts">URLImageSource</a></code>
- <code><a href="./src/resources/messages/messages.ts">URLPDFSource</a></code>
- <code><a href="./src/resources/messages/messages.ts">Usage</a></code>
+- <code><a href="./src/resources/messages/messages.ts">WebSearchResultBlock</a></code>
+- <code><a href="./src/resources/messages/messages.ts">WebSearchResultBlockParam</a></code>
+- <code><a href="./src/resources/messages/messages.ts">WebSearchTool20250305</a></code>
+- <code><a href="./src/resources/messages/messages.ts">WebSearchToolRequestError</a></code>
+- <code><a href="./src/resources/messages/messages.ts">WebSearchToolResultBlock</a></code>
+- <code><a href="./src/resources/messages/messages.ts">WebSearchToolResultBlockContent</a></code>
+- <code><a href="./src/resources/messages/messages.ts">WebSearchToolResultBlockParam</a></code>
+- <code><a href="./src/resources/messages/messages.ts">WebSearchToolResultBlockParamContent</a></code>
+- <code><a href="./src/resources/messages/messages.ts">WebSearchToolResultError</a></code>
- <code><a href="./src/resources/messages/messages.ts">MessageStreamEvent</a></code>
- <code><a href="./src/resources/messages/messages.ts">MessageStartEvent</a></code>
- <code><a href="./src/resources/messages/messages.ts">MessageDeltaEvent</a></code>
@@ -129,7 +143,7 @@ Types:
Methods:
-- <code title="get /v1/models/{model_id}">client.models.<a href="./src/resources/models.ts">retrieve</a>(modelId) -> ModelInfo</code>
+- <code title="get /v1/models/{model_id}">client.models.<a href="./src/resources/models.ts">retrieve</a>(modelId, { ...params }) -> ModelInfo</code>
- <code title="get /v1/models">client.models.<a href="./src/resources/models.ts">list</a>({ ...params }) -> ModelInfosPage</code>
# Beta
@@ -157,7 +171,7 @@ Types:
Methods:
-- <code title="get /v1/models/{model_id}?beta=true">client.beta.models.<a href="./src/resources/beta/models.ts">retrieve</a>(modelId) -> BetaModelInfo</code>
+- <code title="get /v1/models/{model_id}?beta=true">client.beta.models.<a href="./src/resources/beta/models.ts">retrieve</a>(modelId, { ...params }) -> BetaModelInfo</code>
- <code title="get /v1/models?beta=true">client.beta.models.<a href="./src/resources/beta/models.ts">list</a>({ ...params }) -> BetaModelInfosPage</code>
## Messages
@@ -174,8 +188,10 @@ Types:
- <code><a href="./src/resources/beta/messages/messages.ts">BetaCitationContentBlockLocationParam</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaCitationPageLocation</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaCitationPageLocationParam</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaCitationWebSearchResultLocationParam</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaCitationsConfigParam</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaCitationsDelta</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaCitationsWebSearchResultLocation</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaContentBlock</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaContentBlockParam</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaContentBlockSource</a></code>
@@ -198,6 +214,9 @@ Types:
- <code><a href="./src/resources/beta/messages/messages.ts">BetaRawMessageStreamEvent</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaRedactedThinkingBlock</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaRedactedThinkingBlockParam</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaServerToolUsage</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaServerToolUseBlock</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaServerToolUseBlockParam</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaSignatureDelta</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaStopReason</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaTextBlock</a></code>
@@ -230,6 +249,15 @@ Types:
- <code><a href="./src/resources/beta/messages/messages.ts">BetaURLImageSource</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaURLPDFSource</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaUsage</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaWebSearchResultBlock</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaWebSearchResultBlockParam</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaWebSearchTool20250305</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaWebSearchToolRequestError</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaWebSearchToolResultBlock</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaWebSearchToolResultBlockContent</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaWebSearchToolResultBlockParam</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaWebSearchToolResultBlockParamContent</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaWebSearchToolResultError</a></code>
Methods:
diff --git examples/tools.ts examples/tools.ts
index 1a696bc0..8928efb0 100644
--- examples/tools.ts
+++ examples/tools.ts
@@ -49,7 +49,7 @@ async function main() {
{
type: 'tool_result',
tool_use_id: tool.id,
- content: [{ type: 'text', text: 'The weather is 73f' }],
+ content: 'The weather is 73f',
},
],
},
diff --git a/examples/web-search-stream.ts b/examples/web-search-stream.ts
new file mode 100755
index 00000000..38d08d46
--- /dev/null
+++ examples/web-search-stream.ts
@@ -0,0 +1,64 @@
+#!/usr/bin/env -S npm run tsn -T
+
+import Anthropic from '@anthropic-ai/sdk';
+
+const client = new Anthropic();
+
+async function main() {
+ console.log('Claude with Web Search (Streaming)');
+ console.log('==================================');
+
+ // Create a stream with web search enabled
+ const stream = client.messages
+ .stream({
+ model: 'claude-3-5-sonnet-latest',
+ max_tokens: 1024,
+ messages: [
+ {
+ role: 'user',
+ content: "What's the weather in New York?",
+ },
+ ],
+ tools: [
+ {
+ name: 'web_search',
+ type: 'web_search_20250305',
+ },
+ ],
+ })
+ .on('text', (text) => {
+ // Print text as it arrives
+ process.stdout.write(text);
+ })
+ .on('streamEvent', (event) => {
+ // Track when web search is being used
+ if (event.type === 'content_block_start' && event.content_block.type === 'web_search_tool_result') {
+ process.stdout.write('\n[Web search started...]');
+ }
+ });
+
+ // Wait for the stream to complete
+ const message = await stream.finalMessage();
+
+ console.log('\n\nFinal usage statistics:');
+ console.log(`Input tokens: ${message.usage.input_tokens}`);
+ console.log(`Output tokens: ${message.usage.output_tokens}`);
+
+ if (message.usage.server_tool_use) {
+ console.log(`Web search requests: ${message.usage.server_tool_use.web_search_requests}`);
+ } else {
+ console.log('No web search requests recorded in usage');
+ }
+
+ // Display message content types for debugging
+ console.log('\nMessage Content Types:');
+ message.content.forEach((block, i) => {
+ console.log(`Content Block ${i + 1}: Type = ${block.type}`);
+ });
+
+ // Show full message for debugging
+ console.log('\nComplete message structure:');
+ console.dir(message, { depth: 4 });
+}
+
+main().catch(console.error);
diff --git a/examples/web-search.ts b/examples/web-search.ts
new file mode 100755
index 00000000..e5c528ac
--- /dev/null
+++ examples/web-search.ts
@@ -0,0 +1,52 @@
+#!/usr/bin/env -S npm run tsn -T
+
+import Anthropic from '@anthropic-ai/sdk';
+
+const client = new Anthropic();
+
+async function main() {
+ console.log('Web Search Example');
+ console.log('=================');
+
+ // Create a message with web search enabled
+ const message = await client.messages.create({
+ model: 'claude-3-5-sonnet-latest',
+ max_tokens: 1024,
+ messages: [
+ {
+ role: 'user',
+ content:
+ "What's the current weather in San Francisco? Please search the web for up-to-date information.",
+ },
+ ],
+ tools: [
+ {
+ name: 'web_search',
+ type: 'web_search_20250305',
+ },
+ ],
+ });
+
+ // Print the full response
+ console.log('\nFull response:');
+ console.dir(message, { depth: 4 });
+
+ // Extract and print the content
+ console.log('\nResponse content:');
+ for (const contentBlock of message.content) {
+ if (contentBlock.type === 'text') {
+ console.log(contentBlock.text);
+ }
+ }
+
+ // Print usage information
+ console.log('\nUsage statistics:');
+ console.log(`Input tokens: ${message.usage.input_tokens}`);
+ console.log(`Output tokens: ${message.usage.output_tokens}`);
+
+ if (message.usage.server_tool_use) {
+ console.log(`Web search requests: ${message.usage.server_tool_use.web_search_requests}`);
+ }
+}
+
+main().catch(console.error);
diff --git package.json package.json
index 898d950c..451b1d7b 100644
--- package.json
+++ package.json
@@ -1,6 +1,6 @@
{
"name": "@anthropic-ai/sdk",
- "version": "0.40.1",
+ "version": "0.41.0",
"description": "The official TypeScript library for the Anthropic API",
"author": "Anthropic <[email protected]>",
"types": "dist/index.d.ts",
diff --git src/index.ts src/index.ts
index 3d901bea..ccfa494e 100644
--- src/index.ts
+++ src/index.ts
@@ -14,7 +14,7 @@ import {
CompletionCreateParamsStreaming,
Completions,
} from './resources/completions';
-import { ModelInfo, ModelInfosPage, ModelListParams, Models } from './resources/models';
+import { ModelInfo, ModelInfosPage, ModelListParams, ModelRetrieveParams, Models } from './resources/models';
import {
AnthropicBeta,
Beta,
@@ -40,8 +40,10 @@ import {
CitationContentBlockLocationParam,
CitationPageLocation,
CitationPageLocationParam,
+ CitationWebSearchResultLocationParam,
CitationsConfigParam,
CitationsDelta,
+ CitationsWebSearchResultLocation,
ContentBlock,
ContentBlockDeltaEvent,
ContentBlockParam,
@@ -80,6 +82,9 @@ import {
RawMessageStreamEvent,
RedactedThinkingBlock,
RedactedThinkingBlockParam,
+ ServerToolUsage,
+ ServerToolUseBlock,
+ ServerToolUseBlockParam,
SignatureDelta,
StopReason,
TextBlock,
@@ -108,6 +113,15 @@ import {
URLImageSource,
URLPDFSource,
Usage,
+ WebSearchResultBlock,
+ WebSearchResultBlockParam,
+ WebSearchTool20250305,
+ WebSearchToolRequestError,
+ WebSearchToolResultBlock,
+ WebSearchToolResultBlockContent,
+ WebSearchToolResultBlockParam,
+ WebSearchToolResultBlockParamContent,
+ WebSearchToolResultError,
} from './resources/messages/messages';
export interface ClientOptions {
@@ -354,8 +368,10 @@ export declare namespace Anthropic {
type CitationContentBlockLocationParam as CitationContentBlockLocationParam,
type CitationPageLocation as CitationPageLocation,
type CitationPageLocationParam as CitationPageLocationParam,
+ type CitationWebSearchResultLocationParam as CitationWebSearchResultLocationParam,
type CitationsConfigParam as CitationsConfigParam,
type CitationsDelta as CitationsDelta,
+ type CitationsWebSearchResultLocation as CitationsWebSearchResultLocation,
type ContentBlock as ContentBlock,
type ContentBlockParam as ContentBlockParam,
type ContentBlockSource as ContentBlockSource,
@@ -381,6 +397,9 @@ export declare namespace Anthropic {
type RawMessageStreamEvent as RawMessageStreamEvent,
type RedactedThinkingBlock as RedactedThinkingBlock,
type RedactedThinkingBlockParam as RedactedThinkingBlockParam,
+ type ServerToolUsage as ServerToolUsage,
+ type ServerToolUseBlock as ServerToolUseBlock,
+ type ServerToolUseBlockParam as ServerToolUseBlockParam,
type SignatureDelta as SignatureDelta,
type StopReason as StopReason,
type TextBlock as TextBlock,
@@ -409,6 +428,15 @@ export declare namespace Anthropic {
type URLImageSource as URLImageSource,
type URLPDFSource as URLPDFSource,
type Usage as Usage,
+ type WebSearchResultBlock as WebSearchResultBlock,
+ type WebSearchResultBlockParam as WebSearchResultBlockParam,
+ type WebSearchTool20250305 as WebSearchTool20250305,
+ type WebSearchToolRequestError as WebSearchToolRequestError,
+ type WebSearchToolResultBlock as WebSearchToolResultBlock,
+ type WebSearchToolResultBlockContent as WebSearchToolResultBlockContent,
+ type WebSearchToolResultBlockParam as WebSearchToolResultBlockParam,
+ type WebSearchToolResultBlockParamContent as WebSearchToolResultBlockParamContent,
+ type WebSearchToolResultError as WebSearchToolResultError,
type MessageStreamEvent as MessageStreamEvent,
type MessageStartEvent as MessageStartEvent,
type MessageDeltaEvent as MessageDeltaEvent,
@@ -427,6 +455,7 @@ export declare namespace Anthropic {
Models as Models,
type ModelInfo as ModelInfo,
ModelInfosPage as ModelInfosPage,
+ type ModelRetrieveParams as ModelRetrieveParams,
type ModelListParams as ModelListParams,
};
diff --git src/lib/BetaMessageStream.ts src/lib/BetaMessageStream.ts
index fd096926..7ad1d89f 100644
--- src/lib/BetaMessageStream.ts
+++ src/lib/BetaMessageStream.ts
@@ -530,6 +530,15 @@ export class BetaMessageStream implements AsyncIterable<BetaMessageStreamEvent>
snapshot.stop_reason = event.delta.stop_reason;
snapshot.stop_sequence = event.delta.stop_sequence;
snapshot.usage.output_tokens = event.usage.output_tokens;
+
+ // Update other usage fields if they exist in the event
+ if (event.usage.input_tokens) {
+ snapshot.usage.input_tokens = event.usage.input_tokens;
+ }
+ snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens;
+ snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens;
+ snapshot.usage.server_tool_use = event.usage.server_tool_use;
+
return snapshot;
case 'content_block_start':
snapshot.content.push(event.content_block);
diff --git src/lib/MessageStream.ts src/lib/MessageStream.ts
index 712a34ff..af81bf68 100644
--- src/lib/MessageStream.ts
+++ src/lib/MessageStream.ts
@@ -530,6 +530,15 @@ export class MessageStream implements AsyncIterable<MessageStreamEvent> {
snapshot.stop_reason = event.delta.stop_reason;
snapshot.stop_sequence = event.delta.stop_sequence;
snapshot.usage.output_tokens = event.usage.output_tokens;
+
+ // Update other usage fields if they exist in the event
+ if (event.usage.input_tokens) {
+ snapshot.usage.input_tokens = event.usage.input_tokens;
+ }
+ snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens;
+ snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens;
+ snapshot.usage.server_tool_use = event.usage.server_tool_use;
+
return snapshot;
case 'content_block_start':
snapshot.content.push(event.content_block);
diff --git src/resources/beta/beta.ts src/resources/beta/beta.ts
index 69578396..fc16229a 100644
--- src/resources/beta/beta.ts
+++ src/resources/beta/beta.ts
@@ -2,7 +2,7 @@
import { APIResource } from '../../resource';
import * as ModelsAPI from './models';
-import { BetaModelInfo, BetaModelInfosPage, ModelListParams, Models } from './models';
+import { BetaModelInfo, BetaModelInfosPage, ModelListParams, ModelRetrieveParams, Models } from './models';
import * as MessagesAPI from './messages/messages';
import {
BetaBase64ImageSource,
@@ -15,8 +15,10 @@ import {
BetaCitationContentBlockLocationParam,
BetaCitationPageLocation,
BetaCitationPageLocationParam,
+ BetaCitationWebSearchResultLocationParam,
BetaCitationsConfigParam,
BetaCitationsDelta,
+ BetaCitationsWebSearchResultLocation,
BetaContentBlock,
BetaContentBlockParam,
BetaContentBlockSource,
@@ -39,6 +41,9 @@ import {
BetaRawMessageStreamEvent,
BetaRedactedThinkingBlock,
BetaRedactedThinkingBlockParam,
+ BetaServerToolUsage,
+ BetaServerToolUseBlock,
+ BetaServerToolUseBlockParam,
BetaSignatureDelta,
BetaStopReason,
BetaTextBlock,
@@ -71,6 +76,15 @@ import {
BetaURLImageSource,
BetaURLPDFSource,
BetaUsage,
+ BetaWebSearchResultBlock,
+ BetaWebSearchResultBlockParam,
+ BetaWebSearchTool20250305,
+ BetaWebSearchToolRequestError,
+ BetaWebSearchToolResultBlock,
+ BetaWebSearchToolResultBlockContent,
+ BetaWebSearchToolResultBlockParam,
+ BetaWebSearchToolResultBlockParamContent,
+ BetaWebSearchToolResultError,
MessageCountTokensParams,
MessageCreateParams,
MessageCreateParamsNonStreaming,
@@ -189,6 +203,7 @@ export declare namespace Beta {
Models as Models,
type BetaModelInfo as BetaModelInfo,
BetaModelInfosPage as BetaModelInfosPage,
+ type ModelRetrieveParams as ModelRetrieveParams,
type ModelListParams as ModelListParams,
};
@@ -204,8 +219,10 @@ export declare namespace Beta {
type BetaCitationContentBlockLocationParam as BetaCitationContentBlockLocationParam,
type BetaCitationPageLocation as BetaCitationPageLocation,
type BetaCitationPageLocationParam as BetaCitationPageLocationParam,
+ type BetaCitationWebSearchResultLocationParam as BetaCitationWebSearchResultLocationParam,
type BetaCitationsConfigParam as BetaCitationsConfigParam,
type BetaCitationsDelta as BetaCitationsDelta,
+ type BetaCitationsWebSearchResultLocation as BetaCitationsWebSearchResultLocation,
type BetaContentBlock as BetaContentBlock,
type BetaContentBlockParam as BetaContentBlockParam,
type BetaContentBlockSource as BetaContentBlockSource,
@@ -228,6 +245,9 @@ export declare namespace Beta {
type BetaRawMessageStreamEvent as BetaRawMessageStreamEvent,
type BetaRedactedThinkingBlock as BetaRedactedThinkingBlock,
type BetaRedactedThinkingBlockParam as BetaRedactedThinkingBlockParam,
+ type BetaServerToolUsage as BetaServerToolUsage,
+ type BetaServerToolUseBlock as BetaServerToolUseBlock,
+ type BetaServerToolUseBlockParam as BetaServerToolUseBlockParam,
type BetaSignatureDelta as BetaSignatureDelta,
type BetaStopReason as BetaStopReason,
type BetaTextBlock as BetaTextBlock,
@@ -260,6 +280,15 @@ export declare namespace Beta {
type BetaURLImageSource as BetaURLImageSource,
type BetaURLPDFSource as BetaURLPDFSource,
type BetaUsage as BetaUsage,
+ type BetaWebSearchResultBlock as BetaWebSearchResultBlock,
+ type BetaWebSearchResultBlockParam as BetaWebSearchResultBlockParam,
+ type BetaWebSearchTool20250305 as BetaWebSearchTool20250305,
+ type BetaWebSearchToolRequestError as BetaWebSearchToolRequestError,
+ type BetaWebSearchToolResultBlock as BetaWebSearchToolResultBlock,
+ type BetaWebSearchToolResultBlockContent as BetaWebSearchToolResultBlockContent,
+ type BetaWebSearchToolResultBlockParam as BetaWebSearchToolResultBlockParam,
+ type BetaWebSearchToolResultBlockParamContent as BetaWebSearchToolResultBlockParamContent,
+ type BetaWebSearchToolResultError as BetaWebSearchToolResultError,
type MessageCreateParams as MessageCreateParams,
type MessageCreateParamsNonStreaming as MessageCreateParamsNonStreaming,
type MessageCreateParamsStreaming as MessageCreateParamsStreaming,
diff --git src/resources/beta/index.ts src/resources/beta/index.ts
index 4402c642..8abd778f 100644
--- src/resources/beta/index.ts
+++ src/resources/beta/index.ts
@@ -15,7 +15,13 @@ export {
type BetaPermissionError,
type BetaRateLimitError,
} from './beta';
-export { BetaModelInfosPage, Models, type BetaModelInfo, type ModelListParams } from './models';
+export {
+ BetaModelInfosPage,
+ Models,
+ type BetaModelInfo,
+ type ModelRetrieveParams,
+ type ModelListParams,
+} from './models';
export {
Messages,
type BetaBase64ImageSource,
@@ -28,8 +34,10 @@ export {
type BetaCitationContentBlockLocationParam,
type BetaCitationPageLocation,
type BetaCitationPageLocationParam,
+ type BetaCitationWebSearchResultLocationParam,
type BetaCitationsConfigParam,
type BetaCitationsDelta,
+ type BetaCitationsWebSearchResultLocation,
type BetaContentBlock,
type BetaContentBlockParam,
type BetaContentBlockSource,
@@ -52,6 +60,9 @@ export {
type BetaRawMessageStreamEvent,
type BetaRedactedThinkingBlock,
type BetaRedactedThinkingBlockParam,
+ type BetaServerToolUsage,
+ type BetaServerToolUseBlock,
+ type BetaServerToolUseBlockParam,
type BetaSignatureDelta,
type BetaStopReason,
type BetaTextBlock,
@@ -84,6 +95,15 @@ export {
type BetaURLImageSource,
type BetaURLPDFSource,
type BetaUsage,
+ type BetaWebSearchResultBlock,
+ type BetaWebSearchResultBlockParam,
+ type BetaWebSearchTool20250305,
+ type BetaWebSearchToolRequestError,
+ type BetaWebSearchToolResultBlock,
+ type BetaWebSearchToolResultBlockContent,
+ type BetaWebSearchToolResultBlockParam,
+ type BetaWebSearchToolResultBlockParamContent,
+ type BetaWebSearchToolResultError,
type MessageCreateParams,
type MessageCreateParamsNonStreaming,
type MessageCreateParamsStreaming,
diff --git src/resources/beta/messages/batches.ts src/resources/beta/messages/batches.ts
index ba6fce27..dde90fac 100644
--- src/resources/beta/messages/batches.ts
+++ src/resources/beta/messages/batches.ts
@@ -20,6 +20,25 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const betaMessageBatch =
+ * await client.beta.messages.batches.create({
+ * requests: [
+ * {
+ * custom_id: 'my-custom-id-1',
+ * params: {
+ * max_tokens: 1024,
+ * messages: [
+ * { content: 'Hello, world', role: 'user' },
+ * ],
+ * model: 'claude-3-7-sonnet-20250219',
+ * },
+ * },
+ * ],
+ * });
+ * ```
*/
create(params: BatchCreateParams, options?: Core.RequestOptions): Core.APIPromise<BetaMessageBatch> {
const { betas, ...body } = params;
@@ -40,6 +59,14 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const betaMessageBatch =
+ * await client.beta.messages.batches.retrieve(
+ * 'message_batch_id',
+ * );
+ * ```
*/
retrieve(
messageBatchId: string,
@@ -71,6 +98,14 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const betaMessageBatch of client.beta.messages.batches.list()) {
+ * // ...
+ * }
+ * ```
*/
list(
params?: BatchListParams,
@@ -103,6 +138,14 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const betaDeletedMessageBatch =
+ * await client.beta.messages.batches.delete(
+ * 'message_batch_id',
+ * );
+ * ```
*/
delete(
messageBatchId: string,
@@ -141,6 +184,14 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const betaMessageBatch =
+ * await client.beta.messages.batches.cancel(
+ * 'message_batch_id',
+ * );
+ * ```
*/
cancel(
messageBatchId: string,
@@ -175,6 +226,14 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const betaMessageBatchIndividualResponse =
+ * await client.beta.messages.batches.results(
+ * 'message_batch_id',
+ * );
+ * ```
*/
async results(
messageBatchId: string,
diff --git src/resources/beta/messages/index.ts src/resources/beta/messages/index.ts
index 39bfffd8..5a5d04bd 100644
--- src/resources/beta/messages/index.ts
+++ src/resources/beta/messages/index.ts
@@ -31,8 +31,10 @@ export {
type BetaCitationContentBlockLocationParam,
type BetaCitationPageLocation,
type BetaCitationPageLocationParam,
+ type BetaCitationWebSearchResultLocationParam,
type BetaCitationsConfigParam,
type BetaCitationsDelta,
+ type BetaCitationsWebSearchResultLocation,
type BetaContentBlock,
type BetaContentBlockParam,
type BetaContentBlockSource,
@@ -55,6 +57,9 @@ export {
type BetaRawMessageStreamEvent,
type BetaRedactedThinkingBlock,
type BetaRedactedThinkingBlockParam,
+ type BetaServerToolUsage,
+ type BetaServerToolUseBlock,
+ type BetaServerToolUseBlockParam,
type BetaSignatureDelta,
type BetaStopReason,
type BetaTextBlock,
@@ -87,6 +92,15 @@ export {
type BetaURLImageSource,
type BetaURLPDFSource,
type BetaUsage,
+ type BetaWebSearchResultBlock,
+ type BetaWebSearchResultBlockParam,
+ type BetaWebSearchTool20250305,
+ type BetaWebSearchToolRequestError,
+ type BetaWebSearchToolResultBlock,
+ type BetaWebSearchToolResultBlockContent,
+ type BetaWebSearchToolResultBlockParam,
+ type BetaWebSearchToolResultBlockParamContent,
+ type BetaWebSearchToolResultError,
type MessageCreateParams,
type MessageCreateParamsNonStreaming,
type MessageCreateParamsStreaming,
diff --git src/resources/beta/messages/messages.ts src/resources/beta/messages/messages.ts
index bc9fb874..e961cf1c 100644
--- src/resources/beta/messages/messages.ts
+++ src/resources/beta/messages/messages.ts
@@ -54,6 +54,15 @@ export class Messages extends APIResource {
* conversations.
*
* Learn more about the Messages API in our [user guide](/en/docs/initial-setup)
+ *
+ * @example
+ * ```ts
+ * const betaMessage = await client.beta.messages.create({
+ * max_tokens: 1024,
+ * messages: [{ content: 'Hello, world', role: 'user' }],
+ * model: 'claude-3-7-sonnet-20250219',
+ * });
+ * ```
*/
create(params: MessageCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<BetaMessage>;
create(
@@ -107,6 +116,15 @@ export class Messages extends APIResource {
*
* Learn more about token counting in our
* [user guide](/en/docs/build-with-claude/token-counting)
+ *
+ * @example
+ * ```ts
+ * const betaMessageTokensCount =
+ * await client.beta.messages.countTokens({
+ * messages: [{ content: 'string', role: 'user' }],
+ * model: 'claude-3-7-sonnet-latest',
+ * });
+ * ```
*/
countTokens(
params: MessageCountTokensParams,
@@ -139,6 +157,9 @@ export interface BetaBase64PDFBlock {
type: 'document';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
citations?: BetaCitationsConfigParam;
@@ -244,19 +265,49 @@ export interface BetaCitationPageLocationParam {
type: 'page_location';
}
+export interface BetaCitationWebSearchResultLocationParam {
+ cited_text: string;
+
+ encrypted_index: string;
+
+ title: string | null;
+
+ type: 'web_search_result_location';
+
+ url: string;
+}
+
export interface BetaCitationsConfigParam {
enabled?: boolean;
}
export interface BetaCitationsDelta {
- citation: BetaCitationCharLocation | BetaCitationPageLocation | BetaCitationContentBlockLocation;
+ citation:
+ | BetaCitationCharLocation
+ | BetaCitationPageLocation
+ | BetaCitationContentBlockLocation
+ | BetaCitationsWebSearchResultLocation;
type: 'citations_delta';
}
+export interface BetaCitationsWebSearchResultLocation {
+ cited_text: string;
+
+ encrypted_index: string;
+
+ title: string | null;
+
+ type: 'web_search_result_location';
+
+ url: string;
+}
+
export type BetaContentBlock =
| BetaTextBlock
| BetaToolUseBlock
+ | BetaServerToolUseBlock
+ | BetaWebSearchToolResultBlock
| BetaThinkingBlock
| BetaRedactedThinkingBlock;
@@ -264,6 +315,8 @@ export type BetaContentBlockParam =
| BetaTextBlockParam
| BetaImageBlockParam
| BetaToolUseBlockParam
+ | BetaServerToolUseBlockParam
+ | BetaWebSearchToolResultBlockParam
| BetaToolResultBlockParam
| BetaBase64PDFBlock
| BetaThinkingBlockParam
@@ -282,6 +335,9 @@ export interface BetaImageBlockParam {
type: 'image';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
}
@@ -400,10 +456,30 @@ export interface BetaMessage {
}
export interface BetaMessageDeltaUsage {
+ /**
+ * The cumulative number of input tokens used to create the cache entry.
+ */
+ cache_creation_input_tokens: number | null;
+
+ /**
+ * The cumulative number of input tokens read from the cache.
+ */
+ cache_read_input_tokens: number | null;
+
+ /**
+ * The cumulative number of input tokens which were used.
+ */
+ input_tokens: number | null;
+
/**
* The cumulative number of output tokens which were used.
*/
output_tokens: number;
+
+ /**
+ * The number of server tool requests.
+ */
+ server_tool_use: BetaServerToolUsage | null;
}
export interface BetaMessageParam {
@@ -455,7 +531,13 @@ export interface BetaRawContentBlockDeltaEvent {
}
export interface BetaRawContentBlockStartEvent {
- content_block: BetaTextBlock | BetaToolUseBlock | BetaThinkingBlock | BetaRedactedThinkingBlock;
+ content_block:
+ | BetaTextBlock
+ | BetaToolUseBlock
+ | BetaServerToolUseBlock
+ | BetaWebSearchToolResultBlock
+ | BetaThinkingBlock
+ | BetaRedactedThinkingBlock;
index: number;
@@ -531,13 +613,51 @@ export interface BetaRedactedThinkingBlockParam {
type: 'redacted_thinking';
}
+export interface BetaServerToolUsage {
+ /**
+ * The number of web search tool requests.
+ */
+ web_search_requests: number;
+}
+
+export interface BetaServerToolUseBlock {
+ id: string;
+
+ input: unknown;
+
+ name: 'web_search';
+
+ type: 'server_tool_use';
+}
+
+export interface BetaServerToolUseBlockParam {
+ id: string;
+
+ input: unknown;
+
+ name: 'web_search';
+
+ type: 'server_tool_use';
+
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
+ cache_control?: BetaCacheControlEphemeral | null;
+}
+
export interface BetaSignatureDelta {
signature: string;
type: 'signature_delta';
}
-export type BetaStopReason = 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use';
+export type BetaStopReason =
+ | 'end_turn'
+ | 'max_tokens'
+ | 'stop_sequence'
+ | 'tool_use'
+ | 'pause_turn'
+ | 'refusal';
export interface BetaTextBlock {
/**
@@ -559,6 +679,9 @@ export interface BetaTextBlockParam {
type: 'text';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
citations?: Array<BetaTextCitationParam> | null;
@@ -567,12 +690,14 @@ export interface BetaTextBlockParam {
export type BetaTextCitation =
| BetaCitationCharLocation
| BetaCitationPageLocation
- | BetaCitationContentBlockLocation;
+ | BetaCitationContentBlockLocation
+ | BetaCitationsWebSearchResultLocation;
export type BetaTextCitationParam =
| BetaCitationCharLocationParam
| BetaCitationPageLocationParam
- | BetaCitationContentBlockLocationParam;
+ | BetaCitationContentBlockLocationParam
+ | BetaCitationWebSearchResultLocationParam;
export interface BetaTextDelta {
text: string;
@@ -648,10 +773,13 @@ export interface BetaTool {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: string;
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
/**
@@ -687,12 +815,15 @@ export interface BetaToolBash20241022 {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: 'bash';
type: 'bash_20241022';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
}
@@ -700,12 +831,15 @@ export interface BetaToolBash20250124 {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: 'bash';
type: 'bash_20250124';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
}
@@ -786,12 +920,15 @@ export interface BetaToolComputerUse20241022 {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: 'computer';
type: 'computer_20241022';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
/**
@@ -814,12 +951,15 @@ export interface BetaToolComputerUse20250124 {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: 'computer';
type: 'computer_20250124';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
/**
@@ -833,6 +973,9 @@ export interface BetaToolResultBlockParam {
type: 'tool_result';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
content?: string | Array<BetaTextBlockParam | BetaImageBlockParam>;
@@ -844,12 +987,15 @@ export interface BetaToolTextEditor20241022 {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: 'str_replace_editor';
type: 'text_editor_20241022';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
}
@@ -857,12 +1003,15 @@ export interface BetaToolTextEditor20250124 {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: 'str_replace_editor';
type: 'text_editor_20250124';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
}
@@ -873,7 +1022,8 @@ export type BetaToolUnion =
| BetaToolTextEditor20241022
| BetaToolComputerUse20250124
| BetaToolBash20250124
- | BetaToolTextEditor20250124;
+ | BetaToolTextEditor20250124
+ | BetaWebSearchTool20250305;
export interface BetaToolUseBlock {
id: string;
@@ -894,6 +1044,9 @@ export interface BetaToolUseBlockParam {
type: 'tool_use';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
}
@@ -929,6 +1082,157 @@ export interface BetaUsage {
* The number of output tokens which were used.
*/
output_tokens: number;
+
+ /**
+ * The number of server tool requests.
+ */
+ server_tool_use: BetaServerToolUsage | null;
+}
+
+export interface BetaWebSearchResultBlock {
+ encrypted_content: string;
+
+ page_age: string | null;
+
+ title: string;
+
+ type: 'web_search_result';
+
+ url: string;
+}
+
+export interface BetaWebSearchResultBlockParam {
+ encrypted_content: string;
+
+ title: string;
+
+ type: 'web_search_result';
+
+ url: string;
+
+ page_age?: string | null;
+}
+
+export interface BetaWebSearchTool20250305 {
+ /**
+ * Name of the tool.
+ *
+ * This is how the tool will be called by the model and in `tool_use` blocks.
+ */
+ name: 'web_search';
+
+ type: 'web_search_20250305';
+
+ /**
+ * If provided, only these domains will be included in results. Cannot be used
+ * alongside `blocked_domains`.
+ */
+ allowed_domains?: Array<string> | null;
+
+ /**
+ * If provided, these domains will never appear in results. Cannot be used
+ * alongside `allowed_domains`.
+ */
+ blocked_domains?: Array<string> | null;
+
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
+ cache_control?: BetaCacheControlEphemeral | null;
+
+ /**
+ * Maximum number of times the tool can be used in the API request.
+ */
+ max_uses?: number | null;
+
+ /**
+ * Parameters for the user's location. Used to provide more relevant search
+ * results.
+ */
+ user_location?: BetaWebSearchTool20250305.UserLocation | null;
+}
+
+export namespace BetaWebSearchTool20250305 {
+ /**
+ * Parameters for the user's location. Used to provide more relevant search
+ * results.
+ */
+ export interface UserLocation {
+ type: 'approximate';
+
+ /**
+ * The city of the user.
+ */
+ city?: string | null;
+
+ /**
+ * The two letter
+ * [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the
+ * user.
+ */
+ country?: string | null;
+
+ /**
+ * The region of the user.
+ */
+ region?: string | null;
+
+ /**
+ * The [IANA timezone](https://nodatime.org/TimeZones) of the user.
+ */
+ timezone?: string | null;
+ }
+}
+
+export interface BetaWebSearchToolRequestError {
+ error_code:
+ | 'invalid_tool_input'
+ | 'unavailable'
+ | 'max_uses_exceeded'
+ | 'too_many_requests'
+ | 'query_too_long';
+
+ type: 'web_search_tool_result_error';
+}
+
+export interface BetaWebSearchToolResultBlock {
+ content: BetaWebSearchToolResultBlockContent;
+
+ tool_use_id: string;
+
+ type: 'web_search_tool_result';
+}
+
+export type BetaWebSearchToolResultBlockContent =
+ | BetaWebSearchToolResultError
+ | Array<BetaWebSearchResultBlock>;
+
+export interface BetaWebSearchToolResultBlockParam {
+ content: BetaWebSearchToolResultBlockParamContent;
+
+ tool_use_id: string;
+
+ type: 'web_search_tool_result';
+
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
+ cache_control?: BetaCacheControlEphemeral | null;
+}
+
+export type BetaWebSearchToolResultBlockParamContent =
+ | Array<BetaWebSearchResultBlockParam>
+ | BetaWebSearchToolRequestError;
+
+export interface BetaWebSearchToolResultError {
+ error_code:
+ | 'invalid_tool_input'
+ | 'unavailable'
+ | 'max_uses_exceeded'
+ | 'too_many_requests'
+ | 'query_too_long';
+
+ type: 'web_search_tool_result_error';
}
export type MessageCreateParams = MessageCreateParamsNonStreaming | MessageCreateParamsStreaming;
@@ -1032,6 +1336,8 @@ export interface MessageCreateParamsBase {
* [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use
* the top-level `system` parameter β there is no `"system"` role for input
* messages in the Messages API.
+ *
+ * There is a limit of 100000 messages in a single request.
*/
messages: Array<BetaMessageParam>;
@@ -1327,6 +1633,8 @@ export interface MessageCountTokensParams {
* [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use
* the top-level `system` parameter β there is no `"system"` role for input
* messages in the Messages API.
+ *
+ * There is a limit of 100000 messages in a single request.
*/
messages: Array<BetaMessageParam>;
@@ -1444,6 +1752,7 @@ export interface MessageCountTokensParams {
| BetaToolComputerUse20250124
| BetaToolBash20250124
| BetaToolTextEditor20250124
+ | BetaWebSearchTool20250305
>;
/**
@@ -1467,8 +1776,10 @@ export declare namespace Messages {
type BetaCitationContentBlockLocationParam as BetaCitationContentBlockLocationParam,
type BetaCitationPageLocation as BetaCitationPageLocation,
type BetaCitationPageLocationParam as BetaCitationPageLocationParam,
+ type BetaCitationWebSearchResultLocationParam as BetaCitationWebSearchResultLocationParam,
type BetaCitationsConfigParam as BetaCitationsConfigParam,
type BetaCitationsDelta as BetaCitationsDelta,
+ type BetaCitationsWebSearchResultLocation as BetaCitationsWebSearchResultLocation,
type BetaContentBlock as BetaContentBlock,
type BetaContentBlockParam as BetaContentBlockParam,
type BetaContentBlockSource as BetaContentBlockSource,
@@ -1491,6 +1802,9 @@ export declare namespace Messages {
type BetaRawMessageStreamEvent as BetaRawMessageStreamEvent,
type BetaRedactedThinkingBlock as BetaRedactedThinkingBlock,
type BetaRedactedThinkingBlockParam as BetaRedactedThinkingBlockParam,
+ type BetaServerToolUsage as BetaServerToolUsage,
+ type BetaServerToolUseBlock as BetaServerToolUseBlock,
+ type BetaServerToolUseBlockParam as BetaServerToolUseBlockParam,
type BetaSignatureDelta as BetaSignatureDelta,
type BetaStopReason as BetaStopReason,
type BetaTextBlock as BetaTextBlock,
@@ -1523,6 +1837,15 @@ export declare namespace Messages {
type BetaURLImageSource as BetaURLImageSource,
type BetaURLPDFSource as BetaURLPDFSource,
type BetaUsage as BetaUsage,
+ type BetaWebSearchResultBlock as BetaWebSearchResultBlock,
+ type BetaWebSearchResultBlockParam as BetaWebSearchResultBlockParam,
+ type BetaWebSearchTool20250305 as BetaWebSearchTool20250305,
+ type BetaWebSearchToolRequestError as BetaWebSearchToolRequestError,
+ type BetaWebSearchToolResultBlock as BetaWebSearchToolResultBlock,
+ type BetaWebSearchToolResultBlockContent as BetaWebSearchToolResultBlockContent,
+ type BetaWebSearchToolResultBlockParam as BetaWebSearchToolResultBlockParam,
+ type BetaWebSearchToolResultBlockParamContent as BetaWebSearchToolResultBlockParamContent,
+ type BetaWebSearchToolResultError as BetaWebSearchToolResultError,
type MessageCreateParams as MessageCreateParams,
type MessageCreateParamsNonStreaming as MessageCreateParamsNonStreaming,
type MessageCreateParamsStreaming as MessageCreateParamsStreaming,
diff --git src/resources/beta/models.ts src/resources/beta/models.ts
index 48036273..6ec9c244 100644
--- src/resources/beta/models.ts
+++ src/resources/beta/models.ts
@@ -3,6 +3,7 @@
import { APIResource } from '../../resource';
import { isRequestOptions } from '../../core';
import * as Core from '../../core';
+import * as BetaAPI from './beta';
import { Page, type PageParams } from '../../pagination';
export class Models extends APIResource {
@@ -11,9 +12,36 @@ export class Models extends APIResource {
*
* The Models API response can be used to determine information about a specific
* model or resolve a model alias to a model ID.
+ *
+ * @example
+ * ```ts
+ * const betaModelInfo = await client.beta.models.retrieve(
+ * 'model_id',
+ * );
+ * ```
*/
- retrieve(modelId: string, options?: Core.RequestOptions): Core.APIPromise<BetaModelInfo> {
- return this._client.get(`/v1/models/${modelId}?beta=true`, options);
+ retrieve(
+ modelId: string,
+ params?: ModelRetrieveParams,
+ options?: Core.RequestOptions,
+ ): Core.APIPromise<BetaModelInfo>;
+ retrieve(modelId: string, options?: Core.RequestOptions): Core.APIPromise<BetaModelInfo>;
+ retrieve(
+ modelId: string,
+ params: ModelRetrieveParams | Core.RequestOptions = {},
+ options?: Core.RequestOptions,
+ ): Core.APIPromise<BetaModelInfo> {
+ if (isRequestOptions(params)) {
+ return this.retrieve(modelId, {}, params);
+ }
+ const { betas } = params;
+ return this._client.get(`/v1/models/${modelId}?beta=true`, {
+ ...options,
+ headers: {
+ ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined),
+ ...options?.headers,
+ },
+ });
}
/**
@@ -21,20 +49,36 @@ export class Models extends APIResource {
*
* The Models API response can be used to determine which models are available for
* use in the API. More recently released models are listed first.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const betaModelInfo of client.beta.models.list()) {
+ * // ...
+ * }
+ * ```
*/
list(
- query?: ModelListParams,
+ params?: ModelListParams,
options?: Core.RequestOptions,
): Core.PagePromise<BetaModelInfosPage, BetaModelInfo>;
list(options?: Core.RequestOptions): Core.PagePromise<BetaModelInfosPage, BetaModelInfo>;
list(
- query: ModelListParams | Core.RequestOptions = {},
+ params: ModelListParams | Core.RequestOptions = {},
options?: Core.RequestOptions,
): Core.PagePromise<BetaModelInfosPage, BetaModelInfo> {
- if (isRequestOptions(query)) {
- return this.list({}, query);
+ if (isRequestOptions(params)) {
+ return this.list({}, params);
}
- return this._client.getAPIList('/v1/models?beta=true', BetaModelInfosPage, { query, ...options });
+ const { betas, ...query } = params;
+ return this._client.getAPIList('/v1/models?beta=true', BetaModelInfosPage, {
+ query,
+ ...options,
+ headers: {
+ ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined),
+ ...options?.headers,
+ },
+ });
}
}
@@ -65,7 +109,19 @@ export interface BetaModelInfo {
type: 'model';
}
-export interface ModelListParams extends PageParams {}
+export interface ModelRetrieveParams {
+ /**
+ * Optional header to specify the beta version(s) you want to use.
+ */
+ betas?: Array<BetaAPI.AnthropicBeta>;
+}
+
+export interface ModelListParams extends PageParams {
+ /**
+ * Header param: Optional header to specify the beta version(s) you want to use.
+ */
+ betas?: Array<BetaAPI.AnthropicBeta>;
+}
Models.BetaModelInfosPage = BetaModelInfosPage;
@@ -73,6 +129,7 @@ export declare namespace Models {
export {
type BetaModelInfo as BetaModelInfo,
BetaModelInfosPage as BetaModelInfosPage,
+ type ModelRetrieveParams as ModelRetrieveParams,
type ModelListParams as ModelListParams,
};
}
diff --git src/resources/completions.ts src/resources/completions.ts
index 2260681d..a0bfb0ab 100644
--- src/resources/completions.ts
+++ src/resources/completions.ts
@@ -4,6 +4,7 @@ import { APIResource } from '../resource';
import { APIPromise } from '../core';
import * as Core from '../core';
import * as CompletionsAPI from './completions';
+import * as BetaAPI from './beta/beta';
import * as MessagesAPI from './messages/messages';
import { Stream } from '../streaming';
@@ -17,25 +18,39 @@ export class Completions extends APIResource {
* Future models and features will not be compatible with Text Completions. See our
* [migration guide](https://docs.anthropic.com/en/api/migrating-from-text-completions-to-messages)
* for guidance in migrating from Text Completions to Messages.
+ *
+ * @example
+ * ```ts
+ * const completion = await client.completions.create({
+ * max_tokens_to_sample: 256,
+ * model: 'claude-3-7-sonnet-latest',
+ * prompt: '\n\nHuman: Hello, world!\n\nAssistant:',
+ * });
+ * ```
*/
- create(body: CompletionCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<Completion>;
+ create(params: CompletionCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<Completion>;
create(
- body: CompletionCreateParamsStreaming,
+ params: CompletionCreateParamsStreaming,
options?: Core.RequestOptions,
): APIPromise<Stream<Completion>>;
create(
- body: CompletionCreateParamsBase,
+ params: CompletionCreateParamsBase,
options?: Core.RequestOptions,
): APIPromise<Stream<Completion> | Completion>;
create(
- body: CompletionCreateParams,
+ params: CompletionCreateParams,
options?: Core.RequestOptions,
): APIPromise<Completion> | APIPromise<Stream<Completion>> {
+ const { betas, ...body } = params;
return this._client.post('/v1/complete', {
body,
timeout: (this._client as any)._options.timeout ?? 600000,
...options,
- stream: body.stream ?? false,
+ headers: {
+ ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined),
+ ...options?.headers,
+ },
+ stream: params.stream ?? false,
}) as APIPromise<Completion> | APIPromise<Stream<Completion>>;
}
}
@@ -83,7 +98,7 @@ export type CompletionCreateParams = CompletionCreateParamsNonStreaming | Comple
export interface CompletionCreateParamsBase {
/**
- * The maximum number of tokens to generate before stopping.
+ * Body param: The maximum number of tokens to generate before stopping.
*
* Note that our models may stop _before_ reaching this maximum. This parameter
* only specifies the absolute maximum number of tokens to generate.
@@ -91,14 +106,14 @@ export interface CompletionCreateParamsBase {
max_tokens_to_sample: number;
/**
- * The model that will complete your prompt.\n\nSee
+ * Body param: The model that will complete your prompt.\n\nSee
* [models](https://docs.anthropic.com/en/docs/models-overview) for additional
* details and options.
*/
model: MessagesAPI.Model;
/**
- * The prompt that you want Claude to complete.
+ * Body param: The prompt that you want Claude to complete.
*
* For proper response generation you will need to format your prompt using
* alternating `\n\nHuman:` and `\n\nAssistant:` conversational turns. For example:
@@ -115,12 +130,12 @@ export interface CompletionCreateParamsBase {
prompt: string;
/**
- * An object describing metadata about the request.
+ * Body param: An object describing metadata about the request.
*/
metadata?: MessagesAPI.Metadata;
/**
- * Sequences that will cause the model to stop generating.
+ * Body param: Sequences that will cause the model to stop generating.
*
* Our models stop on `"\n\nHuman:"`, and may include additional built-in stop
* sequences in the future. By providing the stop_sequences parameter, you may
@@ -129,14 +144,15 @@ export interface CompletionCreateParamsBase {
stop_sequences?: Array<string>;
/**
- * Whether to incrementally stream the response using server-sent events.
+ * Body param: Whether to incrementally stream the response using server-sent
+ * events.
*
* See [streaming](https://docs.anthropic.com/en/api/streaming) for details.
*/
stream?: boolean;
/**
- * Amount of randomness injected into the response.
+ * Body param: Amount of randomness injected into the response.
*
* Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0`
* for analytical / multiple choice, and closer to `1.0` for creative and
@@ -148,7 +164,7 @@ export interface CompletionCreateParamsBase {
temperature?: number;
/**
- * Only sample from the top K options for each subsequent token.
+ * Body param: Only sample from the top K options for each subsequent token.
*
* Used to remove "long tail" low probability responses.
* [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).
@@ -159,7 +175,7 @@ export interface CompletionCreateParamsBase {
top_k?: number;
/**
- * Use nucleus sampling.
+ * Body param: Use nucleus sampling.
*
* In nucleus sampling, we compute the cumulative distribution over all the options
* for each subsequent token in decreasing probability order and cut it off once it
@@ -170,6 +186,11 @@ export interface CompletionCreateParamsBase {
* `temperature`.
*/
top_p?: number;
+
+ /**
+ * Header param: Optional header to specify the beta version(s) you want to use.
+ */
+ betas?: Array<BetaAPI.AnthropicBeta>;
}
export namespace CompletionCreateParams {
@@ -184,7 +205,8 @@ export namespace CompletionCreateParams {
export interface CompletionCreateParamsNonStreaming extends CompletionCreateParamsBase {
/**
- * Whether to incrementally stream the response using server-sent events.
+ * Body param: Whether to incrementally stream the response using server-sent
+ * events.
*
* See [streaming](https://docs.anthropic.com/en/api/streaming) for details.
*/
@@ -193,7 +215,8 @@ export interface CompletionCreateParamsNonStreaming extends CompletionCreatePara
export interface CompletionCreateParamsStreaming extends CompletionCreateParamsBase {
/**
- * Whether to incrementally stream the response using server-sent events.
+ * Body param: Whether to incrementally stream the response using server-sent
+ * events.
*
* See [streaming](https://docs.anthropic.com/en/api/streaming) for details.
*/
diff --git src/resources/index.ts src/resources/index.ts
index d08d2619..114b9fe4 100644
--- src/resources/index.ts
+++ src/resources/index.ts
@@ -34,8 +34,10 @@ export {
type CitationContentBlockLocationParam,
type CitationPageLocation,
type CitationPageLocationParam,
+ type CitationWebSearchResultLocationParam,
type CitationsConfigParam,
type CitationsDelta,
+ type CitationsWebSearchResultLocation,
type ContentBlock,
type ContentBlockParam,
type ContentBlockSource,
@@ -63,6 +65,9 @@ export {
type RawMessageStreamEvent,
type RedactedThinkingBlock,
type RedactedThinkingBlockParam,
+ type ServerToolUsage,
+ type ServerToolUseBlock,
+ type ServerToolUseBlockParam,
type SignatureDelta,
type StopReason,
type TextBlock,
@@ -91,6 +96,15 @@ export {
type URLImageSource,
type URLPDFSource,
type Usage,
+ type WebSearchResultBlock,
+ type WebSearchResultBlockParam,
+ type WebSearchTool20250305,
+ type WebSearchToolRequestError,
+ type WebSearchToolResultBlock,
+ type WebSearchToolResultBlockContent,
+ type WebSearchToolResultBlockParam,
+ type WebSearchToolResultBlockParamContent,
+ type WebSearchToolResultError,
type MessageStreamEvent,
type MessageStartEvent,
type MessageDeltaEvent,
@@ -103,4 +117,10 @@ export {
type MessageCreateParamsStreaming,
type MessageCountTokensParams,
} from './messages/messages';
-export { ModelInfosPage, Models, type ModelInfo, type ModelListParams } from './models';
+export {
+ ModelInfosPage,
+ Models,
+ type ModelInfo,
+ type ModelRetrieveParams,
+ type ModelListParams,
+} from './models';
diff --git src/resources/messages/batches.ts src/resources/messages/batches.ts
index e188da1a..c14bc48b 100644
--- src/resources/messages/batches.ts
+++ src/resources/messages/batches.ts
@@ -20,6 +20,24 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const messageBatch = await client.messages.batches.create({
+ * requests: [
+ * {
+ * custom_id: 'my-custom-id-1',
+ * params: {
+ * max_tokens: 1024,
+ * messages: [
+ * { content: 'Hello, world', role: 'user' },
+ * ],
+ * model: 'claude-3-7-sonnet-20250219',
+ * },
+ * },
+ * ],
+ * });
+ * ```
*/
create(body: BatchCreateParams, options?: Core.RequestOptions): Core.APIPromise<MessageBatch> {
return this._client.post('/v1/messages/batches', { body, ...options });
@@ -32,6 +50,13 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const messageBatch = await client.messages.batches.retrieve(
+ * 'message_batch_id',
+ * );
+ * ```
*/
retrieve(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<MessageBatch> {
return this._client.get(`/v1/messages/batches/${messageBatchId}`, options);
@@ -43,6 +68,14 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const messageBatch of client.messages.batches.list()) {
+ * // ...
+ * }
+ * ```
*/
list(
query?: BatchListParams,
@@ -67,6 +100,12 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const deletedMessageBatch =
+ * await client.messages.batches.delete('message_batch_id');
+ * ```
*/
delete(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<DeletedMessageBatch> {
return this._client.delete(`/v1/messages/batches/${messageBatchId}`, options);
@@ -85,6 +124,13 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const messageBatch = await client.messages.batches.cancel(
+ * 'message_batch_id',
+ * );
+ * ```
*/
cancel(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<MessageBatch> {
return this._client.post(`/v1/messages/batches/${messageBatchId}/cancel`, options);
@@ -99,6 +145,12 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const messageBatchIndividualResponse =
+ * await client.messages.batches.results('message_batch_id');
+ * ```
*/
async results(
messageBatchId: string,
diff --git src/resources/messages/index.ts src/resources/messages/index.ts
index 197baf25..6ecc7f19 100644
--- src/resources/messages/index.ts
+++ src/resources/messages/index.ts
@@ -26,8 +26,10 @@ export {
type CitationContentBlockLocationParam,
type CitationPageLocation,
type CitationPageLocationParam,
+ type CitationWebSearchResultLocationParam,
type CitationsConfigParam,
type CitationsDelta,
+ type CitationsWebSearchResultLocation,
type ContentBlock,
type ContentBlockParam,
type ContentBlockSource,
@@ -53,6 +55,9 @@ export {
type RawMessageStreamEvent,
type RedactedThinkingBlock,
type RedactedThinkingBlockParam,
+ type ServerToolUsage,
+ type ServerToolUseBlock,
+ type ServerToolUseBlockParam,
, type SignatureDelta,
type StopReason,
type TextBlock,
@@ -81,6 +86,15 @@ export {
type URLImageSource,
type URLPDFSource,
type Usage,
+ type WebSearchResultBlock,
+ type WebSearchResultBlockParam,
+ type WebSearchTool20250305,
+ type WebSearchToolRequestError,
+ type WebSearchToolResultBlock,
+ type WebSearchToolResultBlockContent,
+ type WebSearchToolResultBlockParam,
+ type WebSearchToolResultBlockParamContent,
+ type WebSearchToolResultError,
type MessageStreamEvent,
type MessageStartEvent,
type MessageDeltaEvent,
diff --git src/resources/messages/messages.ts src/resources/messages/messages.ts
index c0ab4767..ce2bde21 100644
--- src/resources/messages/messages.ts
+++ src/resources/messages/messages.ts
@@ -36,6 +36,15 @@ export class Messages extends APIResource {
* conversations.
*
* Learn more about the Messages API in our [user guide](/en/docs/initial-setup)
+ *
+ * @example
+ * ```ts
+ * const message = await client.messages.create({
+ * max_tokens: 1024,
+ * messages: [{ content: 'Hello, world', role: 'user' }],
+ * model: 'claude-3-7-sonnet-20250219',
+ * });
+ * ```
*/
create(body: MessageCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<Message>;
create(
@@ -82,6 +91,15 @@ export class Messages extends APIResource {
*
* Learn more about token counting in our
* [user guide](/en/docs/build-with-claude/token-counting)
+ *
+ * @example
+ * ```ts
+ * const messageTokensCount =
+ * await client.messages.countTokens({
+ * messages: [{ content: 'string', role: 'user' }],
+ * model: 'claude-3-7-sonnet-latest',
+ * });
+ * ```
*/
countTokens(
body: MessageCountTokensParams,
@@ -195,22 +213,58 @@ export interface CitationPageLocationParam {
type: 'page_location';
}
+export interface CitationWebSearchResultLocationParam {
+ cited_text: string;
+
+ encrypted_index: string;
+
+ title: string | null;
+
+ type: 'web_search_result_location';
+
+ url: string;
+}
+
export interface CitationsConfigParam {
enabled?: boolean;
}
export interface CitationsDelta {
- citation: CitationCharLocation | CitationPageLocation | CitationContentBlockLocation;
+ citation:
+ | CitationCharLocation
+ | CitationPageLocation
+ | CitationContentBlockLocation
+ | CitationsWebSearchResultLocation;
type: 'citations_delta';
}
-export type ContentBlock = TextBlock | ToolUseBlock | ThinkingBlock | RedactedThinkingBlock;
+export interface CitationsWebSearchResultLocation {
+ cited_text: string;
+
+ encrypted_index: string;
+
+ title: string | null;
+
+ type: 'web_search_result_location';
+
+ url: string;
+}
+
+export type ContentBlock =
+ | TextBlock
+ | ToolUseBlock
+ | ServerToolUseBlock
+ | WebSearchToolResultBlock
+ | ThinkingBlock
+ | RedactedThinkingBlock;
export type ContentBlockParam =
| TextBlockParam
| ImageBlockParam
| ToolUseBlockParam
+ | ServerToolUseBlockParam
+ | WebSearchToolResultBlockParam
| ToolResultBlockParam
| DocumentBlockParam
| ThinkingBlockParam
@@ -229,6 +283,9 @@ export interface DocumentBlockParam {
type: 'document';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: CacheControlEphemeral | null;
citations?: CitationsConfigParam;
@@ -243,6 +300,9 @@ export interface ImageBlockParam {
type: 'image';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: CacheControlEphemeral | null;
}
@@ -362,13 +422,33 @@ export interface Message {
usage: Usage;
}
-export type MessageCountTokensTool = Tool | ToolBash20250124 | ToolTextEditor20250124;
+export type MessageCountTokensTool = Tool | ToolBash20250124 | ToolTextEditor20250124 | WebSearchTool20250305;
export interface MessageDeltaUsage {
+ /**
+ * The cumulative number of input tokens used to create the cache entry.
+ */
+ cache_creation_input_tokens: number | null;
+
+ /**
+ * The cumulative number of input tokens read from the cache.
+ */
+ cache_read_input_tokens: number | null;
+
+ /**
+ * The cumulative number of input tokens which were used.
+ */
+ input_tokens: number | null;
+
/**
* The cumulative number of output tokens which were used.
*/
output_tokens: number;
+
+ /**
+ * The number of server tool requests.
+ */
+ server_tool_use: ServerToolUsage | null;
}
export interface MessageParam {
@@ -454,7 +534,13 @@ export interface RawContentBlockDeltaEvent {
}
export interface RawContentBlockStartEvent {
- content_block: TextBlock | ToolUseBlock | ThinkingBlock | RedactedThinkingBlock;
+ content_block:
+ | TextBlock
+ | ToolUseBlock
+ | ServerToolUseBlock
+ | WebSearchToolResultBlock
+ | ThinkingBlock
+ | RedactedThinkingBlock;
index: number;
@@ -530,13 +616,45 @@ export interface RedactedThinkingBlockParam {
type: 'redacted_thinking';
}
+export interface ServerToolUsage {
+ /**
+ * The number of web search tool requests.
+ */
+ web_search_requests: number;
+}
+
+export interface ServerToolUseBlock {
+ id: string;
+
+ input: unknown;
+
+ name: 'web_search';
+
+ type: 'server_tool_use';
+}
+
+export interface ServerToolUseBlockParam {
+ id: string;
+
+ input: unknown;
+
+ name: 'web_search';
+
+ type: 'server_tool_use';
+
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
+ cache_control?: CacheControlEphemeral | null;
+}
+
export interface SignatureDelta {
signature: string;
type: 'signature_delta';
}
-export type StopReason = 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use';
+export type StopReason = 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | 'pause_turn' | 'refusal';
export interface TextBlock {
/**
@@ -558,17 +676,25 @@ export interface TextBlockParam {
type: 'text';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: CacheControlEphemeral | null;
citations?: Array<TextCitationParam> | null;
}
-export type TextCitation = CitationCharLocation | CitationPageLocation | CitationContentBlockLocation;
+export type TextCitation =
+ | CitationCharLocation
+ | CitationPageLocation
+ | CitationContentBlockLocation
+ | CitationsWebSearchResultLocation;
export type TextCitationParam =
| CitationCharLocationParam
| CitationPageLocationParam
- | CitationContentBlockLocationParam;
+ | CitationContentBlockLocationParam
+ | CitationWebSearchResultLocationParam;
export interface TextDelta {
text: string;
@@ -644,10 +770,13 @@ export interface Tool {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: string;
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: CacheControlEphemeral | null;
/**
@@ -659,6 +788,8 @@ export interface Tool {
* aspects of the tool input JSON schema.
*/
description?: string;
+
+ type?: 'custom' | null;
}
export namespace Tool {
@@ -681,12 +812,15 @@ export interface ToolBash20250124 {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: 'bash';
type: 'bash_20250124';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: CacheControlEphemeral | null;
}
@@ -758,6 +892,9 @@ export interface ToolResultBlockParam {
type: 'tool_result';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: CacheControlEphemeral | null;
content?: string | Array<TextBlockParam | ImageBlockParam>;
@@ -769,16 +906,19 @@ export interface ToolTextEditor20250124 {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: 'str_replace_editor';
type: 'text_editor_20250124';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: CacheControlEphemeral | null;
}
-export type ToolUnion = Tool | ToolBash20250124 | ToolTextEditor20250124;
+export type ToolUnion = Tool | ToolBash20250124 | ToolTextEditor20250124 | WebSearchTool20250305;
export interface ToolUseBlock {
id: string;
@@ -799,6 +939,9 @@ export interface ToolUseBlockParam {
type: 'tool_use';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: CacheControlEphemeral | null;
}
@@ -834,6 +977,155 @@ export interface Usage {
* The number of output tokens which were used.
*/
output_tokens: number;
+
+ /**
+ * The number of server tool requests.
+ */
+ server_tool_use: ServerToolUsage | null;
+}
+
+export interface WebSearchResultBlock {
+ encrypted_content: string;
+
+ page_age: string | null;
+
+ title: string;
+
+ type: 'web_search_result';
+
+ url: string;
+}
+
+export interface WebSearchResultBlockParam {
+ encrypted_content: string;
+
+ title: string;
+
+ type: 'web_search_result';
+
+ url: string;
+
+ page_age?: string | null;
+}
+
+export interface WebSearchTool20250305 {
+ /**
+ * Name of the tool.
+ *
+ * This is how the tool will be called by the model and in `tool_use` blocks.
+ */
+ name: 'web_search';
+
+ type: 'web_search_20250305';
+
+ /**
+ * If provided, only these domains will be included in results. Cannot be used
+ * alongside `blocked_domains`.
+ */
+ allowed_domains?: Array<string> | null;
+
+ /**
+ * If provided, these domains will never appear in results. Cannot be used
+ * alongside `allowed_domains`.
+ */
+ blocked_domains?: Array<string> | null;
+
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
+ cache_control?: CacheControlEphemeral | null;
+
+ /**
+ * Maximum number of times the tool can be used in the API request.
+ */
+ max_uses?: number | null;
+
+ /**
+ * Parameters for the user's location. Used to provide more relevant search
+ * results.
+ */
+ user_location?: WebSearchTool20250305.UserLocation | null;
+}
+
+export namespace WebSearchTool20250305 {
+ /**
+ * Parameters for the user's location. Used to provide more relevant search
+ * results.
+ */
+ export interface UserLocation {
+ type: 'approximate';
+
+ /**
+ * The city of the user.
+ */
+ city?: string | null;
+
+ /**
+ * The two letter
+ * [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the
+ * user.
+ */
+ country?: string | null;
+
+ /**
+ * The region of the user.
+ */
+ region?: string | null;
+
+ /**
+ * The [IANA timezone](https://nodatime.org/TimeZones) of the user.
+ */
+ timezone?: string | null;
+ }
+}
+
+export interface WebSearchToolRequestError {
+ error_code:
+ | 'invalid_tool_input'
+ | 'unavailable'
+ | 'max_uses_exceeded'
+ | 'too_many_requests'
+ | 'query_too_long';
+
+ type: 'web_search_tool_result_error';
+}
+
+export interface WebSearchToolResultBlock {
+ content: WebSearchToolResultBlockContent;
+
+ tool_use_id: string;
+
+ type: 'web_search_tool_result';
+}
+
+export type WebSearchToolResultBlockContent = WebSearchToolResultError | Array<WebSearchResultBlock>;
+
+export interface WebSearchToolResultBlockParam {
+ content: WebSearchToolResultBlockParamContent;
+
+ tool_use_id: string;
+
+ type: 'web_search_tool_result';
+
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
+ cache_control?: CacheControlEphemeral | null;
+}
+
+export type WebSearchToolResultBlockParamContent =
+ | Array<WebSearchResultBlockParam>
+ | WebSearchToolRequestError;
+
+export interface WebSearchToolResultError {
+ error_code:
+ | 'invalid_tool_input'
+ | 'unavailable'
+ | 'max_uses_exceeded'
+ | 'too_many_requests'
+ | 'query_too_long';
+
+ type: 'web_search_tool_result_error';
}
export type MessageStreamEvent = RawMessageStreamEvent;
@@ -951,6 +1243,8 @@ export interface MessageCreateParamsBase {
* [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use
* the top-level `system` parameter β there is no `"system"` role for input
* messages in the Messages API.
+ *
+ * There is a limit of 100000 messages in a single request.
*/
messages: Array<MessageParam>;
@@ -1260,6 +1554,8 @@ export interface MessageCountTokensParams {
* [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use
* the top-level `system` parameter β there is no `"system"` role for input
* messages in the Messages API.
+ *
+ * There is a limit of 100000 messages in a single request.
*/
messages: Array<MessageParam>;
@@ -1386,8 +1682,10 @@ export declare namespace Messages {
type CitationContentBlockLocationParam as CitationContentBlockLocationParam,
type CitationPageLocation as CitationPageLocation,
type CitationPageLocationParam as CitationPageLocationParam,
+ type CitationWebSearchResultLocationParam as CitationWebSearchResultLocationParam,
type CitationsConfigParam as CitationsConfigParam,
type CitationsDelta as CitationsDelta,
+ type CitationsWebSearchResultLocation as CitationsWebSearchResultLocation,
type ContentBlock as ContentBlock,
type ContentBlockParam as ContentBlockParam,
type ContentBlockSource as ContentBlockSource,
@@ -1414,6 +1712,9 @@ export declare namespace Messages {
type RawMessageStreamEvent as RawMessageStreamEvent,
type RedactedThinkingBlock as RedactedThinkingBlock,
type RedactedThinkingBlockParam as RedactedThinkingBlockParam,
+ type ServerToolUsage as ServerToolUsage,
+ type ServerToolUseBlock as ServerToolUseBlock,
+ type ServerToolUseBlockParam as ServerToolUseBlockParam,
type SignatureDelta as SignatureDelta,
type StopReason as StopReason,
type TextBlock as TextBlock,
@@ -1442,6 +1743,15 @@ export declare namespace Messages {
type URLImageSource as URLImageSource,
type URLPDFSource as URLPDFSource,
type Usage as Usage,
+ type WebSearchResultBlock as WebSearchResultBlock,
+ type WebSearchResultBlockParam as WebSearchResultBlockParam,
+ type WebSearchTool20250305 as WebSearchTool20250305,
+ type WebSearchToolRequestError as WebSearchToolRequestError,
+ type WebSearchToolResultBlock as WebSearchToolResultBlock,
+ type WebSearchToolResultBlockContent as WebSearchToolResultBlockContent,
+ type WebSearchToolResultBlockParam as WebSearchToolResultBlockParam,
+ type WebSearchToolResultBlockParamContent as WebSearchToolResultBlockParamContent,
+ type WebSearchToolResultError as WebSearchToolResultError,
type MessageStreamEvent as MessageStreamEvent,
type MessageStartEvent as MessageStartEvent,
type MessageDeltaEvent as MessageDeltaEvent,
diff --git src/resources/models.ts src/resources/models.ts
index 50e80399..68491b3e 100644
--- src/resources/models.ts
+++ src/resources/models.ts
@@ -3,6 +3,7 @@
import { APIResource } from '../resource';
import { isRequestOptions } from '../core';
import * as Core from '../core';
+import * as BetaAPI from './beta/beta';
import { Page, type PageParams } from '../pagination';
export class Models extends APIResource {
@@ -12,8 +13,28 @@ export class Models extends APIResource {
* The Models API response can be used to determine information about a specific
* model or resolve a model alias to a model ID.
*/
- retrieve(modelId: string, options?: Core.RequestOptions): Core.APIPromise<ModelInfo> {
- return this._client.get(`/v1/models/${modelId}`, options);
+ retrieve(
+ modelId: string,
+ params?: ModelRetrieveParams,
+ options?: Core.RequestOptions,
+ ): Core.APIPromise<ModelInfo>;
+ retrieve(modelId: string, options?: Core.RequestOptions): Core.APIPromise<ModelInfo>;
+ retrieve(
+ modelId: string,
+ params: ModelRetrieveParams | Core.RequestOptions = {},
+ options?: Core.RequestOptions,
+ ): Core.APIPromise<ModelInfo> {
+ if (isRequestOptions(params)) {
+ return this.retrieve(modelId, {}, params);
+ }
+ const { betas } = params;
+ return this._client.get(`/v1/models/${modelId}`, {
+ ...options,
+ headers: {
+ ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined),
+ ...options?.headers,
+ },
+ });
}
/**
@@ -22,16 +43,24 @@ export class Models extends APIResource {
* The Models API response can be used to determine which models are available for
* use in the API. More recently released models are listed first.
*/
- list(query?: ModelListParams, options?: Core.RequestOptions): Core.PagePromise<ModelInfosPage, ModelInfo>;
+ list(params?: ModelListParams, options?: Core.RequestOptions): Core.PagePromise<ModelInfosPage, ModelInfo>;
list(options?: Core.RequestOptions): Core.PagePromise<ModelInfosPage, ModelInfo>;
list(
- query: ModelListParams | Core.RequestOptions = {},
+ params: ModelListParams | Core.RequestOptions = {},
options?: Core.RequestOptions,
): Core.PagePromise<ModelInfosPage, ModelInfo> {
- if (isRequestOptions(query)) {
- return this.list({}, query);
+ if (isRequestOptions(params)) {
+ return this.list({}, params);
}
- return this._client.getAPIList('/v1/models', ModelInfosPage, { query, ...options });
+ const { betas, ...query } = params;
+ return this._client.getAPIList('/v1/models', ModelInfosPage, {
+ query,
+ ...options,
+ headers: {
+ ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined),
+ ...options?.headers,
+ },
+ });
}
}
@@ -62,7 +91,19 @@ export interface ModelInfo {
type: 'model';
}
-export interface ModelListParams extends PageParams {}
+export interface ModelRetrieveParams {
+ /**
+ * Optional header to specify the beta version(s) you want to use.
+ */
+ betas?: Array<BetaAPI.AnthropicBeta>;
+}
+
+export interface ModelListParams extends PageParams {
+ /**
+ * Header param: Optional header to specify the beta version(s) you want to use.
+ */
+ betas?: Array<BetaAPI.AnthropicBeta>;
+}
Models.ModelInfosPage = ModelInfosPage;
@@ -70,6 +111,7 @@ export declare namespace Models {
export {
type ModelInfo as ModelInfo,
ModelInfosPage as ModelInfosPage,
+ type ModelRetrieveParams as ModelRetrieveParams,
type ModelListParams as ModelListParams,
};
}
diff --git src/version.ts src/version.ts
index e88a3c67..2f1576d5 100644
--- src/version.ts
+++ src/version.ts
@@ -1 +1 @@
-export const VERSION = '0.40.1'; // x-release-please-version
+export const VERSION = '0.41.0'; // x-release-please-version
diff --git tests/api-resources/MessageStream.test.ts tests/api-resources/MessageStream.test.ts
index 0788821a..d1912561 100644
--- tests/api-resources/MessageStream.test.ts
+++ tests/api-resources/MessageStream.test.ts
@@ -32,6 +32,19 @@ async function* messageIterable(message: Message): AsyncGenerator<MessageStreamE
}
: content.type === 'thinking' ? { type: 'thinking', thinking: '', signature: '' }
: content.type === 'redacted_thinking' ? { type: 'redacted_thinking', data: '' }
+ : content.type === 'server_tool_use' ?
+ {
+ type: 'server_tool_use',
+ id: 'toolu_01Up7oRoHeGvhded7n66nPzP',
+ name: 'web_search',
+ input: {},
+ }
+ : content.type === 'web_search_tool_result' ?
+ {
+ type: 'web_search_tool_result',
+ tool_use_id: 'toolu_01Up7oRoHeGvhded7n66nPzP',
+ content: [],
+ }
: assertNever(content),
index: idx,
};
@@ -58,6 +71,10 @@ async function* messageIterable(message: Message): AsyncGenerator<MessageStreamE
throw new Error('thinking not implemented yet');
} else if (content.type === 'redacted_thinking') {
throw new Error('redacted_thinking not implemented yet');
+ } else if (content.type === 'server_tool_use') {
+ throw new Error('server_tool_use not implemented yet');
+ } else if (content.type === 'web_search_tool_result') {
+ throw new Error('web_search_tool_result not implemented yet');
} else {
assertNever(content);
}
@@ -70,7 +87,13 @@ async function* messageIterable(message: Message): AsyncGenerator<MessageStreamE
yield {
type: 'message_delta',
- usage: { output_tokens: 6 },
+ usage: {
+ output_tokens: 6,
+ input_tokens: null,
+ cache_creation_input_tokens: null,
+ cache_read_input_tokens: null,
+ server_tool_use: null,
+ },
// @ts-ignore
delta: { stop_reason: message.stop_reason, stop_sequence: message.stop_sequence },
};
@@ -160,6 +183,7 @@ describe('MessageStream class', () => {
input_tokens: 10,
cache_creation_input_tokens: null,
cache_read_input_tokens: null,
+ server_tool_use: null,
},
}),
);
@@ -220,22 +244,22 @@ describe('MessageStream class', () => {
},
{
"args": [
- "{"type":"message_start","message":{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}}",
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message_start","message":{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "streamEvent",
},
{
"args": [
"{"type":"content_block_start","content_block":{"type":"text","text":"","citations":null},"index":0}",
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "streamEvent",
},
{
"args": [
"{"type":"content_block_delta","delta":{"type":"text_delta","text":"Hello"},"index":0}",
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "streamEvent",
},
@@ -249,7 +273,7 @@ describe('MessageStream class', () => {
{
"args": [
"{"type":"content_block_delta","delta":{"type":"text_delta","text":" ther"},"index":0}",
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello ther","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello ther","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "streamEvent",
},
@@ -263,7 +287,7 @@ describe('MessageStream class', () => {
{
"args": [
"{"type":"content_block_delta","delta":{"type":"text_delta","text":"e!"},"index":0}",
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "streamEvent",
},
@@ -277,7 +301,7 @@ describe('MessageStream class', () => {
{
"args": [
"{"type":"content_block_stop","index":0}",
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "streamEvent",
},
@@ -289,27 +313,27 @@ describe('MessageStream class', () => {
},
{
"args": [
- "{"type":"message_delta","usage":{"output_tokens":6},"delta":{"stop_reason":"end_turn","stop_sequence":null}}",
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":"end_turn","stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message_delta","usage":{"output_tokens":6,"input_tokens":null,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null},"delta":{"stop_reason":"end_turn","stop_sequence":null}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":"end_turn","stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "streamEvent",
},
{
"args": [
"{"type":"message_stop"}",
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":"end_turn","stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":"end_turn","stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "streamEvent",
},
{
"args": [
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":"end_turn","stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":"end_turn","stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "message",
},
{
"args": [
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":"end_turn","stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":"end_turn","stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "finalMessage",
},
@@ -342,6 +366,7 @@ describe('MessageStream class', () => {
"cache_read_input_tokens": null,
"input_tokens": 10,
"output_tokens": 6,
+ "server_tool_use": null,
},
}
`);
@@ -372,6 +397,7 @@ describe('MessageStream class', () => {
input_tokens: 10,
cache_creation_input_tokens: null,
cache_read_input_tokens: null,
+ server_tool_use: null,
},
}),
);
@@ -399,7 +425,7 @@ describe('MessageStream class', () => {
const stream = anthropic.messages.stream(
{
max_tokens: 1024,
- model: 'claude-2.1',
+ model: 'claude-3-7-sonnet-20250219',
messages: [{ role: 'user', content: 'Say hello there!' }],
},
{ maxRetries: 0 },
@@ -424,7 +450,7 @@ describe('MessageStream class', () => {
const stream = anthropic.messages.stream(
{
max_tokens: 1024,
- model: 'claude-2.1',
+ model: 'claude-3-7-sonnet-20250219',
messages: [{ role: 'user', content: 'Say hello there!' }],
},
{ maxRetries: 0 },
diff --git tests/api-resources/beta/models.test.ts tests/api-resources/beta/models.test.ts
index f155b632..ce7c72ab 100644
--- tests/api-resources/beta/models.test.ts
+++ tests/api-resources/beta/models.test.ts
@@ -27,6 +27,13 @@ describe('resource models', () => {
).rejects.toThrow(Anthropic.NotFoundError);
});
+ test('retrieve: request options and params are passed correctly', async () => {
+ // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error
+ await expect(
+ client.beta.models.retrieve('model_id', { betas: ['string'] }, { path: '/_stainless_unknown_path' }),
+ ).rejects.toThrow(Anthropic.NotFoundError);
+ });
+
test('list', async () => {
const responsePromise = client.beta.models.list();
const rawResponse = await responsePromise.asResponse();
@@ -49,7 +56,7 @@ describe('resource models', () => {
// ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error
await expect(
client.beta.models.list(
- { after_id: 'after_id', before_id: 'before_id', limit: 1 },
+ { after_id: 'after_id', before_id: 'before_id', limit: 1, betas: ['string'] },
{ path: '/_stainless_unknown_path' },
),
).rejects.toThrow(Anthropic.NotFoundError);
diff --git tests/api-resources/completions.test.ts tests/api-resources/completions.test.ts
index e3ebaa07..b372e474 100644
--- tests/api-resources/completions.test.ts
+++ tests/api-resources/completions.test.ts
@@ -35,6 +35,7 @@ describe('resource completions', () => {
temperature: 1,
top_k: 5,
top_p: 0.7,
+ betas: ['string'],
});
});
});
diff --git tests/api-resources/messages/batches.test.ts tests/api-resources/messages/batches.test.ts
index 95712a32..7c58ca3c 100644
--- tests/api-resources/messages/batches.test.ts
+++ tests/api-resources/messages/batches.test.ts
@@ -77,6 +77,7 @@ describe('resource batches', () => {
name: 'name',
cache_control: { type: 'ephemeral' },
description: 'Get the current weather in a given location',
+ type: 'custom',
},
],
top_k: 5,
diff --git tests/api-resources/messages/messages.test.ts tests/api-resources/messages/messages.test.ts
index 051a2c4f..b9b7bbc2 100644
--- tests/api-resources/messages/messages.test.ts
+++ tests/api-resources/messages/messages.test.ts
@@ -64,6 +64,7 @@ describe('resource messages', () => {
name: 'name',
cache_control: { type: 'ephemeral' },
description: 'Get the current weather in a given location',
+ type: 'custom',
},
],
top_k: 5,
@@ -120,6 +121,7 @@ describe('resource messages', () => {
name: 'name',
cache_control: { type: 'ephemeral' },
description: 'Get the current weather in a given location',
+ type: 'custom',
},
],
});
diff --git tests/api-resources/models.test.ts tests/api-resources/models.test.ts
index 7f5c0411..dc73dc26 100644
--- tests/api-resources/models.test.ts
+++ tests/api-resources/models.test.ts
@@ -27,6 +27,13 @@ describe('resource models', () => {
);
});
+ test('retrieve: request options and params are passed correctly', async () => {
+ // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error
+ await expect(
+ client.models.retrieve('model_id', { betas: ['string'] }, { path: '/_stainless_unknown_path' }),
+ ).rejects.toThrow(Anthropic.NotFoundError);
+ });
+
test('list', async () => {
const responsePromise = client.models.list();
const rawResponse = await responsePromise.asResponse();
@@ -49,7 +56,7 @@ describe('resource models', () => {
// ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error
await expect(
client.models.list(
- { after_id: 'after_id', before_id: 'before_id', limit: 1 },
+ { after_id: 'after_id', before_id: 'before_id', limit: 1, betas: ['string'] },
{ path: '/_stainless_unknown_path' },
),
).rejects.toThrow(Anthropic.NotFoundError);
Description
This pull request (PR) introduces several modifications aimed at adding new features, improving documentation, upgrading workflows, and fixing issues in the project. The main changes include adding support for web search capabilities in the Claude API, updating node version in CI workflows, revising documentation, and extending existing types and interfaces.
Possible Issues
- Backward Compatibility: Changing the node version from 18 to 20 may cause compatibility issues for developers or environments still using the older version.
- Incomplete Tests: While there are some tests, the changes related to new features such as web search might require additional test cases to ensure functionality and coverage.
- Documentation Sync: Ensuring that all documentation references and links are up-to-date to reflect the new features and changes.
Security Hotspots
- Web Search Tool: Processing user inputs to perform web searches can be a potential security risk if not handled appropriately. Ensure proper validation and sanitization of user inputs to prevent injection attacks, malicious URL fetches, and other security vulnerabilities.
Changes
Changes
Filename: .github/workflows/ci.yml
- node-version: '18'
+ node-version: '20'
Filename: .github/workflows/publish-npm.yml
- node-version: '18'
+ node-version: '20'
Filename: .release-please-manifest.json
- ".": "0.40.1",
+ ".": "0.41.0",
Filename: .stats.yml
-openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/anthropic%2Fanthropic-ea0576fceb17a0976feca9aa03aa426984d6fe1390f2bcdbf9de0212a81c8334.yml
-openapi_spec_hash: d2d7ec2a7a35a1ed2443c3b690c802c4
-config_hash: 9d5b992847099d8fe5a5c09e66adbe5f
+openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/anthropic%2Fanthropic-7015ea2d98991d6c2e7931c521e36448778fe868cc1b8a21173898d67b14b819.yml
+openapi_spec_hash: 2007ff815a3f39af8cebe1976d50f17d
+config_hash: 4d0dcf47d77eae22d34624d2ac0f0b46
Filename: CHANGELOG.md
+## 0.41.0 (2025-05-07)
+
+Full Changelog: [sdk-v0.40.1...sdk-v0.41.0](https://github.com/anthropics/anthropic-sdk-typescript/compare/sdk-v0.40.1...sdk-v0.41.0)
+
+### Features
+
+* **api:** adds web search capabilities to the Claude API ([fae7e52](https://github.com/anthropics/anthropic-sdk-typescript/commit/fae7e521568d9659e376d13c4e4a6c320b13b1d4))
+
Filename: README.md
-## Tool use beta
+## Tool use
Filename: api.md
- <code><a href="./src/resources/messages/messages.ts">CitationContentBlockLocationParam</a></code>
- <code><a href="./src/resources/messages/messages.ts">CitationPageLocation</a></code>
+ <code><a href="./src/resources/messages/messages.ts">CitationWebSearchResultLocationParam</a></code>
- <code><a href="./src/resources/messages/messages.ts">CitationsConfigParam</a></code>
+ ... [Adding several new types]
Filename: examples/tools.ts
- content: [{ type: 'text', text: 'The weather is 73f' }],
+ content: 'The weather is 73f',
Filename: examples/web-search-stream.ts (New File)
+#!/usr/bin/env -S npm run tsn -T
+import Anthropic from '@anthropic-ai/sdk';
+const client = new Anthropic();
+async function main() {
+ console.log('Claude with Web Search (Streaming)');
...
+main().catch(console.error);
Filename: examples/web-search.ts [New File]
+#!/usr/bin/env -S npm run tsn -T
+import Anthropic from '@anthropic-ai/sdk';
+const client = new Anthropic();
+async function main() {
+ console.log('Web Search Example');
...
+main().catch(console.error);
Filename: package.json
- "version": "0.40.1",
+ "version": "0.41.0",
Filename: src/index.ts
+import { ModelInfo, ModelInfosPage, ModelListParams, ModelRetrieveParams, Models } from './resources/models';
+... [More types added, changes related to web search]
Filename: src/lib/BetaMessageStream.ts
+ snapshot.usage.server_tool_use = event.usage.server_tool_use;
... [Handling cases for new events]
sequenceDiagram
participant User
participant Client
participant API
User->>Client: Request "create message with web_search enabled"
Client->>API: Forward request
API-->>Client: Response with search results
Client-->>User: Display results
Overall, this PR offers valuable enhancements and brings new features to the SDK. Ensure that backward compatibility and security are thoroughly assessed and validated before merging.
bedrock debug - [puLL-Merge] - anthropics/[email protected]
Diff
diff --git .github/workflows/ci.yml .github/workflows/ci.yml
index f2f42e06..a021391c 100644
--- .github/workflows/ci.yml
+++ .github/workflows/ci.yml
@@ -72,7 +72,7 @@ jobs:
- name: Set up Node
uses: actions/setup-node@v4
with:
- node-version: '18'
+ node-version: '20'
- name: Bootstrap
run: ./scripts/bootstrap
diff --git .github/workflows/publish-npm.yml .github/workflows/publish-npm.yml
index b18decdf..7be59d8e 100644
--- .github/workflows/publish-npm.yml
+++ .github/workflows/publish-npm.yml
@@ -20,7 +20,7 @@ jobs:
- name: Set up Node
uses: actions/setup-node@v4
with:
- node-version: '18'
+ node-version: '20'
- name: Install dependencies
run: |
diff --git .release-please-manifest.json .release-please-manifest.json
index d2fc4414..5ee5f3b3 100644
--- .release-please-manifest.json
+++ .release-please-manifest.json
@@ -1,5 +1,5 @@
{
- ".": "0.40.1",
+ ".": "0.41.0",
"packages/vertex-sdk": "0.7.0",
"packages/bedrock-sdk": "0.12.6"
}
diff --git .stats.yml .stats.yml
index 30b9556d..5aa47f53 100644
--- .stats.yml
+++ .stats.yml
@@ -1,4 +1,4 @@
configured_endpoints: 21
-openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/anthropic%2Fanthropic-ea0576fceb17a0976feca9aa03aa426984d6fe1390f2bcdbf9de0212a81c8334.yml
-openapi_spec_hash: d2d7ec2a7a35a1ed2443c3b690c802c4
-config_hash: 9d5b992847099d8fe5a5c09e66adbe5f
+openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/anthropic%2Fanthropic-7015ea2d98991d6c2e7931c521e36448778fe868cc1b8a21173898d67b14b819.yml
+openapi_spec_hash: 2007ff815a3f39af8cebe1976d50f17d
+config_hash: 4d0dcf47d77eae22d34624d2ac0f0b46
diff --git CHANGELOG.md CHANGELOG.md
index 85f0e40f..53bbc93d 100644
--- CHANGELOG.md
+++ CHANGELOG.md
@@ -1,5 +1,24 @@
# Changelog
+## 0.41.0 (2025-05-07)
+
+Full Changelog: [sdk-v0.40.1...sdk-v0.41.0](https://github.com/anthropics/anthropic-sdk-typescript/compare/sdk-v0.40.1...sdk-v0.41.0)
+
+### Features
+
+* **api:** adds web search capabilities to the Claude API ([fae7e52](https://github.com/anthropics/anthropic-sdk-typescript/commit/fae7e521568d9659e376d13c4e4a6c320b13b1d4))
+
+
+### Chores
+
+* **ci:** bump node version for release workflows ([3502747](https://github.com/anthropics/anthropic-sdk-typescript/commit/350274792ed3d9b7ea237ee60876883373344016))
+
+
+### Documentation
+
+* add examples to tsdocs ([19a9285](https://github.com/anthropics/anthropic-sdk-typescript/commit/19a928512b1616f2cac9c82f02e7bd9a158dab95))
+* **readme:** fix typo ([735574e](https://github.com/anthropics/anthropic-sdk-typescript/commit/735574e23b7956cbfd0c05d0374079391d5d4e96))
+
## 0.40.1 (2025-04-28)
Full Changelog: [sdk-v0.40.0...sdk-v0.40.1](https://github.com/anthropics/anthropic-sdk-typescript/compare/sdk-v0.40.0...sdk-v0.40.1)
diff --git README.md README.md
index cafba323..9e6e15bb 100644
--- README.md
+++ README.md
@@ -183,9 +183,9 @@ for await (const entry of results) {
}
```
-## Tool use beta
+## Tool use
-This SDK provides beta support for tool use, aka function calling. More details can be found in [the documentation](https://docs.anthropic.com/claude/docs/tool-use).
+This SDK provides support for tool use, aka function calling. More details can be found in [the documentation](https://docs.anthropic.com/claude/docs/tool-use).
## AWS Bedrock
@@ -220,7 +220,7 @@ async function main() {
main();
```
-Error codes are as followed:
+Error codes are as follows:
| Status Code | Error Type |
| ----------- | -------------------------- |
diff --git api.md api.md
index 2010bc5f..78a2bac0 100644
--- api.md
+++ api.md
@@ -29,8 +29,10 @@ Types:
- <code><a href="./src/resources/messages/messages.ts">CitationContentBlockLocationParam</a></code>
- <code><a href="./src/resources/messages/messages.ts">CitationPageLocation</a></code>
- <code><a href="./src/resources/messages/messages.ts">CitationPageLocationParam</a></code>
+- <code><a href="./src/resources/messages/messages.ts">CitationWebSearchResultLocationParam</a></code>
- <code><a href="./src/resources/messages/messages.ts">CitationsConfigParam</a></code>
- <code><a href="./src/resources/messages/messages.ts">CitationsDelta</a></code>
+- <code><a href="./src/resources/messages/messages.ts">CitationsWebSearchResultLocation</a></code>
- <code><a href="./src/resources/messages/messages.ts">ContentBlock</a></code>
- <code><a href="./src/resources/messages/messages.ts">ContentBlockParam</a></code>
- <code><a href="./src/resources/messages/messages.ts">ContentBlockSource</a></code>
@@ -56,6 +58,9 @@ Types:
- <code><a href="./src/resources/messages/messages.ts">RawMessageStreamEvent</a></code>
- <code><a href="./src/resources/messages/messages.ts">RedactedThinkingBlock</a></code>
- <code><a href="./src/resources/messages/messages.ts">RedactedThinkingBlockParam</a></code>
+- <code><a href="./src/resources/messages/messages.ts">ServerToolUsage</a></code>
+- <code><a href="./src/resources/messages/messages.ts">ServerToolUseBlock</a></code>
+- <code><a href="./src/resources/messages/messages.ts">ServerToolUseBlockParam</a></code>
- <code><a href="./src/resources/messages/messages.ts">SignatureDelta</a></code>
- <code><a href="./src/resources/messages/messages.ts">StopReason</a></code>
- <code><a href="./src/resources/messages/messages.ts">TextBlock</a></code>
@@ -84,6 +89,15 @@ Types:
- <code><a href="./src/resources/messages/messages.ts">URLImageSource</a></code>
- <code><a href="./src/resources/messages/messages.ts">URLPDFSource</a></code>
- <code><a href="./src/resources/messages/messages.ts">Usage</a></code>
+- <code><a href="./src/resources/messages/messages.ts">WebSearchResultBlock</a></code>
+- <code><a href="./src/resources/messages/messages.ts">WebSearchResultBlockParam</a></code>
+- <code><a href="./src/resources/messages/messages.ts">WebSearchTool20250305</a></code>
+- <code><a href="./src/resources/messages/messages.ts">WebSearchToolRequestError</a></code>
+- <code><a href="./src/resources/messages/messages.ts">WebSearchToolResultBlock</a></code>
+- <code><a href="./src/resources/messages/messages.ts">WebSearchToolResultBlockContent</a></code>
+- <code><a href="./src/resources/messages/messages.ts">WebSearchToolResultBlockParam</a></code>
+- <code><a href="./src/resources/messages/messages.ts">WebSearchToolResultBlockParamContent</a></code>
+- <code><a href="./src/resources/messages/messages.ts">WebSearchToolResultError</a></code>
- <code><a href="./src/resources/messages/messages.ts">MessageStreamEvent</a></code>
- <code><a href="./src/resources/messages/messages.ts">MessageStartEvent</a></code>
- <code><a href="./src/resources/messages/messages.ts">MessageDeltaEvent</a></code>
@@ -129,7 +143,7 @@ Types:
Methods:
-- <code title="get /v1/models/{model_id}">client.models.<a href="./src/resources/models.ts">retrieve</a>(modelId) -> ModelInfo</code>
+- <code title="get /v1/models/{model_id}">client.models.<a href="./src/resources/models.ts">retrieve</a>(modelId, { ...params }) -> ModelInfo</code>
- <code title="get /v1/models">client.models.<a href="./src/resources/models.ts">list</a>({ ...params }) -> ModelInfosPage</code>
# Beta
@@ -157,7 +171,7 @@ Types:
Methods:
-- <code title="get /v1/models/{model_id}?beta=true">client.beta.models.<a href="./src/resources/beta/models.ts">retrieve</a>(modelId) -> BetaModelInfo</code>
+- <code title="get /v1/models/{model_id}?beta=true">client.beta.models.<a href="./src/resources/beta/models.ts">retrieve</a>(modelId, { ...params }) -> BetaModelInfo</code>
- <code title="get /v1/models?beta=true">client.beta.models.<a href="./src/resources/beta/models.ts">list</a>({ ...params }) -> BetaModelInfosPage</code>
## Messages
@@ -174,8 +188,10 @@ Types:
- <code><a href="./src/resources/beta/messages/messages.ts">BetaCitationContentBlockLocationParam</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaCitationPageLocation</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaCitationPageLocationParam</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaCitationWebSearchResultLocationParam</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaCitationsConfigParam</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaCitationsDelta</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaCitationsWebSearchResultLocation</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaContentBlock</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaContentBlockParam</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaContentBlockSource</a></code>
@@ -198,6 +214,9 @@ Types:
- <code><a href="./src/resources/beta/messages/messages.ts">BetaRawMessageStreamEvent</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaRedactedThinkingBlock</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaRedactedThinkingBlockParam</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaServerToolUsage</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaServerToolUseBlock</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaServerToolUseBlockParam</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaSignatureDelta</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaStopReason</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaTextBlock</a></code>
@@ -230,6 +249,15 @@ Types:
- <code><a href="./src/resources/beta/messages/messages.ts">BetaURLImageSource</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaURLPDFSource</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaUsage</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaWebSearchResultBlock</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaWebSearchResultBlockParam</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaWebSearchTool20250305</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaWebSearchToolRequestError</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaWebSearchToolResultBlock</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaWebSearchToolResultBlockContent</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaWebSearchToolResultBlockParam</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaWebSearchToolResultBlockParamContent</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaWebSearchToolResultError</a></code>
Methods:
diff --git examples/tools.ts examples/tools.ts
index 1a696bc0..8928efb0 100644
--- examples/tools.ts
+++ examples/tools.ts
@@ -49,7 +49,7 @@ async function main() {
{
type: 'tool_result',
tool_use_id: tool.id,
- content: [{ type: 'text', text: 'The weather is 73f' }],
+ content: 'The weather is 73f',
},
],
},
diff --git a/examples/web-search-stream.ts b/examples/web-search-stream.ts
new file mode 100755
index 00000000..38d08d46
--- /dev/null
+++ examples/web-search-stream.ts
@@ -0,0 +1,64 @@
+#!/usr/bin/env -S npm run tsn -T
+
+import Anthropic from '@anthropic-ai/sdk';
+
+const client = new Anthropic();
+
+async function main() {
+ console.log('Claude with Web Search (Streaming)');
+ console.log('==================================');
+
+ // Create a stream with web search enabled
+ const stream = client.messages
+ .stream({
+ model: 'claude-3-5-sonnet-latest',
+ max_tokens: 1024,
+ messages: [
+ {
+ role: 'user',
+ content: "What's the weather in New York?",
+ },
+ ],
+ tools: [
+ {
+ name: 'web_search',
+ type: 'web_search_20250305',
+ },
+ ],
+ })
+ .on('text', (text) => {
+ // Print text as it arrives
+ process.stdout.write(text);
+ })
+ .on('streamEvent', (event) => {
+ // Track when web search is being used
+ if (event.type === 'content_block_start' && event.content_block.type === 'web_search_tool_result') {
+ process.stdout.write('\n[Web search started...]');
+ }
+ });
+
+ // Wait for the stream to complete
+ const message = await stream.finalMessage();
+
+ console.log('\n\nFinal usage statistics:');
+ console.log(`Input tokens: ${message.usage.input_tokens}`);
+ console.log(`Output tokens: ${message.usage.output_tokens}`);
+
+ if (message.usage.server_tool_use) {
+ console.log(`Web search requests: ${message.usage.server_tool_use.web_search_requests}`);
+ } else {
+ console.log('No web search requests recorded in usage');
+ }
+
+ // Display message content types for debugging
+ console.log('\nMessage Content Types:');
+ message.content.forEach((block, i) => {
+ console.log(`Content Block ${i + 1}: Type = ${block.type}`);
+ });
+
+ // Show full message for debugging
+ console.log('\nComplete message structure:');
+ console.dir(message, { depth: 4 });
+}
+
+main().catch(console.error);
diff --git a/examples/web-search.ts b/examples/web-search.ts
new file mode 100755
index 00000000..e5c528ac
--- /dev/null
+++ examples/web-search.ts
@@ -0,0 +1,52 @@
+#!/usr/bin/env -S npm run tsn -T
+
+import Anthropic from '@anthropic-ai/sdk';
+
+const client = new Anthropic();
+
+async function main() {
+ console.log('Web Search Example');
+ console.log('=================');
+
+ // Create a message with web search enabled
+ const message = await client.messages.create({
+ model: 'claude-3-5-sonnet-latest',
+ max_tokens: 1024,
+ messages: [
+ {
+ role: 'user',
+ content:
+ "What's the current weather in San Francisco? Please search the web for up-to-date information.",
+ },
+ ],
+ tools: [
+ {
+ name: 'web_search',
+ type: 'web_search_20250305',
+ },
+ ],
+ });
+
+ // Print the full response
+ console.log('\nFull response:');
+ console.dir(message, { depth: 4 });
+
+ // Extract and print the content
+ console.log('\nResponse content:');
+ for (const contentBlock of message.content) {
+ if (contentBlock.type === 'text') {
+ console.log(contentBlock.text);
+ }
+ }
+
+ // Print usage information
+ console.log('\nUsage statistics:');
+ console.log(`Input tokens: ${message.usage.input_tokens}`);
+ console.log(`Output tokens: ${message.usage.output_tokens}`);
+
+ if (message.usage.server_tool_use) {
+ console.log(`Web search requests: ${message.usage.server_tool_use.web_search_requests}`);
+ }
+}
+
+main().catch(console.error);
diff --git package.json package.json
index 898d950c..451b1d7b 100644
--- package.json
+++ package.json
@@ -1,6 +1,6 @@
{
"name": "@anthropic-ai/sdk",
- "version": "0.40.1",
+ "version": "0.41.0",
"description": "The official TypeScript library for the Anthropic API",
"author": "Anthropic <[email protected]>",
"types": "dist/index.d.ts",
diff --git src/index.ts src/index.ts
index 3d901bea..ccfa494e 100644
--- src/index.ts
+++ src/index.ts
@@ -14,7 +14,7 @@ import {
CompletionCreateParamsStreaming,
Completions,
} from './resources/completions';
-import { ModelInfo, ModelInfosPage, ModelListParams, Models } from './resources/models';
+import { ModelInfo, ModelInfosPage, ModelListParams, ModelRetrieveParams, Models } from './resources/models';
import {
AnthropicBeta,
Beta,
@@ -40,8 +40,10 @@ import {
CitationContentBlockLocationParam,
CitationPageLocation,
CitationPageLocationParam,
+ CitationWebSearchResultLocationParam,
CitationsConfigParam,
CitationsDelta,
+ CitationsWebSearchResultLocation,
ContentBlock,
ContentBlockDeltaEvent,
ContentBlockParam,
@@ -80,6 +82,9 @@ import {
RawMessageStreamEvent,
RedactedThinkingBlock,
RedactedThinkingBlockParam,
+ ServerToolUsage,
+ ServerToolUseBlock,
+ ServerToolUseBlockParam,
SignatureDelta,
StopReason,
TextBlock,
@@ -108,6 +113,15 @@ import {
URLImageSource,
URLPDFSource,
Usage,
+ WebSearchResultBlock,
+ WebSearchResultBlockParam,
+ WebSearchTool20250305,
+ WebSearchToolRequestError,
+ WebSearchToolResultBlock,
+ WebSearchToolResultBlockContent,
+ WebSearchToolResultBlockParam,
+ WebSearchToolResultBlockParamContent,
+ WebSearchToolResultError,
} from './resources/messages/messages';
export interface ClientOptions {
@@ -354,8 +368,10 @@ export declare namespace Anthropic {
type CitationContentBlockLocationParam as CitationContentBlockLocationParam,
type CitationPageLocation as CitationPageLocation,
type CitationPageLocationParam as CitationPageLocationParam,
+ type CitationWebSearchResultLocationParam as CitationWebSearchResultLocationParam,
type CitationsConfigParam as CitationsConfigParam,
type CitationsDelta as CitationsDelta,
+ type CitationsWebSearchResultLocation as CitationsWebSearchResultLocation,
type ContentBlock as ContentBlock,
type ContentBlockParam as ContentBlockParam,
type ContentBlockSource as ContentBlockSource,
@@ -381,6 +397,9 @@ export declare namespace Anthropic {
type RawMessageStreamEvent as RawMessageStreamEvent,
type RedactedThinkingBlock as RedactedThinkingBlock,
type RedactedThinkingBlockParam as RedactedThinkingBlockParam,
+ type ServerToolUsage as ServerToolUsage,
+ type ServerToolUseBlock as ServerToolUseBlock,
+ type ServerToolUseBlockParam as ServerToolUseBlockParam,
type SignatureDelta as SignatureDelta,
type StopReason as StopReason,
type TextBlock as TextBlock,
@@ -409,6 +428,15 @@ export declare namespace Anthropic {
type URLImageSource as URLImageSource,
type URLPDFSource as URLPDFSource,
type Usage as Usage,
+ type WebSearchResultBlock as WebSearchResultBlock,
+ type WebSearchResultBlockParam as WebSearchResultBlockParam,
+ type WebSearchTool20250305 as WebSearchTool20250305,
+ type WebSearchToolRequestError as WebSearchToolRequestError,
+ type WebSearchToolResultBlock as WebSearchToolResultBlock,
+ type WebSearchToolResultBlockContent as WebSearchToolResultBlockContent,
+ type WebSearchToolResultBlockParam as WebSearchToolResultBlockParam,
+ type WebSearchToolResultBlockParamContent as WebSearchToolResultBlockParamContent,
+ type WebSearchToolResultError as WebSearchToolResultError,
type MessageStreamEvent as MessageStreamEvent,
type MessageStartEvent as MessageStartEvent,
type MessageDeltaEvent as MessageDeltaEvent,
@@ -427,6 +455,7 @@ export declare namespace Anthropic {
Models as Models,
type ModelInfo as ModelInfo,
ModelInfosPage as ModelInfosPage,
+ type ModelRetrieveParams as ModelRetrieveParams,
type ModelListParams as ModelListParams,
};
diff --git src/lib/BetaMessageStream.ts src/lib/BetaMessageStream.ts
index fd096926..7ad1d89f 100644
--- src/lib/BetaMessageStream.ts
+++ src/lib/BetaMessageStream.ts
@@ -530,6 +530,15 @@ export class BetaMessageStream implements AsyncIterable<BetaMessageStreamEvent>
snapshot.stop_reason = event.delta.stop_reason;
snapshot.stop_sequence = event.delta.stop_sequence;
snapshot.usage.output_tokens = event.usage.output_tokens;
+
+ // Update other usage fields if they exist in the event
+ if (event.usage.input_tokens) {
+ snapshot.usage.input_tokens = event.usage.input_tokens;
+ }
+ snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens;
+ snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens;
+ snapshot.usage.server_tool_use = event.usage.server_tool_use;
+
return snapshot;
case 'content_block_start':
snapshot.content.push(event.content_block);
diff --git src/lib/MessageStream.ts src/lib/MessageStream.ts
index 712a34ff..af81bf68 100644
--- src/lib/MessageStream.ts
+++ src/lib/MessageStream.ts
@@ -530,6 +530,15 @@ export class MessageStream implements AsyncIterable<MessageStreamEvent> {
snapshot.stop_reason = event.delta.stop_reason;
snapshot.stop_sequence = event.delta.stop_sequence;
snapshot.usage.output_tokens = event.usage.output_tokens;
+
+ // Update other usage fields if they exist in the event
+ if (event.usage.input_tokens) {
+ snapshot.usage.input_tokens = event.usage.input_tokens;
+ }
+ snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens;
+ snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens;
+ snapshot.usage.server_tool_use = event.usage.server_tool_use;
+
return snapshot;
case 'content_block_start':
snapshot.content.push(event.content_block);
diff --git src/resources/beta/beta.ts src/resources/beta/beta.ts
index 69578396..fc16229a 100644
--- src/resources/beta/beta.ts
+++ src/resources/beta/beta.ts
@@ -2,7 +2,7 @@
import { APIResource } from '../../resource';
import * as ModelsAPI from './models';
-import { BetaModelInfo, BetaModelInfosPage, ModelListParams, Models } from './models';
+import { BetaModelInfo, BetaModelInfosPage, ModelListParams, ModelRetrieveParams, Models } from './models';
import * as MessagesAPI from './messages/messages';
import {
BetaBase64ImageSource,
@@ -15,8 +15,10 @@ import {
BetaCitationContentBlockLocationParam,
BetaCitationPageLocation,
BetaCitationPageLocationParam,
+ BetaCitationWebSearchResultLocationParam,
BetaCitationsConfigParam,
BetaCitationsDelta,
+ BetaCitationsWebSearchResultLocation,
BetaContentBlock,
BetaContentBlockParam,
BetaContentBlockSource,
@@ -39,6 +41,9 @@ import {
BetaRawMessageStreamEvent,
BetaRedactedThinkingBlock,
BetaRedactedThinkingBlockParam,
+ BetaServerToolUsage,
+ BetaServerToolUseBlock,
+ BetaServerToolUseBlockParam,
BetaSignatureDelta,
BetaStopReason,
BetaTextBlock,
@@ -71,6 +76,15 @@ import {
BetaURLImageSource,
BetaURLPDFSource,
BetaUsage,
+ BetaWebSearchResultBlock,
+ BetaWebSearchResultBlockParam,
+ BetaWebSearchTool20250305,
+ BetaWebSearchToolRequestError,
+ BetaWebSearchToolResultBlock,
+ BetaWebSearchToolResultBlockContent,
+ BetaWebSearchToolResultBlockParam,
+ BetaWebSearchToolResultBlockParamContent,
+ BetaWebSearchToolResultError,
MessageCountTokensParams,
MessageCreateParams,
MessageCreateParamsNonStreaming,
@@ -189,6 +203,7 @@ export declare namespace Beta {
Models as Models,
type BetaModelInfo as BetaModelInfo,
BetaModelInfosPage as BetaModelInfosPage,
+ type ModelRetrieveParams as ModelRetrieveParams,
type ModelListParams as ModelListParams,
};
@@ -204,8 +219,10 @@ export declare namespace Beta {
type BetaCitationContentBlockLocationParam as BetaCitationContentBlockLocationParam,
type BetaCitationPageLocation as BetaCitationPageLocation,
type BetaCitationPageLocationParam as BetaCitationPageLocationParam,
+ type BetaCitationWebSearchResultLocationParam as BetaCitationWebSearchResultLocationParam,
type BetaCitationsConfigParam as BetaCitationsConfigParam,
type BetaCitationsDelta as BetaCitationsDelta,
+ type BetaCitationsWebSearchResultLocation as BetaCitationsWebSearchResultLocation,
type BetaContentBlock as BetaContentBlock,
type BetaContentBlockParam as BetaContentBlockParam,
type BetaContentBlockSource as BetaContentBlockSource,
@@ -228,6 +245,9 @@ export declare namespace Beta {
type BetaRawMessageStreamEvent as BetaRawMessageStreamEvent,
type BetaRedactedThinkingBlock as BetaRedactedThinkingBlock,
type BetaRedactedThinkingBlockParam as BetaRedactedThinkingBlockParam,
+ type BetaServerToolUsage as BetaServerToolUsage,
+ type BetaServerToolUseBlock as BetaServerToolUseBlock,
+ type BetaServerToolUseBlockParam as BetaServerToolUseBlockParam,
type BetaSignatureDelta as BetaSignatureDelta,
type BetaStopReason as BetaStopReason,
type BetaTextBlock as BetaTextBlock,
@@ -260,6 +280,15 @@ export declare namespace Beta {
type BetaURLImageSource as BetaURLImageSource,
type BetaURLPDFSource as BetaURLPDFSource,
type BetaUsage as BetaUsage,
+ type BetaWebSearchResultBlock as BetaWebSearchResultBlock,
+ type BetaWebSearchResultBlockParam as BetaWebSearchResultBlockParam,
+ type BetaWebSearchTool20250305 as BetaWebSearchTool20250305,
+ type BetaWebSearchToolRequestError as BetaWebSearchToolRequestError,
+ type BetaWebSearchToolResultBlock as BetaWebSearchToolResultBlock,
+ type BetaWebSearchToolResultBlockContent as BetaWebSearchToolResultBlockContent,
+ type BetaWebSearchToolResultBlockParam as BetaWebSearchToolResultBlockParam,
+ type BetaWebSearchToolResultBlockParamContent as BetaWebSearchToolResultBlockParamContent,
+ type BetaWebSearchToolResultError as BetaWebSearchToolResultError,
type MessageCreateParams as MessageCreateParams,
type MessageCreateParamsNonStreaming as MessageCreateParamsNonStreaming,
type MessageCreateParamsStreaming as MessageCreateParamsStreaming,
diff --git src/resources/beta/index.ts src/resources/beta/index.ts
index 4402c642..8abd778f 100644
--- src/resources/beta/index.ts
+++ src/resources/beta/index.ts
@@ -15,7 +15,13 @@ export {
type BetaPermissionError,
type BetaRateLimitError,
} from './beta';
-export { BetaModelInfosPage, Models, type BetaModelInfo, type ModelListParams } from './models';
+export {
+ BetaModelInfosPage,
+ Models,
+ type BetaModelInfo,
+ type ModelRetrieveParams,
+ type ModelListParams,
+} from './models';
export {
Messages,
type BetaBase64ImageSource,
@@ -28,8 +34,10 @@ export {
type BetaCitationContentBlockLocationParam,
type BetaCitationPageLocation,
type BetaCitationPageLocationParam,
+ type BetaCitationWebSearchResultLocationParam,
type BetaCitationsConfigParam,
type BetaCitationsDelta,
+ type BetaCitationsWebSearchResultLocation,
type BetaContentBlock,
type BetaContentBlockParam,
type BetaContentBlockSource,
@@ -52,6 +60,9 @@ export {
type BetaRawMessageStreamEvent,
type BetaRedactedThinkingBlock,
type BetaRedactedThinkingBlockParam,
+ type BetaServerToolUsage,
+ type BetaServerToolUseBlock,
+ type BetaServerToolUseBlockParam,
type BetaSignatureDelta,
type BetaStopReason,
type BetaTextBlock,
@@ -84,6 +95,15 @@ export {
type BetaURLImageSource,
type BetaURLPDFSource,
type BetaUsage,
+ type BetaWebSearchResultBlock,
+ type BetaWebSearchResultBlockParam,
+ type BetaWebSearchTool20250305,
+ type BetaWebSearchToolRequestError,
+ type BetaWebSearchToolResultBlock,
+ type BetaWebSearchToolResultBlockContent,
+ type BetaWebSearchToolResultBlockParam,
+ type BetaWebSearchToolResultBlockParamContent,
+ type BetaWebSearchToolResultError,
type MessageCreateParams,
type MessageCreateParamsNonStreaming,
type MessageCreateParamsStreaming,
diff --git src/resources/beta/messages/batches.ts src/resources/beta/messages/batches.ts
index ba6fce27..dde90fac 100644
--- src/resources/beta/messages/batches.ts
+++ src/resources/beta/messages/batches.ts
@@ -20,6 +20,25 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const betaMessageBatch =
+ * await client.beta.messages.batches.create({
+ * requests: [
+ * {
+ * custom_id: 'my-custom-id-1',
+ * params: {
+ * max_tokens: 1024,
+ * messages: [
+ * { content: 'Hello, world', role: 'user' },
+ * ],
+ * model: 'claude-3-7-sonnet-20250219',
+ * },
+ * },
+ * ],
+ * });
+ * ```
*/
create(params: BatchCreateParams, options?: Core.RequestOptions): Core.APIPromise<BetaMessageBatch> {
const { betas, ...body } = params;
@@ -40,6 +59,14 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const betaMessageBatch =
+ * await client.beta.messages.batches.retrieve(
+ * 'message_batch_id',
+ * );
+ * ```
*/
retrieve(
messageBatchId: string,
@@ -71,6 +98,14 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const betaMessageBatch of client.beta.messages.batches.list()) {
+ * // ...
+ * }
+ * ```
*/
list(
params?: BatchListParams,
@@ -103,6 +138,14 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const betaDeletedMessageBatch =
+ * await client.beta.messages.batches.delete(
+ * 'message_batch_id',
+ * );
+ * ```
*/
delete(
messageBatchId: string,
@@ -141,6 +184,14 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const betaMessageBatch =
+ * await client.beta.messages.batches.cancel(
+ * 'message_batch_id',
+ * );
+ * ```
*/
cancel(
messageBatchId: string,
@@ -175,6 +226,14 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const betaMessageBatchIndividualResponse =
+ * await client.beta.messages.batches.results(
+ * 'message_batch_id',
+ * );
+ * ```
*/
async results(
messageBatchId: string,
diff --git src/resources/beta/messages/index.ts src/resources/beta/messages/index.ts
index 39bfffd8..5a5d04bd 100644
--- src/resources/beta/messages/index.ts
+++ src/resources/beta/messages/index.ts
@@ -31,8 +31,10 @@ export {
type BetaCitationContentBlockLocationParam,
type BetaCitationPageLocation,
type BetaCitationPageLocationParam,
+ type BetaCitationWebSearchResultLocationParam,
type BetaCitationsConfigParam,
type BetaCitationsDelta,
+ type BetaCitationsWebSearchResultLocation,
type BetaContentBlock,
type BetaContentBlockParam,
type BetaContentBlockSource,
@@ -55,6 +57,9 @@ export {
type BetaRawMessageStreamEvent,
type BetaRedactedThinkingBlock,
type BetaRedactedThinkingBlockParam,
+ type BetaServerToolUsage,
+ type BetaServerToolUseBlock,
+ type BetaServerToolUseBlockParam,
type BetaSignatureDelta,
type BetaStopReason,
type BetaTextBlock,
@@ -87,6 +92,15 @@ export {
type BetaURLImageSource,
type BetaURLPDFSource,
type BetaUsage,
+ type BetaWebSearchResultBlock,
+ type BetaWebSearchResultBlockParam,
+ type BetaWebSearchTool20250305,
+ type BetaWebSearchToolRequestError,
+ type BetaWebSearchToolResultBlock,
+ type BetaWebSearchToolResultBlockContent,
+ type BetaWebSearchToolResultBlockParam,
+ type BetaWebSearchToolResultBlockParamContent,
+ type BetaWebSearchToolResultError,
type MessageCreateParams,
type MessageCreateParamsNonStreaming,
type MessageCreateParamsStreaming,
diff --git src/resources/beta/messages/messages.ts src/resources/beta/messages/messages.ts
index bc9fb874..e961cf1c 100644
--- src/resources/beta/messages/messages.ts
+++ src/resources/beta/messages/messages.ts
@@ -54,6 +54,15 @@ export class Messages extends APIResource {
* conversations.
*
* Learn more about the Messages API in our [user guide](/en/docs/initial-setup)
+ *
+ * @example
+ * ```ts
+ * const betaMessage = await client.beta.messages.create({
+ * max_tokens: 1024,
+ * messages: [{ content: 'Hello, world', role: 'user' }],
+ * model: 'claude-3-7-sonnet-20250219',
+ * });
+ * ```
*/
create(params: MessageCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<BetaMessage>;
create(
@@ -107,6 +116,15 @@ export class Messages extends APIResource {
*
* Learn more about token counting in our
* [user guide](/en/docs/build-with-claude/token-counting)
+ *
+ * @example
+ * ```ts
+ * const betaMessageTokensCount =
+ * await client.beta.messages.countTokens({
+ * messages: [{ content: 'string', role: 'user' }],
+ * model: 'claude-3-7-sonnet-latest',
+ * });
+ * ```
*/
countTokens(
params: MessageCountTokensParams,
@@ -139,6 +157,9 @@ export interface BetaBase64PDFBlock {
type: 'document';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
citations?: BetaCitationsConfigParam;
@@ -244,19 +265,49 @@ export interface BetaCitationPageLocationParam {
type: 'page_location';
}
+export interface BetaCitationWebSearchResultLocationParam {
+ cited_text: string;
+
+ encrypted_index: string;
+
+ title: string | null;
+
+ type: 'web_search_result_location';
+
+ url: string;
+}
+
export interface BetaCitationsConfigParam {
enabled?: boolean;
}
export interface BetaCitationsDelta {
- citation: BetaCitationCharLocation | BetaCitationPageLocation | BetaCitationContentBlockLocation;
+ citation:
+ | BetaCitationCharLocation
+ | BetaCitationPageLocation
+ | BetaCitationContentBlockLocation
+ | BetaCitationsWebSearchResultLocation;
type: 'citations_delta';
}
+export interface BetaCitationsWebSearchResultLocation {
+ cited_text: string;
+
+ encrypted_index: string;
+
+ title: string | null;
+
+ type: 'web_search_result_location';
+
+ url: string;
+}
+
export type BetaContentBlock =
| BetaTextBlock
| BetaToolUseBlock
+ | BetaServerToolUseBlock
+ | BetaWebSearchToolResultBlock
| BetaThinkingBlock
| BetaRedactedThinkingBlock;
@@ -264,6 +315,8 @@ export type BetaContentBlockParam =
| BetaTextBlockParam
| BetaImageBlockParam
| BetaToolUseBlockParam
+ | BetaServerToolUseBlockParam
+ | BetaWebSearchToolResultBlockParam
| BetaToolResultBlockParam
| BetaBase64PDFBlock
| BetaThinkingBlockParam
@@ -282,6 +335,9 @@ export interface BetaImageBlockParam {
type: 'image';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
}
@@ -400,10 +456,30 @@ export interface BetaMessage {
}
export interface BetaMessageDeltaUsage {
+ /**
+ * The cumulative number of input tokens used to create the cache entry.
+ */
+ cache_creation_input_tokens: number | null;
+
+ /**
+ * The cumulative number of input tokens read from the cache.
+ */
+ cache_read_input_tokens: number | null;
+
+ /**
+ * The cumulative number of input tokens which were used.
+ */
+ input_tokens: number | null;
+
/**
* The cumulative number of output tokens which were used.
*/
output_tokens: number;
+
+ /**
+ * The number of server tool requests.
+ */
+ server_tool_use: BetaServerToolUsage | null;
}
export interface BetaMessageParam {
@@ -455,7 +531,13 @@ export interface BetaRawContentBlockDeltaEvent {
}
export interface BetaRawContentBlockStartEvent {
- content_block: BetaTextBlock | BetaToolUseBlock | BetaThinkingBlock | BetaRedactedThinkingBlock;
+ content_block:
+ | BetaTextBlock
+ | BetaToolUseBlock
+ | BetaServerToolUseBlock
+ | BetaWebSearchToolResultBlock
+ | BetaThinkingBlock
+ | BetaRedactedThinkingBlock;
index: number;
@@ -531,13 +613,51 @@ export interface BetaRedactedThinkingBlockParam {
type: 'redacted_thinking';
}
+export interface BetaServerToolUsage {
+ /**
+ * The number of web search tool requests.
+ */
+ web_search_requests: number;
+}
+
+export interface BetaServerToolUseBlock {
+ id: string;
+
+ input: unknown;
+
+ name: 'web_search';
+
+ type: 'server_tool_use';
+}
+
+export interface BetaServerToolUseBlockParam {
+ id: string;
+
+ input: unknown;
+
+ name: 'web_search';
+
+ type: 'server_tool_use';
+
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
+ cache_control?: BetaCacheControlEphemeral | null;
+}
+
export interface BetaSignatureDelta {
signature: string;
type: 'signature_delta';
}
-export type BetaStopReason = 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use';
+export type BetaStopReason =
+ | 'end_turn'
+ | 'max_tokens'
+ | 'stop_sequence'
+ | 'tool_use'
+ | 'pause_turn'
+ | 'refusal';
export interface BetaTextBlock {
/**
@@ -559,6 +679,9 @@ export interface BetaTextBlockParam {
type: 'text';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
citations?: Array<BetaTextCitationParam> | null;
@@ -567,12 +690,14 @@ export interface BetaTextBlockParam {
export type BetaTextCitation =
| BetaCitationCharLocation
| BetaCitationPageLocation
- | BetaCitationContentBlockLocation;
+ | BetaCitationContentBlockLocation
+ | BetaCitationsWebSearchResultLocation;
export type BetaTextCitationParam =
| BetaCitationCharLocationParam
| BetaCitationPageLocationParam
- | BetaCitationContentBlockLocationParam;
+ | BetaCitationContentBlockLocationParam
+ | BetaCitationWebSearchResultLocationParam;
export interface BetaTextDelta {
text: string;
@@ -648,10 +773,13 @@ export interface BetaTool {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: string;
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
/**
@@ -687,12 +815,15 @@ export interface BetaToolBash20241022 {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: 'bash';
type: 'bash_20241022';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
}
@@ -700,12 +831,15 @@ export interface BetaToolBash20250124 {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: 'bash';
type: 'bash_20250124';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
}
@@ -786,12 +920,15 @@ export interface BetaToolComputerUse20241022 {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: 'computer';
type: 'computer_20241022';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
/**
@@ -814,12 +951,15 @@ export interface BetaToolComputerUse20250124 {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: 'computer';
type: 'computer_20250124';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
/**
@@ -833,6 +973,9 @@ export interface BetaToolResultBlockParam {
type: 'tool_result';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
content?: string | Array<BetaTextBlockParam | BetaImageBlockParam>;
@@ -844,12 +987,15 @@ export interface BetaToolTextEditor20241022 {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: 'str_replace_editor';
type: 'text_editor_20241022';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
}
@@ -857,12 +1003,15 @@ export interface BetaToolTextEditor20250124 {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: 'str_replace_editor';
type: 'text_editor_20250124';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
}
@@ -873,7 +1022,8 @@ export type BetaToolUnion =
| BetaToolTextEditor20241022
| BetaToolComputerUse20250124
| BetaToolBash20250124
- | BetaToolTextEditor20250124;
+ | BetaToolTextEditor20250124
+ | BetaWebSearchTool20250305;
export interface BetaToolUseBlock {
id: string;
@@ -894,6 +1044,9 @@ export interface BetaToolUseBlockParam {
type: 'tool_use';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
}
@@ -929,6 +1082,157 @@ export interface BetaUsage {
* The number of output tokens which were used.
*/
output_tokens: number;
+
+ /**
+ * The number of server tool requests.
+ */
+ server_tool_use: BetaServerToolUsage | null;
+}
+
+export interface BetaWebSearchResultBlock {
+ encrypted_content: string;
+
+ page_age: string | null;
+
+ title: string;
+
+ type: 'web_search_result';
+
+ url: string;
+}
+
+export interface BetaWebSearchResultBlockParam {
+ encrypted_content: string;
+
+ title: string;
+
+ type: 'web_search_result';
+
+ url: string;
+
+ page_age?: string | null;
+}
+
+export interface BetaWebSearchTool20250305 {
+ /**
+ * Name of the tool.
+ *
+ * This is how the tool will be called by the model and in `tool_use` blocks.
+ */
+ name: 'web_search';
+
+ type: 'web_search_20250305';
+
+ /**
+ * If provided, only these domains will be included in results. Cannot be used
+ * alongside `blocked_domains`.
+ */
+ allowed_domains?: Array<string> | null;
+
+ /**
+ * If provided, these domains will never appear in results. Cannot be used
+ * alongside `allowed_domains`.
+ */
+ blocked_domains?: Array<string> | null;
+
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
+ cache_control?: BetaCacheControlEphemeral | null;
+
+ /**
+ * Maximum number of times the tool can be used in the API request.
+ */
+ max_uses?: number | null;
+
+ /**
+ * Parameters for the user's location. Used to provide more relevant search
+ * results.
+ */
+ user_location?: BetaWebSearchTool20250305.UserLocation | null;
+}
+
+export namespace BetaWebSearchTool20250305 {
+ /**
+ * Parameters for the user's location. Used to provide more relevant search
+ * results.
+ */
+ export interface UserLocation {
+ type: 'approximate';
+
+ /**
+ * The city of the user.
+ */
+ city?: string | null;
+
+ /**
+ * The two letter
+ * [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the
+ * user.
+ */
+ country?: string | null;
+
+ /**
+ * The region of the user.
+ */
+ region?: string | null;
+
+ /**
+ * The [IANA timezone](https://nodatime.org/TimeZones) of the user.
+ */
+ timezone?: string | null;
+ }
+}
+
+export interface BetaWebSearchToolRequestError {
+ error_code:
+ | 'invalid_tool_input'
+ | 'unavailable'
+ | 'max_uses_exceeded'
+ | 'too_many_requests'
+ | 'query_too_long';
+
+ type: 'web_search_tool_result_error';
+}
+
+export interface BetaWebSearchToolResultBlock {
+ content: BetaWebSearchToolResultBlockContent;
+
+ tool_use_id: string;
+
+ type: 'web_search_tool_result';
+}
+
+export type BetaWebSearchToolResultBlockContent =
+ | BetaWebSearchToolResultError
+ | Array<BetaWebSearchResultBlock>;
+
+export interface BetaWebSearchToolResultBlockParam {
+ content: BetaWebSearchToolResultBlockParamContent;
+
+ tool_use_id: string;
+
+ type: 'web_search_tool_result';
+
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
+ cache_control?: BetaCacheControlEphemeral | null;
+}
+
+export type BetaWebSearchToolResultBlockParamContent =
+ | Array<BetaWebSearchResultBlockParam>
+ | BetaWebSearchToolRequestError;
+
+export interface BetaWebSearchToolResultError {
+ error_code:
+ | 'invalid_tool_input'
+ | 'unavailable'
+ | 'max_uses_exceeded'
+ | 'too_many_requests'
+ | 'query_too_long';
+
+ type: 'web_search_tool_result_error';
}
export type MessageCreateParams = MessageCreateParamsNonStreaming | MessageCreateParamsStreaming;
@@ -1032,6 +1336,8 @@ export interface MessageCreateParamsBase {
* [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use
* the top-level `system` parameter β there is no `"system"` role for input
* messages in the Messages API.
+ *
+ * There is a limit of 100000 messages in a single request.
*/
messages: Array<BetaMessageParam>;
@@ -1327,6 +1633,8 @@ export interface MessageCountTokensParams {
* [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use
* the top-level `system` parameter β there is no `"system"` role for input
* messages in the Messages API.
+ *
+ * There is a limit of 100000 messages in a single request.
*/
messages: Array<BetaMessageParam>;
@@ -1444,6 +1752,7 @@ export interface MessageCountTokensParams {
| BetaToolComputerUse20250124
| BetaToolBash20250124
| BetaToolTextEditor20250124
+ | BetaWebSearchTool20250305
>;
/**
@@ -1467,8 +1776,10 @@ export declare namespace Messages {
type BetaCitationContentBlockLocationParam as BetaCitationContentBlockLocationParam,
type BetaCitationPageLocation as BetaCitationPageLocation,
type BetaCitationPageLocationParam as BetaCitationPageLocationParam,
+ type BetaCitationWebSearchResultLocationParam as BetaCitationWebSearchResultLocationParam,
type BetaCitationsConfigParam as BetaCitationsConfigParam,
type BetaCitationsDelta as BetaCitationsDelta,
+ type BetaCitationsWebSearchResultLocation as BetaCitationsWebSearchResultLocation,
type BetaContentBlock as BetaContentBlock,
type BetaContentBlockParam as BetaContentBlockParam,
type BetaContentBlockSource as BetaContentBlockSource,
@@ -1491,6 +1802,9 @@ export declare namespace Messages {
type BetaRawMessageStreamEvent as BetaRawMessageStreamEvent,
type BetaRedactedThinkingBlock as BetaRedactedThinkingBlock,
type BetaRedactedThinkingBlockParam as BetaRedactedThinkingBlockParam,
+ type BetaServerToolUsage as BetaServerToolUsage,
+ type BetaServerToolUseBlock as BetaServerToolUseBlock,
+ type BetaServerToolUseBlockParam as BetaServerToolUseBlockParam,
type BetaSignatureDelta as BetaSignatureDelta,
type BetaStopReason as BetaStopReason,
type BetaTextBlock as BetaTextBlock,
@@ -1523,6 +1837,15 @@ export declare namespace Messages {
type BetaURLImageSource as BetaURLImageSource,
type BetaURLPDFSource as BetaURLPDFSource,
type BetaUsage as BetaUsage,
+ type BetaWebSearchResultBlock as BetaWebSearchResultBlock,
+ type BetaWebSearchResultBlockParam as BetaWebSearchResultBlockParam,
+ type BetaWebSearchTool20250305 as BetaWebSearchTool20250305,
+ type BetaWebSearchToolRequestError as BetaWebSearchToolRequestError,
+ type BetaWebSearchToolResultBlock as BetaWebSearchToolResultBlock,
+ type BetaWebSearchToolResultBlockContent as BetaWebSearchToolResultBlockContent,
+ type BetaWebSearchToolResultBlockParam as BetaWebSearchToolResultBlockParam,
+ type BetaWebSearchToolResultBlockParamContent as BetaWebSearchToolResultBlockParamContent,
+ type BetaWebSearchToolResultError as BetaWebSearchToolResultError,
type MessageCreateParams as MessageCreateParams,
type MessageCreateParamsNonStreaming as MessageCreateParamsNonStreaming,
type MessageCreateParamsStreaming as MessageCreateParamsStreaming,
diff --git src/resources/beta/models.ts src/resources/beta/models.ts
index 48036273..6ec9c244 100644
--- src/resources/beta/models.ts
+++ src/resources/beta/models.ts
@@ -3,6 +3,7 @@
import { APIResource } from '../../resource';
import { isRequestOptions } from '../../core';
import * as Core from '../../core';
+import * as BetaAPI from './beta';
import { Page, type PageParams } from '../../pagination';
export class Models extends APIResource {
@@ -11,9 +12,36 @@ export class Models extends APIResource {
*
* The Models API response can be used to determine information about a specific
* model or resolve a model alias to a model ID.
+ *
+ * @example
+ * ```ts
+ * const betaModelInfo = await client.beta.models.retrieve(
+ * 'model_id',
+ * );
+ * ```
*/
- retrieve(modelId: string, options?: Core.RequestOptions): Core.APIPromise<BetaModelInfo> {
- return this._client.get(`/v1/models/${modelId}?beta=true`, options);
+ retrieve(
+ modelId: string,
+ params?: ModelRetrieveParams,
+ options?: Core.RequestOptions,
+ ): Core.APIPromise<BetaModelInfo>;
+ retrieve(modelId: string, options?: Core.RequestOptions): Core.APIPromise<BetaModelInfo>;
+ retrieve(
+ modelId: string,
+ params: ModelRetrieveParams | Core.RequestOptions = {},
+ options?: Core.RequestOptions,
+ ): Core.APIPromise<BetaModelInfo> {
+ if (isRequestOptions(params)) {
+ return this.retrieve(modelId, {}, params);
+ }
+ const { betas } = params;
+ return this._client.get(`/v1/models/${modelId}?beta=true`, {
+ ...options,
+ headers: {
+ ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined),
+ ...options?.headers,
+ },
+ });
}
/**
@@ -21,20 +49,36 @@ export class Models extends APIResource {
*
* The Models API response can be used to determine which models are available for
* use in the API. More recently released models are listed first.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const betaModelInfo of client.beta.models.list()) {
+ * // ...
+ * }
+ * ```
*/
list(
- query?: ModelListParams,
+ params?: ModelListParams,
options?: Core.RequestOptions,
): Core.PagePromise<BetaModelInfosPage, BetaModelInfo>;
list(options?: Core.RequestOptions): Core.PagePromise<BetaModelInfosPage, BetaModelInfo>;
list(
- query: ModelListParams | Core.RequestOptions = {},
+ params: ModelListParams | Core.RequestOptions = {},
options?: Core.RequestOptions,
): Core.PagePromise<BetaModelInfosPage, BetaModelInfo> {
- if (isRequestOptions(query)) {
- return this.list({}, query);
+ if (isRequestOptions(params)) {
+ return this.list({}, params);
}
- return this._client.getAPIList('/v1/models?beta=true', BetaModelInfosPage, { query, ...options });
+ const { betas, ...query } = params;
+ return this._client.getAPIList('/v1/models?beta=true', BetaModelInfosPage, {
+ query,
+ ...options,
+ headers: {
+ ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined),
+ ...options?.headers,
+ },
+ });
}
}
@@ -65,7 +109,19 @@ export interface BetaModelInfo {
type: 'model';
}
-export interface ModelListParams extends PageParams {}
+export interface ModelRetrieveParams {
+ /**
+ * Optional header to specify the beta version(s) you want to use.
+ */
+ betas?: Array<BetaAPI.AnthropicBeta>;
+}
+
+export interface ModelListParams extends PageParams {
+ /**
+ * Header param: Optional header to specify the beta version(s) you want to use.
+ */
+ betas?: Array<BetaAPI.AnthropicBeta>;
+}
Models.BetaModelInfosPage = BetaModelInfosPage;
@@ -73,6 +129,7 @@ export declare namespace Models {
export {
type BetaModelInfo as BetaModelInfo,
BetaModelInfosPage as BetaModelInfosPage,
+ type ModelRetrieveParams as ModelRetrieveParams,
type ModelListParams as ModelListParams,
};
}
diff --git src/resources/completions.ts src/resources/completions.ts
index 2260681d..a0bfb0ab 100644
--- src/resources/completions.ts
+++ src/resources/completions.ts
@@ -4,6 +4,7 @@ import { APIResource } from '../resource';
import { APIPromise } from '../core';
import * as Core from '../core';
import * as CompletionsAPI from './completions';
+import * as BetaAPI from './beta/beta';
import * as MessagesAPI from './messages/messages';
import { Stream } from '../streaming';
@@ -17,25 +18,39 @@ export class Completions extends APIResource {
* Future models and features will not be compatible with Text Completions. See our
* [migration guide](https://docs.anthropic.com/en/api/migrating-from-text-completions-to-messages)
* for guidance in migrating from Text Completions to Messages.
+ *
+ * @example
+ * ```ts
+ * const completion = await client.completions.create({
+ * max_tokens_to_sample: 256,
+ * model: 'claude-3-7-sonnet-latest',
+ * prompt: '\n\nHuman: Hello, world!\n\nAssistant:',
+ * });
+ * ```
*/
- create(body: CompletionCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<Completion>;
+ create(params: CompletionCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<Completion>;
create(
- body: CompletionCreateParamsStreaming,
+ params: CompletionCreateParamsStreaming,
options?: Core.RequestOptions,
): APIPromise<Stream<Completion>>;
create(
- body: CompletionCreateParamsBase,
+ params: CompletionCreateParamsBase,
options?: Core.RequestOptions,
): APIPromise<Stream<Completion> | Completion>;
create(
- body: CompletionCreateParams,
+ params: CompletionCreateParams,
options?: Core.RequestOptions,
): APIPromise<Completion> | APIPromise<Stream<Completion>> {
+ const { betas, ...body } = params;
return this._client.post('/v1/complete', {
body,
timeout: (this._client as any)._options.timeout ?? 600000,
...options,
- stream: body.stream ?? false,
+ headers: {
+ ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined),
+ ...options?.headers,
+ },
+ stream: params.stream ?? false,
}) as APIPromise<Completion> | APIPromise<Stream<Completion>>;
}
}
@@ -83,7 +98,7 @@ export type CompletionCreateParams = CompletionCreateParamsNonStreaming | Comple
export interface CompletionCreateParamsBase {
/**
- * The maximum number of tokens to generate before stopping.
+ * Body param: The maximum number of tokens to generate before stopping.
*
* Note that our models may stop _before_ reaching this maximum. This parameter
* only specifies the absolute maximum number of tokens to generate.
@@ -91,14 +106,14 @@ export interface CompletionCreateParamsBase {
max_tokens_to_sample: number;
/**
- * The model that will complete your prompt.\n\nSee
+ * Body param: The model that will complete your prompt.\n\nSee
* [models](https://docs.anthropic.com/en/docs/models-overview) for additional
* details and options.
*/
model: MessagesAPI.Model;
/**
- * The prompt that you want Claude to complete.
+ * Body param: The prompt that you want Claude to complete.
*
* For proper response generation you will need to format your prompt using
* alternating `\n\nHuman:` and `\n\nAssistant:` conversational turns. For example:
@@ -115,12 +130,12 @@ export interface CompletionCreateParamsBase {
prompt: string;
/**
- * An object describing metadata about the request.
+ * Body param: An object describing metadata about the request.
*/
metadata?: MessagesAPI.Metadata;
/**
- * Sequences that will cause the model to stop generating.
+ * Body param: Sequences that will cause the model to stop generating.
*
* Our models stop on `"\n\nHuman:"`, and may include additional built-in stop
* sequences in the future. By providing the stop_sequences parameter, you may
@@ -129,14 +144,15 @@ export interface CompletionCreateParamsBase {
stop_sequences?: Array<string>;
/**
- * Whether to incrementally stream the response using server-sent events.
+ * Body param: Whether to incrementally stream the response using server-sent
+ * events.
*
* See [streaming](https://docs.anthropic.com/en/api/streaming) for details.
*/
stream?: boolean;
/**
- * Amount of randomness injected into the response.
+ * Body param: Amount of randomness injected into the response.
*
* Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0`
* for analytical / multiple choice, and closer to `1.0` for creative and
@@ -148,7 +164,7 @@ export interface CompletionCreateParamsBase {
temperature?: number;
/**
- * Only sample from the top K options for each subsequent token.
+ * Body param: Only sample from the top K options for each subsequent token.
*
* Used to remove "long tail" low probability responses.
* [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).
@@ -159,7 +175,7 @@ export interface CompletionCreateParamsBase {
top_k?: number;
/**
- * Use nucleus sampling.
+ * Body param: Use nucleus sampling.
*
* In nucleus sampling, we compute the cumulative distribution over all the options
* for each subsequent token in decreasing probability order and cut it off once it
@@ -170,6 +186,11 @@ export interface CompletionCreateParamsBase {
* `temperature`.
*/
top_p?: number;
+
+ /**
+ * Header param: Optional header to specify the beta version(s) you want to use.
+ */
+ betas?: Array<BetaAPI.AnthropicBeta>;
}
export namespace CompletionCreateParams {
@@ -184,7 +205,8 @@ export namespace CompletionCreateParams {
export interface CompletionCreateParamsNonStreaming extends CompletionCreateParamsBase {
/**
- * Whether to incrementally stream the response using server-sent events.
+ * Body param: Whether to incrementally stream the response using server-sent
+ * events.
*
* See [streaming](https://docs.anthropic.com/en/api/streaming) for details.
*/
@@ -193,7 +215,8 @@ export interface CompletionCreateParamsNonStreaming extends CompletionCreatePara
export interface CompletionCreateParamsStreaming extends CompletionCreateParamsBase {
/**
- * Whether to incrementally stream the response using server-sent events.
+ * Body param: Whether to incrementally stream the response using server-sent
+ * events.
*
* See [streaming](https://docs.anthropic.com/en/api/streaming) for details.
*/
diff --git src/resources/index.ts src/resources/index.ts
index d08d2619..114b9fe4 100644
--- src/resources/index.ts
+++ src/resources/index.ts
@@ -34,8 +34,10 @@ export {
type CitationContentBlockLocationParam,
type CitationPageLocation,
type CitationPageLocationParam,
+ type CitationWebSearchResultLocationParam,
type CitationsConfigParam,
type CitationsDelta,
+ type CitationsWebSearchResultLocation,
type ContentBlock,
type ContentBlockParam,
type ContentBlockSource,
@@ -63,6 +65,9 @@ export {
type RawMessageStreamEvent,
type RedactedThinkingBlock,
type RedactedThinkingBlockParam,
+ type ServerToolUsage,
+ type ServerToolUseBlock,
+ type ServerToolUseBlockParam,
type SignatureDelta,
type StopReason,
type TextBlock,
@@ -91,6 +96,15 @@ export {
type URLImageSource,
type URLPDFSource,
type Usage,
+ type WebSearchResultBlock,
+ type WebSearchResultBlockParam,
+ type WebSearchTool20250305,
+ type WebSearchToolRequestError,
+ type WebSearchToolResultBlock,
+ type WebSearchToolResultBlockContent,
+ type WebSearchToolResultBlockParam,
+ type WebSearchToolResultBlockParamContent,
+ type WebSearchToolResultError,
type MessageStreamEvent,
type MessageStartEvent,
type MessageDeltaEvent,
@@ -103,4 +117,10 @@ export {
type MessageCreateParamsStreaming,
type MessageCountTokensParams,
} from './messages/messages';
-export { ModelInfosPage, Models, type ModelInfo, type ModelListParams } from './models';
+export {
+ ModelInfosPage,
+ Models,
+ type ModelInfo,
+ type ModelRetrieveParams,
+ type ModelListParams,
+} from './models';
diff --git src/resources/messages/batches.ts src/resources/messages/batches.ts
index e188da1a..c14bc48b 100644
--- src/resources/messages/batches.ts
+++ src/resources/messages/batches.ts
@@ -20,6 +20,24 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const messageBatch = await client.messages.batches.create({
+ * requests: [
+ * {
+ * custom_id: 'my-custom-id-1',
+ * params: {
+ * max_tokens: 1024,
+ * messages: [
+ * { content: 'Hello, world', role: 'user' },
+ * ],
+ * model: 'claude-3-7-sonnet-20250219',
+ * },
+ * },
+ * ],
+ * });
+ * ```
*/
create(body: BatchCreateParams, options?: Core.RequestOptions): Core.APIPromise<MessageBatch> {
return this._client.post('/v1/messages/batches', { body, ...options });
@@ -32,6 +50,13 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const messageBatch = await client.messages.batches.retrieve(
+ * 'message_batch_id',
+ * );
+ * ```
*/
retrieve(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<MessageBatch> {
return this._client.get(`/v1/messages/batches/${messageBatchId}`, options);
@@ -43,6 +68,14 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const messageBatch of client.messages.batches.list()) {
+ * // ...
+ * }
+ * ```
*/
list(
query?: BatchListParams,
@@ -67,6 +100,12 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const deletedMessageBatch =
+ * await client.messages.batches.delete('message_batch_id');
+ * ```
*/
delete(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<DeletedMessageBatch> {
return this._client.delete(`/v1/messages/batches/${messageBatchId}`, options);
@@ -85,6 +124,13 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const messageBatch = await client.messages.batches.cancel(
+ * 'message_batch_id',
+ * );
+ * ```
*/
cancel(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<MessageBatch> {
return this._client.post(`/v1/messages/batches/${messageBatchId}/cancel`, options);
@@ -99,6 +145,12 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const messageBatchIndividualResponse =
+ * await client.messages.batches.results('message_batch_id');
+ * ```
*/
async results(
messageBatchId: string,
diff --git src/resources/messages/index.ts src/resources/messages/index.ts
index 197baf25..6ecc7f19 100644
--- src/resources/messages/index.ts
+++ src/resources/messages/index.ts
@@ -26,8 +26,10 @@ export {
type CitationContentBlockLocationParam,
type CitationPageLocation,
type CitationPageLocationParam,
+ type CitationWebSearchResultLocationParam,
type CitationsConfigParam,
type CitationsDelta,
+ type CitationsWebSearchResultLocation,
type ContentBlock,
type ContentBlockParam,
type ContentBlockSource,
@@ -53,6 +55,9 @@ export {
type RawMessageStreamEvent,
type RedactedThinkingBlock,
type RedactedThinkingBlockParam,
+ type ServerToolUsage,
+ type ServerToolUseBlock,
+ type ServerToolUseBlockParam,
, type SignatureDelta,
type StopReason,
type TextBlock,
@@ -81,6 +86,15 @@ export {
type URLImageSource,
type URLPDFSource,
type Usage,
+ type WebSearchResultBlock,
+ type WebSearchResultBlockParam,
+ type WebSearchTool20250305,
+ type WebSearchToolRequestError,
+ type WebSearchToolResultBlock,
+ type WebSearchToolResultBlockContent,
+ type WebSearchToolResultBlockParam,
+ type WebSearchToolResultBlockParamContent,
+ type WebSearchToolResultError,
type MessageStreamEvent,
type MessageStartEvent,
type MessageDeltaEvent,
diff --git src/resources/messages/messages.ts src/resources/messages/messages.ts
index c0ab4767..ce2bde21 100644
--- src/resources/messages/messages.ts
+++ src/resources/messages/messages.ts
@@ -36,6 +36,15 @@ export class Messages extends APIResource {
* conversations.
*
* Learn more about the Messages API in our [user guide](/en/docs/initial-setup)
+ *
+ * @example
+ * ```ts
+ * const message = await client.messages.create({
+ * max_tokens: 1024,
+ * messages: [{ content: 'Hello, world', role: 'user' }],
+ * model: 'claude-3-7-sonnet-20250219',
+ * });
+ * ```
*/
create(body: MessageCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<Message>;
create(
@@ -82,6 +91,15 @@ export class Messages extends APIResource {
*
* Learn more about token counting in our
* [user guide](/en/docs/build-with-claude/token-counting)
+ *
+ * @example
+ * ```ts
+ * const messageTokensCount =
+ * await client.messages.countTokens({
+ * messages: [{ content: 'string', role: 'user' }],
+ * model: 'claude-3-7-sonnet-latest',
+ * });
+ * ```
*/
countTokens(
body: MessageCountTokensParams,
@@ -195,22 +213,58 @@ export interface CitationPageLocationParam {
type: 'page_location';
}
+export interface CitationWebSearchResultLocationParam {
+ cited_text: string;
+
+ encrypted_index: string;
+
+ title: string | null;
+
+ type: 'web_search_result_location';
+
+ url: string;
+}
+
export interface CitationsConfigParam {
enabled?: boolean;
}
export interface CitationsDelta {
- citation: CitationCharLocation | CitationPageLocation | CitationContentBlockLocation;
+ citation:
+ | CitationCharLocation
+ | CitationPageLocation
+ | CitationContentBlockLocation
+ | CitationsWebSearchResultLocation;
type: 'citations_delta';
}
-export type ContentBlock = TextBlock | ToolUseBlock | ThinkingBlock | RedactedThinkingBlock;
+export interface CitationsWebSearchResultLocation {
+ cited_text: string;
+
+ encrypted_index: string;
+
+ title: string | null;
+
+ type: 'web_search_result_location';
+
+ url: string;
+}
+
+export type ContentBlock =
+ | TextBlock
+ | ToolUseBlock
+ | ServerToolUseBlock
+ | WebSearchToolResultBlock
+ | ThinkingBlock
+ | RedactedThinkingBlock;
export type ContentBlockParam =
| TextBlockParam
| ImageBlockParam
| ToolUseBlockParam
+ | ServerToolUseBlockParam
+ | WebSearchToolResultBlockParam
| ToolResultBlockParam
| DocumentBlockParam
| ThinkingBlockParam
@@ -229,6 +283,9 @@ export interface DocumentBlockParam {
type: 'document';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: CacheControlEphemeral | null;
citations?: CitationsConfigParam;
@@ -243,6 +300,9 @@ export interface ImageBlockParam {
type: 'image';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: CacheControlEphemeral | null;
}
@@ -362,13 +422,33 @@ export interface Message {
usage: Usage;
}
-export type MessageCountTokensTool = Tool | ToolBash20250124 | ToolTextEditor20250124;
+export type MessageCountTokensTool = Tool | ToolBash20250124 | ToolTextEditor20250124 | WebSearchTool20250305;
export interface MessageDeltaUsage {
+ /**
+ * The cumulative number of input tokens used to create the cache entry.
+ */
+ cache_creation_input_tokens: number | null;
+
+ /**
+ * The cumulative number of input tokens read from the cache.
+ */
+ cache_read_input_tokens: number | null;
+
+ /**
+ * The cumulative number of input tokens which were used.
+ */
+ input_tokens: number | null;
+
/**
* The cumulative number of output tokens which were used.
*/
output_tokens: number;
+
+ /**
+ * The number of server tool requests.
+ */
+ server_tool_use: ServerToolUsage | null;
}
export interface MessageParam {
@@ -454,7 +534,13 @@ export interface RawContentBlockDeltaEvent {
}
export interface RawContentBlockStartEvent {
- content_block: TextBlock | ToolUseBlock | ThinkingBlock | RedactedThinkingBlock;
+ content_block:
+ | TextBlock
+ | ToolUseBlock
+ | ServerToolUseBlock
+ | WebSearchToolResultBlock
+ | ThinkingBlock
+ | RedactedThinkingBlock;
index: number;
@@ -530,13 +616,45 @@ export interface RedactedThinkingBlockParam {
type: 'redacted_thinking';
}
+export interface ServerToolUsage {
+ /**
+ * The number of web search tool requests.
+ */
+ web_search_requests: number;
+}
+
+export interface ServerToolUseBlock {
+ id: string;
+
+ input: unknown;
+
+ name: 'web_search';
+
+ type: 'server_tool_use';
+}
+
+export interface ServerToolUseBlockParam {
+ id: string;
+
+ input: unknown;
+
+ name: 'web_search';
+
+ type: 'server_tool_use';
+
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
+ cache_control?: CacheControlEphemeral | null;
+}
+
export interface SignatureDelta {
signature: string;
type: 'signature_delta';
}
-export type StopReason = 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use';
+export type StopReason = 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | 'pause_turn' | 'refusal';
export interface TextBlock {
/**
@@ -558,17 +676,25 @@ export interface TextBlockParam {
type: 'text';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: CacheControlEphemeral | null;
citations?: Array<TextCitationParam> | null;
}
-export type TextCitation = CitationCharLocation | CitationPageLocation | CitationContentBlockLocation;
+export type TextCitation =
+ | CitationCharLocation
+ | CitationPageLocation
+ | CitationContentBlockLocation
+ | CitationsWebSearchResultLocation;
export type TextCitationParam =
| CitationCharLocationParam
| CitationPageLocationParam
- | CitationContentBlockLocationParam;
+ | CitationContentBlockLocationParam
+ | CitationWebSearchResultLocationParam;
export interface TextDelta {
text: string;
@@ -644,10 +770,13 @@ export interface Tool {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: string;
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: CacheControlEphemeral | null;
/**
@@ -659,6 +788,8 @@ export interface Tool {
* aspects of the tool input JSON schema.
*/
description?: string;
+
+ type?: 'custom' | null;
}
export namespace Tool {
@@ -681,12 +812,15 @@ export interface ToolBash20250124 {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: 'bash';
type: 'bash_20250124';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: CacheControlEphemeral | null;
}
@@ -758,6 +892,9 @@ export interface ToolResultBlockParam {
type: 'tool_result';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: CacheControlEphemeral | null;
content?: string | Array<TextBlockParam | ImageBlockParam>;
@@ -769,16 +906,19 @@ export interface ToolTextEditor20250124 {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: 'str_replace_editor';
type: 'text_editor_20250124';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: CacheControlEphemeral | null;
}
-export type ToolUnion = Tool | ToolBash20250124 | ToolTextEditor20250124;
+export type ToolUnion = Tool | ToolBash20250124 | ToolTextEditor20250124 | WebSearchTool20250305;
export interface ToolUseBlock {
id: string;
@@ -799,6 +939,9 @@ export interface ToolUseBlockParam {
type: 'tool_use';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: CacheControlEphemeral | null;
}
@@ -834,6 +977,155 @@ export interface Usage {
* The number of output tokens which were used.
*/
output_tokens: number;
+
+ /**
+ * The number of server tool requests.
+ */
+ server_tool_use: ServerToolUsage | null;
+}
+
+export interface WebSearchResultBlock {
+ encrypted_content: string;
+
+ page_age: string | null;
+
+ title: string;
+
+ type: 'web_search_result';
+
+ url: string;
+}
+
+export interface WebSearchResultBlockParam {
+ encrypted_content: string;
+
+ title: string;
+
+ type: 'web_search_result';
+
+ url: string;
+
+ page_age?: string | null;
+}
+
+export interface WebSearchTool20250305 {
+ /**
+ * Name of the tool.
+ *
+ * This is how the tool will be called by the model and in `tool_use` blocks.
+ */
+ name: 'web_search';
+
+ type: 'web_search_20250305';
+
+ /**
+ * If provided, only these domains will be included in results. Cannot be used
+ * alongside `blocked_domains`.
+ */
+ allowed_domains?: Array<string> | null;
+
+ /**
+ * If provided, these domains will never appear in results. Cannot be used
+ * alongside `allowed_domains`.
+ */
+ blocked_domains?: Array<string> | null;
+
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
+ cache_control?: CacheControlEphemeral | null;
+
+ /**
+ * Maximum number of times the tool can be used in the API request.
+ */
+ max_uses?: number | null;
+
+ /**
+ * Parameters for the user's location. Used to provide more relevant search
+ * results.
+ */
+ user_location?: WebSearchTool20250305.UserLocation | null;
+}
+
+export namespace WebSearchTool20250305 {
+ /**
+ * Parameters for the user's location. Used to provide more relevant search
+ * results.
+ */
+ export interface UserLocation {
+ type: 'approximate';
+
+ /**
+ * The city of the user.
+ */
+ city?: string | null;
+
+ /**
+ * The two letter
+ * [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the
+ * user.
+ */
+ country?: string | null;
+
+ /**
+ * The region of the user.
+ */
+ region?: string | null;
+
+ /**
+ * The [IANA timezone](https://nodatime.org/TimeZones) of the user.
+ */
+ timezone?: string | null;
+ }
+}
+
+export interface WebSearchToolRequestError {
+ error_code:
+ | 'invalid_tool_input'
+ | 'unavailable'
+ | 'max_uses_exceeded'
+ | 'too_many_requests'
+ | 'query_too_long';
+
+ type: 'web_search_tool_result_error';
+}
+
+export interface WebSearchToolResultBlock {
+ content: WebSearchToolResultBlockContent;
+
+ tool_use_id: string;
+
+ type: 'web_search_tool_result';
+}
+
+export type WebSearchToolResultBlockContent = WebSearchToolResultError | Array<WebSearchResultBlock>;
+
+export interface WebSearchToolResultBlockParam {
+ content: WebSearchToolResultBlockParamContent;
+
+ tool_use_id: string;
+
+ type: 'web_search_tool_result';
+
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
+ cache_control?: CacheControlEphemeral | null;
+}
+
+export type WebSearchToolResultBlockParamContent =
+ | Array<WebSearchResultBlockParam>
+ | WebSearchToolRequestError;
+
+export interface WebSearchToolResultError {
+ error_code:
+ | 'invalid_tool_input'
+ | 'unavailable'
+ | 'max_uses_exceeded'
+ | 'too_many_requests'
+ | 'query_too_long';
+
+ type: 'web_search_tool_result_error';
}
export type MessageStreamEvent = RawMessageStreamEvent;
@@ -951,6 +1243,8 @@ export interface MessageCreateParamsBase {
* [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use
* the top-level `system` parameter β there is no `"system"` role for input
* messages in the Messages API.
+ *
+ * There is a limit of 100000 messages in a single request.
*/
messages: Array<MessageParam>;
@@ -1260,6 +1554,8 @@ export interface MessageCountTokensParams {
* [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use
* the top-level `system` parameter β there is no `"system"` role for input
* messages in the Messages API.
+ *
+ * There is a limit of 100000 messages in a single request.
*/
messages: Array<MessageParam>;
@@ -1386,8 +1682,10 @@ export declare namespace Messages {
type CitationContentBlockLocationParam as CitationContentBlockLocationParam,
type CitationPageLocation as CitationPageLocation,
type CitationPageLocationParam as CitationPageLocationParam,
+ type CitationWebSearchResultLocationParam as CitationWebSearchResultLocationParam,
type CitationsConfigParam as CitationsConfigParam,
type CitationsDelta as CitationsDelta,
+ type CitationsWebSearchResultLocation as CitationsWebSearchResultLocation,
type ContentBlock as ContentBlock,
type ContentBlockParam as ContentBlockParam,
type ContentBlockSource as ContentBlockSource,
@@ -1414,6 +1712,9 @@ export declare namespace Messages {
type RawMessageStreamEvent as RawMessageStreamEvent,
type RedactedThinkingBlock as RedactedThinkingBlock,
type RedactedThinkingBlockParam as RedactedThinkingBlockParam,
+ type ServerToolUsage as ServerToolUsage,
+ type ServerToolUseBlock as ServerToolUseBlock,
+ type ServerToolUseBlockParam as ServerToolUseBlockParam,
type SignatureDelta as SignatureDelta,
type StopReason as StopReason,
type TextBlock as TextBlock,
@@ -1442,6 +1743,15 @@ export declare namespace Messages {
type URLImageSource as URLImageSource,
type URLPDFSource as URLPDFSource,
type Usage as Usage,
+ type WebSearchResultBlock as WebSearchResultBlock,
+ type WebSearchResultBlockParam as WebSearchResultBlockParam,
+ type WebSearchTool20250305 as WebSearchTool20250305,
+ type WebSearchToolRequestError as WebSearchToolRequestError,
+ type WebSearchToolResultBlock as WebSearchToolResultBlock,
+ type WebSearchToolResultBlockContent as WebSearchToolResultBlockContent,
+ type WebSearchToolResultBlockParam as WebSearchToolResultBlockParam,
+ type WebSearchToolResultBlockParamContent as WebSearchToolResultBlockParamContent,
+ type WebSearchToolResultError as WebSearchToolResultError,
type MessageStreamEvent as MessageStreamEvent,
type MessageStartEvent as MessageStartEvent,
type MessageDeltaEvent as MessageDeltaEvent,
diff --git src/resources/models.ts src/resources/models.ts
index 50e80399..68491b3e 100644
--- src/resources/models.ts
+++ src/resources/models.ts
@@ -3,6 +3,7 @@
import { APIResource } from '../resource';
import { isRequestOptions } from '../core';
import * as Core from '../core';
+import * as BetaAPI from './beta/beta';
import { Page, type PageParams } from '../pagination';
export class Models extends APIResource {
@@ -12,8 +13,28 @@ export class Models extends APIResource {
* The Models API response can be used to determine information about a specific
* model or resolve a model alias to a model ID.
*/
- retrieve(modelId: string, options?: Core.RequestOptions): Core.APIPromise<ModelInfo> {
- return this._client.get(`/v1/models/${modelId}`, options);
+ retrieve(
+ modelId: string,
+ params?: ModelRetrieveParams,
+ options?: Core.RequestOptions,
+ ): Core.APIPromise<ModelInfo>;
+ retrieve(modelId: string, options?: Core.RequestOptions): Core.APIPromise<ModelInfo>;
+ retrieve(
+ modelId: string,
+ params: ModelRetrieveParams | Core.RequestOptions = {},
+ options?: Core.RequestOptions,
+ ): Core.APIPromise<ModelInfo> {
+ if (isRequestOptions(params)) {
+ return this.retrieve(modelId, {}, params);
+ }
+ const { betas } = params;
+ return this._client.get(`/v1/models/${modelId}`, {
+ ...options,
+ headers: {
+ ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined),
+ ...options?.headers,
+ },
+ });
}
/**
@@ -22,16 +43,24 @@ export class Models extends APIResource {
* The Models API response can be used to determine which models are available for
* use in the API. More recently released models are listed first.
*/
- list(query?: ModelListParams, options?: Core.RequestOptions): Core.PagePromise<ModelInfosPage, ModelInfo>;
+ list(params?: ModelListParams, options?: Core.RequestOptions): Core.PagePromise<ModelInfosPage, ModelInfo>;
list(options?: Core.RequestOptions): Core.PagePromise<ModelInfosPage, ModelInfo>;
list(
- query: ModelListParams | Core.RequestOptions = {},
+ params: ModelListParams | Core.RequestOptions = {},
options?: Core.RequestOptions,
): Core.PagePromise<ModelInfosPage, ModelInfo> {
- if (isRequestOptions(query)) {
- return this.list({}, query);
+ if (isRequestOptions(params)) {
+ return this.list({}, params);
}
- return this._client.getAPIList('/v1/models', ModelInfosPage, { query, ...options });
+ const { betas, ...query } = params;
+ return this._client.getAPIList('/v1/models', ModelInfosPage, {
+ query,
+ ...options,
+ headers: {
+ ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined),
+ ...options?.headers,
+ },
+ });
}
}
@@ -62,7 +91,19 @@ export interface ModelInfo {
type: 'model';
}
-export interface ModelListParams extends PageParams {}
+export interface ModelRetrieveParams {
+ /**
+ * Optional header to specify the beta version(s) you want to use.
+ */
+ betas?: Array<BetaAPI.AnthropicBeta>;
+}
+
+export interface ModelListParams extends PageParams {
+ /**
+ * Header param: Optional header to specify the beta version(s) you want to use.
+ */
+ betas?: Array<BetaAPI.AnthropicBeta>;
+}
Models.ModelInfosPage = ModelInfosPage;
@@ -70,6 +111,7 @@ export declare namespace Models {
export {
type ModelInfo as ModelInfo,
ModelInfosPage as ModelInfosPage,
+ type ModelRetrieveParams as ModelRetrieveParams,
type ModelListParams as ModelListParams,
};
}
diff --git src/version.ts src/version.ts
index e88a3c67..2f1576d5 100644
--- src/version.ts
+++ src/version.ts
@@ -1 +1 @@
-export const VERSION = '0.40.1'; // x-release-please-version
+export const VERSION = '0.41.0'; // x-release-please-version
diff --git tests/api-resources/MessageStream.test.ts tests/api-resources/MessageStream.test.ts
index 0788821a..d1912561 100644
--- tests/api-resources/MessageStream.test.ts
+++ tests/api-resources/MessageStream.test.ts
@@ -32,6 +32,19 @@ async function* messageIterable(message: Message): AsyncGenerator<MessageStreamE
}
: content.type === 'thinking' ? { type: 'thinking', thinking: '', signature: '' }
: content.type === 'redacted_thinking' ? { type: 'redacted_thinking', data: '' }
+ : content.type === 'server_tool_use' ?
+ {
+ type: 'server_tool_use',
+ id: 'toolu_01Up7oRoHeGvhded7n66nPzP',
+ name: 'web_search',
+ input: {},
+ }
+ : content.type === 'web_search_tool_result' ?
+ {
+ type: 'web_search_tool_result',
+ tool_use_id: 'toolu_01Up7oRoHeGvhded7n66nPzP',
+ content: [],
+ }
: assertNever(content),
index: idx,
};
@@ -58,6 +71,10 @@ async function* messageIterable(message: Message): AsyncGenerator<MessageStreamE
throw new Error('thinking not implemented yet');
} else if (content.type === 'redacted_thinking') {
throw new Error('redacted_thinking not implemented yet');
+ } else if (content.type === 'server_tool_use') {
+ throw new Error('server_tool_use not implemented yet');
+ } else if (content.type === 'web_search_tool_result') {
+ throw new Error('web_search_tool_result not implemented yet');
} else {
assertNever(content);
}
@@ -70,7 +87,13 @@ async function* messageIterable(message: Message): AsyncGenerator<MessageStreamE
yield {
type: 'message_delta',
- usage: { output_tokens: 6 },
+ usage: {
+ output_tokens: 6,
+ input_tokens: null,
+ cache_creation_input_tokens: null,
+ cache_read_input_tokens: null,
+ server_tool_use: null,
+ },
// @ts-ignore
delta: { stop_reason: message.stop_reason, stop_sequence: message.stop_sequence },
};
@@ -160,6 +183,7 @@ describe('MessageStream class', () => {
input_tokens: 10,
cache_creation_input_tokens: null,
cache_read_input_tokens: null,
+ server_tool_use: null,
},
}),
);
@@ -220,22 +244,22 @@ describe('MessageStream class', () => {
},
{
"args": [
- "{"type":"message_start","message":{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}}",
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message_start","message":{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "streamEvent",
},
{
"args": [
"{"type":"content_block_start","content_block":{"type":"text","text":"","citations":null},"index":0}",
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "streamEvent",
},
{
"args": [
"{"type":"content_block_delta","delta":{"type":"text_delta","text":"Hello"},"index":0}",
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "streamEvent",
},
@@ -249,7 +273,7 @@ describe('MessageStream class', () => {
{
"args": [
"{"type":"content_block_delta","delta":{"type":"text_delta","text":" ther"},"index":0}",
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello ther","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello ther","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "streamEvent",
},
@@ -263,7 +287,7 @@ describe('MessageStream class', () => {
{
"args": [
"{"type":"content_block_delta","delta":{"type":"text_delta","text":"e!"},"index":0}",
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "streamEvent",
},
@@ -277,7 +301,7 @@ describe('MessageStream class', () => {
{
"args": [
"{"type":"content_block_stop","index":0}",
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "streamEvent",
},
@@ -289,27 +313,27 @@ describe('MessageStream class', () => {
},
{
"args": [
- "{"type":"message_delta","usage":{"output_tokens":6},"delta":{"stop_reason":"end_turn","stop_sequence":null}}",
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":"end_turn","stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message_delta","usage":{"output_tokens":6,"input_tokens":null,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null},"delta":{"stop_reason":"end_turn","stop_sequence":null}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":"end_turn","stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "streamEvent",
},
{
"args": [
"{"type":"message_stop"}",
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":"end_turn","stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":"end_turn","stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "streamEvent",
},
{
"args": [
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":"end_turn","stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":"end_turn","stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "message",
},
{
"args": [
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":"end_turn","stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":"end_turn","stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "finalMessage",
},
@@ -342,6 +366,7 @@ describe('MessageStream class', () => {
"cache_read_input_tokens": null,
"input_tokens": 10,
"output_tokens": 6,
+ "server_tool_use": null,
},
}
`);
@@ -372,6 +397,7 @@ describe('MessageStream class', () => {
input_tokens: 10,
cache_creation_input_tokens: null,
cache_read_input_tokens: null,
+ server_tool_use: null,
},
}),
);
@@ -399,7 +425,7 @@ describe('MessageStream class', () => {
const stream = anthropic.messages.stream(
{
max_tokens: 1024,
- model: 'claude-2.1',
+ model: 'claude-3-7-sonnet-20250219',
messages: [{ role: 'user', content: 'Say hello there!' }],
},
{ maxRetries: 0 },
@@ -424,7 +450,7 @@ describe('MessageStream class', () => {
const stream = anthropic.messages.stream(
{
max_tokens: 1024,
- model: 'claude-2.1',
+ model: 'claude-3-7-sonnet-20250219',
messages: [{ role: 'user', content: 'Say hello there!' }],
},
{ maxRetries: 0 },
diff --git tests/api-resources/beta/models.test.ts tests/api-resources/beta/models.test.ts
index f155b632..ce7c72ab 100644
--- tests/api-resources/beta/models.test.ts
+++ tests/api-resources/beta/models.test.ts
@@ -27,6 +27,13 @@ describe('resource models', () => {
).rejects.toThrow(Anthropic.NotFoundError);
});
+ test('retrieve: request options and params are passed correctly', async () => {
+ // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error
+ await expect(
+ client.beta.models.retrieve('model_id', { betas: ['string'] }, { path: '/_stainless_unknown_path' }),
+ ).rejects.toThrow(Anthropic.NotFoundError);
+ });
+
test('list', async () => {
const responsePromise = client.beta.models.list();
const rawResponse = await responsePromise.asResponse();
@@ -49,7 +56,7 @@ describe('resource models', () => {
// ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error
await expect(
client.beta.models.list(
- { after_id: 'after_id', before_id: 'before_id', limit: 1 },
+ { after_id: 'after_id', before_id: 'before_id', limit: 1, betas: ['string'] },
{ path: '/_stainless_unknown_path' },
),
).rejects.toThrow(Anthropic.NotFoundError);
diff --git tests/api-resources/completions.test.ts tests/api-resources/completions.test.ts
index e3ebaa07..b372e474 100644
--- tests/api-resources/completions.test.ts
+++ tests/api-resources/completions.test.ts
@@ -35,6 +35,7 @@ describe('resource completions', () => {
temperature: 1,
top_k: 5,
top_p: 0.7,
+ betas: ['string'],
});
});
});
diff --git tests/api-resources/messages/batches.test.ts tests/api-resources/messages/batches.test.ts
index 95712a32..7c58ca3c 100644
--- tests/api-resources/messages/batches.test.ts
+++ tests/api-resources/messages/batches.test.ts
@@ -77,6 +77,7 @@ describe('resource batches', () => {
name: 'name',
cache_control: { type: 'ephemeral' },
description: 'Get the current weather in a given location',
+ type: 'custom',
},
],
top_k: 5,
diff --git tests/api-resources/messages/messages.test.ts tests/api-resources/messages/messages.test.ts
index 051a2c4f..b9b7bbc2 100644
--- tests/api-resources/messages/messages.test.ts
+++ tests/api-resources/messages/messages.test.ts
@@ -64,6 +64,7 @@ describe('resource messages', () => {
name: 'name',
cache_control: { type: 'ephemeral' },
description: 'Get the current weather in a given location',
+ type: 'custom',
},
],
top_k: 5,
@@ -120,6 +121,7 @@ describe('resource messages', () => {
name: 'name',
cache_control: { type: 'ephemeral' },
description: 'Get the current weather in a given location',
+ type: 'custom',
},
],
});
diff --git tests/api-resources/models.test.ts tests/api-resources/models.test.ts
index 7f5c0411..dc73dc26 100644
--- tests/api-resources/models.test.ts
+++ tests/api-resources/models.test.ts
@@ -27,6 +27,13 @@ describe('resource models', () => {
);
});
+ test('retrieve: request options and params are passed correctly', async () => {
+ // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error
+ await expect(
+ client.models.retrieve('model_id', { betas: ['string'] }, { path: '/_stainless_unknown_path' }),
+ ).rejects.toThrow(Anthropic.NotFoundError);
+ });
+
test('list', async () => {
const responsePromise = client.models.list();
const rawResponse = await responsePromise.asResponse();
@@ -49,7 +56,7 @@ describe('resource models', () => {
// ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error
await expect(
client.models.list(
- { after_id: 'after_id', before_id: 'before_id', limit: 1 },
+ { after_id: 'after_id', before_id: 'before_id', limit: 1, betas: ['string'] },
{ path: '/_stainless_unknown_path' },
),
).rejects.toThrow(Anthropic.NotFoundError);
Description
This PR adds web search capabilities to the Claude API in the Anthropic SDK for TypeScript. It includes new types for web search tools, API updates, documentation changes, examples, and bumps the SDK version from 0.40.1 to 0.41.0. The PR also updates Node.js version in CI workflows from 18 to 20.
Changes
Changes
Web Search Feature Implementation
-
New Types: Added numerous types related to web search functionality:
-
WebSearchTool20250305: Main interface for web search tool configuration -
WebSearchToolResultBlock: For search results content -
WebSearchResultBlock: For individual search results -
WebSearchToolRequestError: For error handling in web search -
CitationWebSearchResultLocation: For citations from web search results
-
Documentation and Examples
-
/examples/web-search.ts: Added example showing basic web search usage -
/examples/web-search-stream.ts: Added example for streaming web search results - Updated
README.md: Changed "Tool use beta" section to "Tool use" (removing beta designation) - Fixed typo in README: "as followed" -> "as follows"
- Enhanced API documentation with clearer parameter descriptions
Usage Statistics Updates
- Enhanced
UsageandMessageDeltaUsageinterfaces withserver_tool_usefield to track web search requests - Added support for new fields in usage statistics in stream handling
Workflows and Configuration
- Updated Node version from 18 to 20 in CI workflows
- Bumped version from 0.40.1 to 0.41.0 in multiple files
- Updated OpenAPI spec URL and hash in
.stats.yml
Type Improvements
- Extended
StopReasontype to include new reasons like 'pause_turn' and 'refusal' - Updated
MessageStreamandBetaMessageStreamto handle new usage fields
Testing
- Updated tests to handle new fields in usage tracking
- Added tests for web search capabilities
sequenceDiagram
participant Client
participant SDK
participant Anthropic API
participant SearchEngine
Client->>SDK: Create message with web_search tool
SDK->>Anthropic API: Request with web_search_20250305 tool
Anthropic API->>SearchEngine: Perform web search
SearchEngine-->>Anthropic API: Return search results
Anthropic API->>SDK: Search results in ServerToolUseBlock
SDK->>Client: Message with search results
Client->>SDK: Use results in follow-up message
SDK->>Anthropic API: New message with search context
Anthropic API->>SDK: Response with citations
SDK->>Client: Final response with web citations
anthropic debug - [puLL-Merge] - anthropics/[email protected]
Diff
diff --git .github/workflows/ci.yml .github/workflows/ci.yml
index f2f42e06..a021391c 100644
--- .github/workflows/ci.yml
+++ .github/workflows/ci.yml
@@ -72,7 +72,7 @@ jobs:
- name: Set up Node
uses: actions/setup-node@v4
with:
- node-version: '18'
+ node-version: '20'
- name: Bootstrap
run: ./scripts/bootstrap
diff --git .github/workflows/publish-npm.yml .github/workflows/publish-npm.yml
index b18decdf..7be59d8e 100644
--- .github/workflows/publish-npm.yml
+++ .github/workflows/publish-npm.yml
@@ -20,7 +20,7 @@ jobs:
- name: Set up Node
uses: actions/setup-node@v4
with:
- node-version: '18'
+ node-version: '20'
- name: Install dependencies
run: |
diff --git .release-please-manifest.json .release-please-manifest.json
index d2fc4414..5ee5f3b3 100644
--- .release-please-manifest.json
+++ .release-please-manifest.json
@@ -1,5 +1,5 @@
{
- ".": "0.40.1",
+ ".": "0.41.0",
"packages/vertex-sdk": "0.7.0",
"packages/bedrock-sdk": "0.12.6"
}
diff --git .stats.yml .stats.yml
index 30b9556d..5aa47f53 100644
--- .stats.yml
+++ .stats.yml
@@ -1,4 +1,4 @@
configured_endpoints: 21
-openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/anthropic%2Fanthropic-ea0576fceb17a0976feca9aa03aa426984d6fe1390f2bcdbf9de0212a81c8334.yml
-openapi_spec_hash: d2d7ec2a7a35a1ed2443c3b690c802c4
-config_hash: 9d5b992847099d8fe5a5c09e66adbe5f
+openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/anthropic%2Fanthropic-7015ea2d98991d6c2e7931c521e36448778fe868cc1b8a21173898d67b14b819.yml
+openapi_spec_hash: 2007ff815a3f39af8cebe1976d50f17d
+config_hash: 4d0dcf47d77eae22d34624d2ac0f0b46
diff --git CHANGELOG.md CHANGELOG.md
index 85f0e40f..53bbc93d 100644
--- CHANGELOG.md
+++ CHANGELOG.md
@@ -1,5 +1,24 @@
# Changelog
+## 0.41.0 (2025-05-07)
+
+Full Changelog: [sdk-v0.40.1...sdk-v0.41.0](https://github.com/anthropics/anthropic-sdk-typescript/compare/sdk-v0.40.1...sdk-v0.41.0)
+
+### Features
+
+* **api:** adds web search capabilities to the Claude API ([fae7e52](https://github.com/anthropics/anthropic-sdk-typescript/commit/fae7e521568d9659e376d13c4e4a6c320b13b1d4))
+
+
+### Chores
+
+* **ci:** bump node version for release workflows ([3502747](https://github.com/anthropics/anthropic-sdk-typescript/commit/350274792ed3d9b7ea237ee60876883373344016))
+
+
+### Documentation
+
+* add examples to tsdocs ([19a9285](https://github.com/anthropics/anthropic-sdk-typescript/commit/19a928512b1616f2cac9c82f02e7bd9a158dab95))
+* **readme:** fix typo ([735574e](https://github.com/anthropics/anthropic-sdk-typescript/commit/735574e23b7956cbfd0c05d0374079391d5d4e96))
+
## 0.40.1 (2025-04-28)
Full Changelog: [sdk-v0.40.0...sdk-v0.40.1](https://github.com/anthropics/anthropic-sdk-typescript/compare/sdk-v0.40.0...sdk-v0.40.1)
diff --git README.md README.md
index cafba323..9e6e15bb 100644
--- README.md
+++ README.md
@@ -183,9 +183,9 @@ for await (const entry of results) {
}
```
-## Tool use beta
+## Tool use
-This SDK provides beta support for tool use, aka function calling. More details can be found in [the documentation](https://docs.anthropic.com/claude/docs/tool-use).
+This SDK provides support for tool use, aka function calling. More details can be found in [the documentation](https://docs.anthropic.com/claude/docs/tool-use).
## AWS Bedrock
@@ -220,7 +220,7 @@ async function main() {
main();
```
-Error codes are as followed:
+Error codes are as follows:
| Status Code | Error Type |
| ----------- | -------------------------- |
diff --git api.md api.md
index 2010bc5f..78a2bac0 100644
--- api.md
+++ api.md
@@ -29,8 +29,10 @@ Types:
- <code><a href="./src/resources/messages/messages.ts">CitationContentBlockLocationParam</a></code>
- <code><a href="./src/resources/messages/messages.ts">CitationPageLocation</a></code>
- <code><a href="./src/resources/messages/messages.ts">CitationPageLocationParam</a></code>
+- <code><a href="./src/resources/messages/messages.ts">CitationWebSearchResultLocationParam</a></code>
- <code><a href="./src/resources/messages/messages.ts">CitationsConfigParam</a></code>
- <code><a href="./src/resources/messages/messages.ts">CitationsDelta</a></code>
+- <code><a href="./src/resources/messages/messages.ts">CitationsWebSearchResultLocation</a></code>
- <code><a href="./src/resources/messages/messages.ts">ContentBlock</a></code>
- <code><a href="./src/resources/messages/messages.ts">ContentBlockParam</a></code>
- <code><a href="./src/resources/messages/messages.ts">ContentBlockSource</a></code>
@@ -56,6 +58,9 @@ Types:
- <code><a href="./src/resources/messages/messages.ts">RawMessageStreamEvent</a></code>
- <code><a href="./src/resources/messages/messages.ts">RedactedThinkingBlock</a></code>
- <code><a href="./src/resources/messages/messages.ts">RedactedThinkingBlockParam</a></code>
+- <code><a href="./src/resources/messages/messages.ts">ServerToolUsage</a></code>
+- <code><a href="./src/resources/messages/messages.ts">ServerToolUseBlock</a></code>
+- <code><a href="./src/resources/messages/messages.ts">ServerToolUseBlockParam</a></code>
- <code><a href="./src/resources/messages/messages.ts">SignatureDelta</a></code>
- <code><a href="./src/resources/messages/messages.ts">StopReason</a></code>
- <code><a href="./src/resources/messages/messages.ts">TextBlock</a></code>
@@ -84,6 +89,15 @@ Types:
- <code><a href="./src/resources/messages/messages.ts">URLImageSource</a></code>
- <code><a href="./src/resources/messages/messages.ts">URLPDFSource</a></code>
- <code><a href="./src/resources/messages/messages.ts">Usage</a></code>
+- <code><a href="./src/resources/messages/messages.ts">WebSearchResultBlock</a></code>
+- <code><a href="./src/resources/messages/messages.ts">WebSearchResultBlockParam</a></code>
+- <code><a href="./src/resources/messages/messages.ts">WebSearchTool20250305</a></code>
+- <code><a href="./src/resources/messages/messages.ts">WebSearchToolRequestError</a></code>
+- <code><a href="./src/resources/messages/messages.ts">WebSearchToolResultBlock</a></code>
+- <code><a href="./src/resources/messages/messages.ts">WebSearchToolResultBlockContent</a></code>
+- <code><a href="./src/resources/messages/messages.ts">WebSearchToolResultBlockParam</a></code>
+- <code><a href="./src/resources/messages/messages.ts">WebSearchToolResultBlockParamContent</a></code>
+- <code><a href="./src/resources/messages/messages.ts">WebSearchToolResultError</a></code>
- <code><a href="./src/resources/messages/messages.ts">MessageStreamEvent</a></code>
- <code><a href="./src/resources/messages/messages.ts">MessageStartEvent</a></code>
- <code><a href="./src/resources/messages/messages.ts">MessageDeltaEvent</a></code>
@@ -129,7 +143,7 @@ Types:
Methods:
-- <code title="get /v1/models/{model_id}">client.models.<a href="./src/resources/models.ts">retrieve</a>(modelId) -> ModelInfo</code>
+- <code title="get /v1/models/{model_id}">client.models.<a href="./src/resources/models.ts">retrieve</a>(modelId, { ...params }) -> ModelInfo</code>
- <code title="get /v1/models">client.models.<a href="./src/resources/models.ts">list</a>({ ...params }) -> ModelInfosPage</code>
# Beta
@@ -157,7 +171,7 @@ Types:
Methods:
-- <code title="get /v1/models/{model_id}?beta=true">client.beta.models.<a href="./src/resources/beta/models.ts">retrieve</a>(modelId) -> BetaModelInfo</code>
+- <code title="get /v1/models/{model_id}?beta=true">client.beta.models.<a href="./src/resources/beta/models.ts">retrieve</a>(modelId, { ...params }) -> BetaModelInfo</code>
- <code title="get /v1/models?beta=true">client.beta.models.<a href="./src/resources/beta/models.ts">list</a>({ ...params }) -> BetaModelInfosPage</code>
## Messages
@@ -174,8 +188,10 @@ Types:
- <code><a href="./src/resources/beta/messages/messages.ts">BetaCitationContentBlockLocationParam</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaCitationPageLocation</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaCitationPageLocationParam</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaCitationWebSearchResultLocationParam</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaCitationsConfigParam</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaCitationsDelta</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaCitationsWebSearchResultLocation</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaContentBlock</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaContentBlockParam</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaContentBlockSource</a></code>
@@ -198,6 +214,9 @@ Types:
- <code><a href="./src/resources/beta/messages/messages.ts">BetaRawMessageStreamEvent</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaRedactedThinkingBlock</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaRedactedThinkingBlockParam</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaServerToolUsage</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaServerToolUseBlock</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaServerToolUseBlockParam</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaSignatureDelta</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaStopReason</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaTextBlock</a></code>
@@ -230,6 +249,15 @@ Types:
- <code><a href="./src/resources/beta/messages/messages.ts">BetaURLImageSource</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaURLPDFSource</a></code>
- <code><a href="./src/resources/beta/messages/messages.ts">BetaUsage</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaWebSearchResultBlock</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaWebSearchResultBlockParam</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaWebSearchTool20250305</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaWebSearchToolRequestError</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaWebSearchToolResultBlock</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaWebSearchToolResultBlockContent</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaWebSearchToolResultBlockParam</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaWebSearchToolResultBlockParamContent</a></code>
+- <code><a href="./src/resources/beta/messages/messages.ts">BetaWebSearchToolResultError</a></code>
Methods:
diff --git examples/tools.ts examples/tools.ts
index 1a696bc0..8928efb0 100644
--- examples/tools.ts
+++ examples/tools.ts
@@ -49,7 +49,7 @@ async function main() {
{
type: 'tool_result',
tool_use_id: tool.id,
- content: [{ type: 'text', text: 'The weather is 73f' }],
+ content: 'The weather is 73f',
},
],
},
diff --git a/examples/web-search-stream.ts b/examples/web-search-stream.ts
new file mode 100755
index 00000000..38d08d46
--- /dev/null
+++ examples/web-search-stream.ts
@@ -0,0 +1,64 @@
+#!/usr/bin/env -S npm run tsn -T
+
+import Anthropic from '@anthropic-ai/sdk';
+
+const client = new Anthropic();
+
+async function main() {
+ console.log('Claude with Web Search (Streaming)');
+ console.log('==================================');
+
+ // Create a stream with web search enabled
+ const stream = client.messages
+ .stream({
+ model: 'claude-3-5-sonnet-latest',
+ max_tokens: 1024,
+ messages: [
+ {
+ role: 'user',
+ content: "What's the weather in New York?",
+ },
+ ],
+ tools: [
+ {
+ name: 'web_search',
+ type: 'web_search_20250305',
+ },
+ ],
+ })
+ .on('text', (text) => {
+ // Print text as it arrives
+ process.stdout.write(text);
+ })
+ .on('streamEvent', (event) => {
+ // Track when web search is being used
+ if (event.type === 'content_block_start' && event.content_block.type === 'web_search_tool_result') {
+ process.stdout.write('\n[Web search started...]');
+ }
+ });
+
+ // Wait for the stream to complete
+ const message = await stream.finalMessage();
+
+ console.log('\n\nFinal usage statistics:');
+ console.log(`Input tokens: ${message.usage.input_tokens}`);
+ console.log(`Output tokens: ${message.usage.output_tokens}`);
+
+ if (message.usage.server_tool_use) {
+ console.log(`Web search requests: ${message.usage.server_tool_use.web_search_requests}`);
+ } else {
+ console.log('No web search requests recorded in usage');
+ }
+
+ // Display message content types for debugging
+ console.log('\nMessage Content Types:');
+ message.content.forEach((block, i) => {
+ console.log(`Content Block ${i + 1}: Type = ${block.type}`);
+ });
+
+ // Show full message for debugging
+ console.log('\nComplete message structure:');
+ console.dir(message, { depth: 4 });
+}
+
+main().catch(console.error);
diff --git a/examples/web-search.ts b/examples/web-search.ts
new file mode 100755
index 00000000..e5c528ac
--- /dev/null
+++ examples/web-search.ts
@@ -0,0 +1,52 @@
+#!/usr/bin/env -S npm run tsn -T
+
+import Anthropic from '@anthropic-ai/sdk';
+
+const client = new Anthropic();
+
+async function main() {
+ console.log('Web Search Example');
+ console.log('=================');
+
+ // Create a message with web search enabled
+ const message = await client.messages.create({
+ model: 'claude-3-5-sonnet-latest',
+ max_tokens: 1024,
+ messages: [
+ {
+ role: 'user',
+ content:
+ "What's the current weather in San Francisco? Please search the web for up-to-date information.",
+ },
+ ],
+ tools: [
+ {
+ name: 'web_search',
+ type: 'web_search_20250305',
+ },
+ ],
+ });
+
+ // Print the full response
+ console.log('\nFull response:');
+ console.dir(message, { depth: 4 });
+
+ // Extract and print the content
+ console.log('\nResponse content:');
+ for (const contentBlock of message.content) {
+ if (contentBlock.type === 'text') {
+ console.log(contentBlock.text);
+ }
+ }
+
+ // Print usage information
+ console.log('\nUsage statistics:');
+ console.log(`Input tokens: ${message.usage.input_tokens}`);
+ console.log(`Output tokens: ${message.usage.output_tokens}`);
+
+ if (message.usage.server_tool_use) {
+ console.log(`Web search requests: ${message.usage.server_tool_use.web_search_requests}`);
+ }
+}
+
+main().catch(console.error);
diff --git package.json package.json
index 898d950c..451b1d7b 100644
--- package.json
+++ package.json
@@ -1,6 +1,6 @@
{
"name": "@anthropic-ai/sdk",
- "version": "0.40.1",
+ "version": "0.41.0",
"description": "The official TypeScript library for the Anthropic API",
"author": "Anthropic <[email protected]>",
"types": "dist/index.d.ts",
diff --git src/index.ts src/index.ts
index 3d901bea..ccfa494e 100644
--- src/index.ts
+++ src/index.ts
@@ -14,7 +14,7 @@ import {
CompletionCreateParamsStreaming,
Completions,
} from './resources/completions';
-import { ModelInfo, ModelInfosPage, ModelListParams, Models } from './resources/models';
+import { ModelInfo, ModelInfosPage, ModelListParams, ModelRetrieveParams, Models } from './resources/models';
import {
AnthropicBeta,
Beta,
@@ -40,8 +40,10 @@ import {
CitationContentBlockLocationParam,
CitationPageLocation,
CitationPageLocationParam,
+ CitationWebSearchResultLocationParam,
CitationsConfigParam,
CitationsDelta,
+ CitationsWebSearchResultLocation,
ContentBlock,
ContentBlockDeltaEvent,
ContentBlockParam,
@@ -80,6 +82,9 @@ import {
RawMessageStreamEvent,
RedactedThinkingBlock,
RedactedThinkingBlockParam,
+ ServerToolUsage,
+ ServerToolUseBlock,
+ ServerToolUseBlockParam,
SignatureDelta,
StopReason,
TextBlock,
@@ -108,6 +113,15 @@ import {
URLImageSource,
URLPDFSource,
Usage,
+ WebSearchResultBlock,
+ WebSearchResultBlockParam,
+ WebSearchTool20250305,
+ WebSearchToolRequestError,
+ WebSearchToolResultBlock,
+ WebSearchToolResultBlockContent,
+ WebSearchToolResultBlockParam,
+ WebSearchToolResultBlockParamContent,
+ WebSearchToolResultError,
} from './resources/messages/messages';
export interface ClientOptions {
@@ -354,8 +368,10 @@ export declare namespace Anthropic {
type CitationContentBlockLocationParam as CitationContentBlockLocationParam,
type CitationPageLocation as CitationPageLocation,
type CitationPageLocationParam as CitationPageLocationParam,
+ type CitationWebSearchResultLocationParam as CitationWebSearchResultLocationParam,
type CitationsConfigParam as CitationsConfigParam,
type CitationsDelta as CitationsDelta,
+ type CitationsWebSearchResultLocation as CitationsWebSearchResultLocation,
type ContentBlock as ContentBlock,
type ContentBlockParam as ContentBlockParam,
type ContentBlockSource as ContentBlockSource,
@@ -381,6 +397,9 @@ export declare namespace Anthropic {
type RawMessageStreamEvent as RawMessageStreamEvent,
type RedactedThinkingBlock as RedactedThinkingBlock,
type RedactedThinkingBlockParam as RedactedThinkingBlockParam,
+ type ServerToolUsage as ServerToolUsage,
+ type ServerToolUseBlock as ServerToolUseBlock,
+ type ServerToolUseBlockParam as ServerToolUseBlockParam,
type SignatureDelta as SignatureDelta,
type StopReason as StopReason,
type TextBlock as TextBlock,
@@ -409,6 +428,15 @@ export declare namespace Anthropic {
type URLImageSource as URLImageSource,
type URLPDFSource as URLPDFSource,
type Usage as Usage,
+ type WebSearchResultBlock as WebSearchResultBlock,
+ type WebSearchResultBlockParam as WebSearchResultBlockParam,
+ type WebSearchTool20250305 as WebSearchTool20250305,
+ type WebSearchToolRequestError as WebSearchToolRequestError,
+ type WebSearchToolResultBlock as WebSearchToolResultBlock,
+ type WebSearchToolResultBlockContent as WebSearchToolResultBlockContent,
+ type WebSearchToolResultBlockParam as WebSearchToolResultBlockParam,
+ type WebSearchToolResultBlockParamContent as WebSearchToolResultBlockParamContent,
+ type WebSearchToolResultError as WebSearchToolResultError,
type MessageStreamEvent as MessageStreamEvent,
type MessageStartEvent as MessageStartEvent,
type MessageDeltaEvent as MessageDeltaEvent,
@@ -427,6 +455,7 @@ export declare namespace Anthropic {
Models as Models,
type ModelInfo as ModelInfo,
ModelInfosPage as ModelInfosPage,
+ type ModelRetrieveParams as ModelRetrieveParams,
type ModelListParams as ModelListParams,
};
diff --git src/lib/BetaMessageStream.ts src/lib/BetaMessageStream.ts
index fd096926..7ad1d89f 100644
--- src/lib/BetaMessageStream.ts
+++ src/lib/BetaMessageStream.ts
@@ -530,6 +530,15 @@ export class BetaMessageStream implements AsyncIterable<BetaMessageStreamEvent>
snapshot.stop_reason = event.delta.stop_reason;
snapshot.stop_sequence = event.delta.stop_sequence;
snapshot.usage.output_tokens = event.usage.output_tokens;
+
+ // Update other usage fields if they exist in the event
+ if (event.usage.input_tokens) {
+ snapshot.usage.input_tokens = event.usage.input_tokens;
+ }
+ snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens;
+ snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens;
+ snapshot.usage.server_tool_use = event.usage.server_tool_use;
+
return snapshot;
case 'content_block_start':
snapshot.content.push(event.content_block);
diff --git src/lib/MessageStream.ts src/lib/MessageStream.ts
index 712a34ff..af81bf68 100644
--- src/lib/MessageStream.ts
+++ src/lib/MessageStream.ts
@@ -530,6 +530,15 @@ export class MessageStream implements AsyncIterable<MessageStreamEvent> {
snapshot.stop_reason = event.delta.stop_reason;
snapshot.stop_sequence = event.delta.stop_sequence;
snapshot.usage.output_tokens = event.usage.output_tokens;
+
+ // Update other usage fields if they exist in the event
+ if (event.usage.input_tokens) {
+ snapshot.usage.input_tokens = event.usage.input_tokens;
+ }
+ snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens;
+ snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens;
+ snapshot.usage.server_tool_use = event.usage.server_tool_use;
+
return snapshot;
case 'content_block_start':
snapshot.content.push(event.content_block);
diff --git src/resources/beta/beta.ts src/resources/beta/beta.ts
index 69578396..fc16229a 100644
--- src/resources/beta/beta.ts
+++ src/resources/beta/beta.ts
@@ -2,7 +2,7 @@
import { APIResource } from '../../resource';
import * as ModelsAPI from './models';
-import { BetaModelInfo, BetaModelInfosPage, ModelListParams, Models } from './models';
+import { BetaModelInfo, BetaModelInfosPage, ModelListParams, ModelRetrieveParams, Models } from './models';
import * as MessagesAPI from './messages/messages';
import {
BetaBase64ImageSource,
@@ -15,8 +15,10 @@ import {
BetaCitationContentBlockLocationParam,
BetaCitationPageLocation,
BetaCitationPageLocationParam,
+ BetaCitationWebSearchResultLocationParam,
BetaCitationsConfigParam,
BetaCitationsDelta,
+ BetaCitationsWebSearchResultLocation,
BetaContentBlock,
BetaContentBlockParam,
BetaContentBlockSource,
@@ -39,6 +41,9 @@ import {
BetaRawMessageStreamEvent,
BetaRedactedThinkingBlock,
BetaRedactedThinkingBlockParam,
+ BetaServerToolUsage,
+ BetaServerToolUseBlock,
+ BetaServerToolUseBlockParam,
BetaSignatureDelta,
BetaStopReason,
BetaTextBlock,
@@ -71,6 +76,15 @@ import {
BetaURLImageSource,
BetaURLPDFSource,
BetaUsage,
+ BetaWebSearchResultBlock,
+ BetaWebSearchResultBlockParam,
+ BetaWebSearchTool20250305,
+ BetaWebSearchToolRequestError,
+ BetaWebSearchToolResultBlock,
+ BetaWebSearchToolResultBlockContent,
+ BetaWebSearchToolResultBlockParam,
+ BetaWebSearchToolResultBlockParamContent,
+ BetaWebSearchToolResultError,
MessageCountTokensParams,
MessageCreateParams,
MessageCreateParamsNonStreaming,
@@ -189,6 +203,7 @@ export declare namespace Beta {
Models as Models,
type BetaModelInfo as BetaModelInfo,
BetaModelInfosPage as BetaModelInfosPage,
+ type ModelRetrieveParams as ModelRetrieveParams,
type ModelListParams as ModelListParams,
};
@@ -204,8 +219,10 @@ export declare namespace Beta {
type BetaCitationContentBlockLocationParam as BetaCitationContentBlockLocationParam,
type BetaCitationPageLocation as BetaCitationPageLocation,
type BetaCitationPageLocationParam as BetaCitationPageLocationParam,
+ type BetaCitationWebSearchResultLocationParam as BetaCitationWebSearchResultLocationParam,
type BetaCitationsConfigParam as BetaCitationsConfigParam,
type BetaCitationsDelta as BetaCitationsDelta,
+ type BetaCitationsWebSearchResultLocation as BetaCitationsWebSearchResultLocation,
type BetaContentBlock as BetaContentBlock,
type BetaContentBlockParam as BetaContentBlockParam,
type BetaContentBlockSource as BetaContentBlockSource,
@@ -228,6 +245,9 @@ export declare namespace Beta {
type BetaRawMessageStreamEvent as BetaRawMessageStreamEvent,
type BetaRedactedThinkingBlock as BetaRedactedThinkingBlock,
type BetaRedactedThinkingBlockParam as BetaRedactedThinkingBlockParam,
+ type BetaServerToolUsage as BetaServerToolUsage,
+ type BetaServerToolUseBlock as BetaServerToolUseBlock,
+ type BetaServerToolUseBlockParam as BetaServerToolUseBlockParam,
type BetaSignatureDelta as BetaSignatureDelta,
type BetaStopReason as BetaStopReason,
type BetaTextBlock as BetaTextBlock,
@@ -260,6 +280,15 @@ export declare namespace Beta {
type BetaURLImageSource as BetaURLImageSource,
type BetaURLPDFSource as BetaURLPDFSource,
type BetaUsage as BetaUsage,
+ type BetaWebSearchResultBlock as BetaWebSearchResultBlock,
+ type BetaWebSearchResultBlockParam as BetaWebSearchResultBlockParam,
+ type BetaWebSearchTool20250305 as BetaWebSearchTool20250305,
+ type BetaWebSearchToolRequestError as BetaWebSearchToolRequestError,
+ type BetaWebSearchToolResultBlock as BetaWebSearchToolResultBlock,
+ type BetaWebSearchToolResultBlockContent as BetaWebSearchToolResultBlockContent,
+ type BetaWebSearchToolResultBlockParam as BetaWebSearchToolResultBlockParam,
+ type BetaWebSearchToolResultBlockParamContent as BetaWebSearchToolResultBlockParamContent,
+ type BetaWebSearchToolResultError as BetaWebSearchToolResultError,
type MessageCreateParams as MessageCreateParams,
type MessageCreateParamsNonStreaming as MessageCreateParamsNonStreaming,
type MessageCreateParamsStreaming as MessageCreateParamsStreaming,
diff --git src/resources/beta/index.ts src/resources/beta/index.ts
index 4402c642..8abd778f 100644
--- src/resources/beta/index.ts
+++ src/resources/beta/index.ts
@@ -15,7 +15,13 @@ export {
type BetaPermissionError,
type BetaRateLimitError,
} from './beta';
-export { BetaModelInfosPage, Models, type BetaModelInfo, type ModelListParams } from './models';
+export {
+ BetaModelInfosPage,
+ Models,
+ type BetaModelInfo,
+ type ModelRetrieveParams,
+ type ModelListParams,
+} from './models';
export {
Messages,
type BetaBase64ImageSource,
@@ -28,8 +34,10 @@ export {
type BetaCitationContentBlockLocationParam,
type BetaCitationPageLocation,
type BetaCitationPageLocationParam,
+ type BetaCitationWebSearchResultLocationParam,
type BetaCitationsConfigParam,
type BetaCitationsDelta,
+ type BetaCitationsWebSearchResultLocation,
type BetaContentBlock,
type BetaContentBlockParam,
type BetaContentBlockSource,
@@ -52,6 +60,9 @@ export {
type BetaRawMessageStreamEvent,
type BetaRedactedThinkingBlock,
type BetaRedactedThinkingBlockParam,
+ type BetaServerToolUsage,
+ type BetaServerToolUseBlock,
+ type BetaServerToolUseBlockParam,
type BetaSignatureDelta,
type BetaStopReason,
type BetaTextBlock,
@@ -84,6 +95,15 @@ export {
type BetaURLImageSource,
type BetaURLPDFSource,
type BetaUsage,
+ type BetaWebSearchResultBlock,
+ type BetaWebSearchResultBlockParam,
+ type BetaWebSearchTool20250305,
+ type BetaWebSearchToolRequestError,
+ type BetaWebSearchToolResultBlock,
+ type BetaWebSearchToolResultBlockContent,
+ type BetaWebSearchToolResultBlockParam,
+ type BetaWebSearchToolResultBlockParamContent,
+ type BetaWebSearchToolResultError,
type MessageCreateParams,
type MessageCreateParamsNonStreaming,
type MessageCreateParamsStreaming,
diff --git src/resources/beta/messages/batches.ts src/resources/beta/messages/batches.ts
index ba6fce27..dde90fac 100644
--- src/resources/beta/messages/batches.ts
+++ src/resources/beta/messages/batches.ts
@@ -20,6 +20,25 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const betaMessageBatch =
+ * await client.beta.messages.batches.create({
+ * requests: [
+ * {
+ * custom_id: 'my-custom-id-1',
+ * params: {
+ * max_tokens: 1024,
+ * messages: [
+ * { content: 'Hello, world', role: 'user' },
+ * ],
+ * model: 'claude-3-7-sonnet-20250219',
+ * },
+ * },
+ * ],
+ * });
+ * ```
*/
create(params: BatchCreateParams, options?: Core.RequestOptions): Core.APIPromise<BetaMessageBatch> {
const { betas, ...body } = params;
@@ -40,6 +59,14 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const betaMessageBatch =
+ * await client.beta.messages.batches.retrieve(
+ * 'message_batch_id',
+ * );
+ * ```
*/
retrieve(
messageBatchId: string,
@@ -71,6 +98,14 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const betaMessageBatch of client.beta.messages.batches.list()) {
+ * // ...
+ * }
+ * ```
*/
list(
params?: BatchListParams,
@@ -103,6 +138,14 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const betaDeletedMessageBatch =
+ * await client.beta.messages.batches.delete(
+ * 'message_batch_id',
+ * );
+ * ```
*/
delete(
messageBatchId: string,
@@ -141,6 +184,14 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const betaMessageBatch =
+ * await client.beta.messages.batches.cancel(
+ * 'message_batch_id',
+ * );
+ * ```
*/
cancel(
messageBatchId: string,
@@ -175,6 +226,14 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const betaMessageBatchIndividualResponse =
+ * await client.beta.messages.batches.results(
+ * 'message_batch_id',
+ * );
+ * ```
*/
async results(
messageBatchId: string,
diff --git src/resources/beta/messages/index.ts src/resources/beta/messages/index.ts
index 39bfffd8..5a5d04bd 100644
--- src/resources/beta/messages/index.ts
+++ src/resources/beta/messages/index.ts
@@ -31,8 +31,10 @@ export {
type BetaCitationContentBlockLocationParam,
type BetaCitationPageLocation,
type BetaCitationPageLocationParam,
+ type BetaCitationWebSearchResultLocationParam,
type BetaCitationsConfigParam,
type BetaCitationsDelta,
+ type BetaCitationsWebSearchResultLocation,
type BetaContentBlock,
type BetaContentBlockParam,
type BetaContentBlockSource,
@@ -55,6 +57,9 @@ export {
type BetaRawMessageStreamEvent,
type BetaRedactedThinkingBlock,
type BetaRedactedThinkingBlockParam,
+ type BetaServerToolUsage,
+ type BetaServerToolUseBlock,
+ type BetaServerToolUseBlockParam,
type BetaSignatureDelta,
type BetaStopReason,
type BetaTextBlock,
@@ -87,6 +92,15 @@ export {
type BetaURLImageSource,
type BetaURLPDFSource,
type BetaUsage,
+ type BetaWebSearchResultBlock,
+ type BetaWebSearchResultBlockParam,
+ type BetaWebSearchTool20250305,
+ type BetaWebSearchToolRequestError,
+ type BetaWebSearchToolResultBlock,
+ type BetaWebSearchToolResultBlockContent,
+ type BetaWebSearchToolResultBlockParam,
+ type BetaWebSearchToolResultBlockParamContent,
+ type BetaWebSearchToolResultError,
type MessageCreateParams,
type MessageCreateParamsNonStreaming,
type MessageCreateParamsStreaming,
diff --git src/resources/beta/messages/messages.ts src/resources/beta/messages/messages.ts
index bc9fb874..e961cf1c 100644
--- src/resources/beta/messages/messages.ts
+++ src/resources/beta/messages/messages.ts
@@ -54,6 +54,15 @@ export class Messages extends APIResource {
* conversations.
*
* Learn more about the Messages API in our [user guide](/en/docs/initial-setup)
+ *
+ * @example
+ * ```ts
+ * const betaMessage = await client.beta.messages.create({
+ * max_tokens: 1024,
+ * messages: [{ content: 'Hello, world', role: 'user' }],
+ * model: 'claude-3-7-sonnet-20250219',
+ * });
+ * ```
*/
create(params: MessageCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<BetaMessage>;
create(
@@ -107,6 +116,15 @@ export class Messages extends APIResource {
*
* Learn more about token counting in our
* [user guide](/en/docs/build-with-claude/token-counting)
+ *
+ * @example
+ * ```ts
+ * const betaMessageTokensCount =
+ * await client.beta.messages.countTokens({
+ * messages: [{ content: 'string', role: 'user' }],
+ * model: 'claude-3-7-sonnet-latest',
+ * });
+ * ```
*/
countTokens(
params: MessageCountTokensParams,
@@ -139,6 +157,9 @@ export interface BetaBase64PDFBlock {
type: 'document';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
citations?: BetaCitationsConfigParam;
@@ -244,19 +265,49 @@ export interface BetaCitationPageLocationParam {
type: 'page_location';
}
+export interface BetaCitationWebSearchResultLocationParam {
+ cited_text: string;
+
+ encrypted_index: string;
+
+ title: string | null;
+
+ type: 'web_search_result_location';
+
+ url: string;
+}
+
export interface BetaCitationsConfigParam {
enabled?: boolean;
}
export interface BetaCitationsDelta {
- citation: BetaCitationCharLocation | BetaCitationPageLocation | BetaCitationContentBlockLocation;
+ citation:
+ | BetaCitationCharLocation
+ | BetaCitationPageLocation
+ | BetaCitationContentBlockLocation
+ | BetaCitationsWebSearchResultLocation;
type: 'citations_delta';
}
+export interface BetaCitationsWebSearchResultLocation {
+ cited_text: string;
+
+ encrypted_index: string;
+
+ title: string | null;
+
+ type: 'web_search_result_location';
+
+ url: string;
+}
+
export type BetaContentBlock =
| BetaTextBlock
| BetaToolUseBlock
+ | BetaServerToolUseBlock
+ | BetaWebSearchToolResultBlock
| BetaThinkingBlock
| BetaRedactedThinkingBlock;
@@ -264,6 +315,8 @@ export type BetaContentBlockParam =
| BetaTextBlockParam
| BetaImageBlockParam
| BetaToolUseBlockParam
+ | BetaServerToolUseBlockParam
+ | BetaWebSearchToolResultBlockParam
| BetaToolResultBlockParam
| BetaBase64PDFBlock
| BetaThinkingBlockParam
@@ -282,6 +335,9 @@ export interface BetaImageBlockParam {
type: 'image';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
}
@@ -400,10 +456,30 @@ export interface BetaMessage {
}
export interface BetaMessageDeltaUsage {
+ /**
+ * The cumulative number of input tokens used to create the cache entry.
+ */
+ cache_creation_input_tokens: number | null;
+
+ /**
+ * The cumulative number of input tokens read from the cache.
+ */
+ cache_read_input_tokens: number | null;
+
+ /**
+ * The cumulative number of input tokens which were used.
+ */
+ input_tokens: number | null;
+
/**
* The cumulative number of output tokens which were used.
*/
output_tokens: number;
+
+ /**
+ * The number of server tool requests.
+ */
+ server_tool_use: BetaServerToolUsage | null;
}
export interface BetaMessageParam {
@@ -455,7 +531,13 @@ export interface BetaRawContentBlockDeltaEvent {
}
export interface BetaRawContentBlockStartEvent {
- content_block: BetaTextBlock | BetaToolUseBlock | BetaThinkingBlock | BetaRedactedThinkingBlock;
+ content_block:
+ | BetaTextBlock
+ | BetaToolUseBlock
+ | BetaServerToolUseBlock
+ | BetaWebSearchToolResultBlock
+ | BetaThinkingBlock
+ | BetaRedactedThinkingBlock;
index: number;
@@ -531,13 +613,51 @@ export interface BetaRedactedThinkingBlockParam {
type: 'redacted_thinking';
}
+export interface BetaServerToolUsage {
+ /**
+ * The number of web search tool requests.
+ */
+ web_search_requests: number;
+}
+
+export interface BetaServerToolUseBlock {
+ id: string;
+
+ input: unknown;
+
+ name: 'web_search';
+
+ type: 'server_tool_use';
+}
+
+export interface BetaServerToolUseBlockParam {
+ id: string;
+
+ input: unknown;
+
+ name: 'web_search';
+
+ type: 'server_tool_use';
+
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
+ cache_control?: BetaCacheControlEphemeral | null;
+}
+
export interface BetaSignatureDelta {
signature: string;
type: 'signature_delta';
}
-export type BetaStopReason = 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use';
+export type BetaStopReason =
+ | 'end_turn'
+ | 'max_tokens'
+ | 'stop_sequence'
+ | 'tool_use'
+ | 'pause_turn'
+ | 'refusal';
export interface BetaTextBlock {
/**
@@ -559,6 +679,9 @@ export interface BetaTextBlockParam {
type: 'text';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
citations?: Array<BetaTextCitationParam> | null;
@@ -567,12 +690,14 @@ export interface BetaTextBlockParam {
export type BetaTextCitation =
| BetaCitationCharLocation
| BetaCitationPageLocation
- | BetaCitationContentBlockLocation;
+ | BetaCitationContentBlockLocation
+ | BetaCitationsWebSearchResultLocation;
export type BetaTextCitationParam =
| BetaCitationCharLocationParam
| BetaCitationPageLocationParam
- | BetaCitationContentBlockLocationParam;
+ | BetaCitationContentBlockLocationParam
+ | BetaCitationWebSearchResultLocationParam;
export interface BetaTextDelta {
text: string;
@@ -648,10 +773,13 @@ export interface BetaTool {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: string;
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
/**
@@ -687,12 +815,15 @@ export interface BetaToolBash20241022 {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: 'bash';
type: 'bash_20241022';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
}
@@ -700,12 +831,15 @@ export interface BetaToolBash20250124 {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: 'bash';
type: 'bash_20250124';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
}
@@ -786,12 +920,15 @@ export interface BetaToolComputerUse20241022 {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: 'computer';
type: 'computer_20241022';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
/**
@@ -814,12 +951,15 @@ export interface BetaToolComputerUse20250124 {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: 'computer';
type: 'computer_20250124';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
/**
@@ -833,6 +973,9 @@ export interface BetaToolResultBlockParam {
type: 'tool_result';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
content?: string | Array<BetaTextBlockParam | BetaImageBlockParam>;
@@ -844,12 +987,15 @@ export interface BetaToolTextEditor20241022 {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: 'str_replace_editor';
type: 'text_editor_20241022';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
}
@@ -857,12 +1003,15 @@ export interface BetaToolTextEditor20250124 {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: 'str_replace_editor';
type: 'text_editor_20250124';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
}
@@ -873,7 +1022,8 @@ export type BetaToolUnion =
| BetaToolTextEditor20241022
| BetaToolComputerUse20250124
| BetaToolBash20250124
- | BetaToolTextEditor20250124;
+ | BetaToolTextEditor20250124
+ | BetaWebSearchTool20250305;
export interface BetaToolUseBlock {
id: string;
@@ -894,6 +1044,9 @@ export interface BetaToolUseBlockParam {
type: 'tool_use';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: BetaCacheControlEphemeral | null;
}
@@ -929,6 +1082,157 @@ export interface BetaUsage {
* The number of output tokens which were used.
*/
output_tokens: number;
+
+ /**
+ * The number of server tool requests.
+ */
+ server_tool_use: BetaServerToolUsage | null;
+}
+
+export interface BetaWebSearchResultBlock {
+ encrypted_content: string;
+
+ page_age: string | null;
+
+ title: string;
+
+ type: 'web_search_result';
+
+ url: string;
+}
+
+export interface BetaWebSearchResultBlockParam {
+ encrypted_content: string;
+
+ title: string;
+
+ type: 'web_search_result';
+
+ url: string;
+
+ page_age?: string | null;
+}
+
+export interface BetaWebSearchTool20250305 {
+ /**
+ * Name of the tool.
+ *
+ * This is how the tool will be called by the model and in `tool_use` blocks.
+ */
+ name: 'web_search';
+
+ type: 'web_search_20250305';
+
+ /**
+ * If provided, only these domains will be included in results. Cannot be used
+ * alongside `blocked_domains`.
+ */
+ allowed_domains?: Array<string> | null;
+
+ /**
+ * If provided, these domains will never appear in results. Cannot be used
+ * alongside `allowed_domains`.
+ */
+ blocked_domains?: Array<string> | null;
+
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
+ cache_control?: BetaCacheControlEphemeral | null;
+
+ /**
+ * Maximum number of times the tool can be used in the API request.
+ */
+ max_uses?: number | null;
+
+ /**
+ * Parameters for the user's location. Used to provide more relevant search
+ * results.
+ */
+ user_location?: BetaWebSearchTool20250305.UserLocation | null;
+}
+
+export namespace BetaWebSearchTool20250305 {
+ /**
+ * Parameters for the user's location. Used to provide more relevant search
+ * results.
+ */
+ export interface UserLocation {
+ type: 'approximate';
+
+ /**
+ * The city of the user.
+ */
+ city?: string | null;
+
+ /**
+ * The two letter
+ * [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the
+ * user.
+ */
+ country?: string | null;
+
+ /**
+ * The region of the user.
+ */
+ region?: string | null;
+
+ /**
+ * The [IANA timezone](https://nodatime.org/TimeZones) of the user.
+ */
+ timezone?: string | null;
+ }
+}
+
+export interface BetaWebSearchToolRequestError {
+ error_code:
+ | 'invalid_tool_input'
+ | 'unavailable'
+ | 'max_uses_exceeded'
+ | 'too_many_requests'
+ | 'query_too_long';
+
+ type: 'web_search_tool_result_error';
+}
+
+export interface BetaWebSearchToolResultBlock {
+ content: BetaWebSearchToolResultBlockContent;
+
+ tool_use_id: string;
+
+ type: 'web_search_tool_result';
+}
+
+export type BetaWebSearchToolResultBlockContent =
+ | BetaWebSearchToolResultError
+ | Array<BetaWebSearchResultBlock>;
+
+export interface BetaWebSearchToolResultBlockParam {
+ content: BetaWebSearchToolResultBlockParamContent;
+
+ tool_use_id: string;
+
+ type: 'web_search_tool_result';
+
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
+ cache_control?: BetaCacheControlEphemeral | null;
+}
+
+export type BetaWebSearchToolResultBlockParamContent =
+ | Array<BetaWebSearchResultBlockParam>
+ | BetaWebSearchToolRequestError;
+
+export interface BetaWebSearchToolResultError {
+ error_code:
+ | 'invalid_tool_input'
+ | 'unavailable'
+ | 'max_uses_exceeded'
+ | 'too_many_requests'
+ | 'query_too_long';
+
+ type: 'web_search_tool_result_error';
}
export type MessageCreateParams = MessageCreateParamsNonStreaming | MessageCreateParamsStreaming;
@@ -1032,6 +1336,8 @@ export interface MessageCreateParamsBase {
* [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use
* the top-level `system` parameter β there is no `"system"` role for input
* messages in the Messages API.
+ *
+ * There is a limit of 100000 messages in a single request.
*/
messages: Array<BetaMessageParam>;
@@ -1327,6 +1633,8 @@ export interface MessageCountTokensParams {
* [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use
* the top-level `system` parameter β there is no `"system"` role for input
* messages in the Messages API.
+ *
+ * There is a limit of 100000 messages in a single request.
*/
messages: Array<BetaMessageParam>;
@@ -1444,6 +1752,7 @@ export interface MessageCountTokensParams {
| BetaToolComputerUse20250124
| BetaToolBash20250124
| BetaToolTextEditor20250124
+ | BetaWebSearchTool20250305
>;
/**
@@ -1467,8 +1776,10 @@ export declare namespace Messages {
type BetaCitationContentBlockLocationParam as BetaCitationContentBlockLocationParam,
type BetaCitationPageLocation as BetaCitationPageLocation,
type BetaCitationPageLocationParam as BetaCitationPageLocationParam,
+ type BetaCitationWebSearchResultLocationParam as BetaCitationWebSearchResultLocationParam,
type BetaCitationsConfigParam as BetaCitationsConfigParam,
type BetaCitationsDelta as BetaCitationsDelta,
+ type BetaCitationsWebSearchResultLocation as BetaCitationsWebSearchResultLocation,
type BetaContentBlock as BetaContentBlock,
type BetaContentBlockParam as BetaContentBlockParam,
type BetaContentBlockSource as BetaContentBlockSource,
@@ -1491,6 +1802,9 @@ export declare namespace Messages {
type BetaRawMessageStreamEvent as BetaRawMessageStreamEvent,
type BetaRedactedThinkingBlock as BetaRedactedThinkingBlock,
type BetaRedactedThinkingBlockParam as BetaRedactedThinkingBlockParam,
+ type BetaServerToolUsage as BetaServerToolUsage,
+ type BetaServerToolUseBlock as BetaServerToolUseBlock,
+ type BetaServerToolUseBlockParam as BetaServerToolUseBlockParam,
type BetaSignatureDelta as BetaSignatureDelta,
type BetaStopReason as BetaStopReason,
type BetaTextBlock as BetaTextBlock,
@@ -1523,6 +1837,15 @@ export declare namespace Messages {
type BetaURLImageSource as BetaURLImageSource,
type BetaURLPDFSource as BetaURLPDFSource,
type BetaUsage as BetaUsage,
+ type BetaWebSearchResultBlock as BetaWebSearchResultBlock,
+ type BetaWebSearchResultBlockParam as BetaWebSearchResultBlockParam,
+ type BetaWebSearchTool20250305 as BetaWebSearchTool20250305,
+ type BetaWebSearchToolRequestError as BetaWebSearchToolRequestError,
+ type BetaWebSearchToolResultBlock as BetaWebSearchToolResultBlock,
+ type BetaWebSearchToolResultBlockContent as BetaWebSearchToolResultBlockContent,
+ type BetaWebSearchToolResultBlockParam as BetaWebSearchToolResultBlockParam,
+ type BetaWebSearchToolResultBlockParamContent as BetaWebSearchToolResultBlockParamContent,
+ type BetaWebSearchToolResultError as BetaWebSearchToolResultError,
type MessageCreateParams as MessageCreateParams,
type MessageCreateParamsNonStreaming as MessageCreateParamsNonStreaming,
type MessageCreateParamsStreaming as MessageCreateParamsStreaming,
diff --git src/resources/beta/models.ts src/resources/beta/models.ts
index 48036273..6ec9c244 100644
--- src/resources/beta/models.ts
+++ src/resources/beta/models.ts
@@ -3,6 +3,7 @@
import { APIResource } from '../../resource';
import { isRequestOptions } from '../../core';
import * as Core from '../../core';
+import * as BetaAPI from './beta';
import { Page, type PageParams } from '../../pagination';
export class Models extends APIResource {
@@ -11,9 +12,36 @@ export class Models extends APIResource {
*
* The Models API response can be used to determine information about a specific
* model or resolve a model alias to a model ID.
+ *
+ * @example
+ * ```ts
+ * const betaModelInfo = await client.beta.models.retrieve(
+ * 'model_id',
+ * );
+ * ```
*/
- retrieve(modelId: string, options?: Core.RequestOptions): Core.APIPromise<BetaModelInfo> {
- return this._client.get(`/v1/models/${modelId}?beta=true`, options);
+ retrieve(
+ modelId: string,
+ params?: ModelRetrieveParams,
+ options?: Core.RequestOptions,
+ ): Core.APIPromise<BetaModelInfo>;
+ retrieve(modelId: string, options?: Core.RequestOptions): Core.APIPromise<BetaModelInfo>;
+ retrieve(
+ modelId: string,
+ params: ModelRetrieveParams | Core.RequestOptions = {},
+ options?: Core.RequestOptions,
+ ): Core.APIPromise<BetaModelInfo> {
+ if (isRequestOptions(params)) {
+ return this.retrieve(modelId, {}, params);
+ }
+ const { betas } = params;
+ return this._client.get(`/v1/models/${modelId}?beta=true`, {
+ ...options,
+ headers: {
+ ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined),
+ ...options?.headers,
+ },
+ });
}
/**
@@ -21,20 +49,36 @@ export class Models extends APIResource {
*
* The Models API response can be used to determine which models are available for
* use in the API. More recently released models are listed first.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const betaModelInfo of client.beta.models.list()) {
+ * // ...
+ * }
+ * ```
*/
list(
- query?: ModelListParams,
+ params?: ModelListParams,
options?: Core.RequestOptions,
): Core.PagePromise<BetaModelInfosPage, BetaModelInfo>;
list(options?: Core.RequestOptions): Core.PagePromise<BetaModelInfosPage, BetaModelInfo>;
list(
- query: ModelListParams | Core.RequestOptions = {},
+ params: ModelListParams | Core.RequestOptions = {},
options?: Core.RequestOptions,
): Core.PagePromise<BetaModelInfosPage, BetaModelInfo> {
- if (isRequestOptions(query)) {
- return this.list({}, query);
+ if (isRequestOptions(params)) {
+ return this.list({}, params);
}
- return this._client.getAPIList('/v1/models?beta=true', BetaModelInfosPage, { query, ...options });
+ const { betas, ...query } = params;
+ return this._client.getAPIList('/v1/models?beta=true', BetaModelInfosPage, {
+ query,
+ ...options,
+ headers: {
+ ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined),
+ ...options?.headers,
+ },
+ });
}
}
@@ -65,7 +109,19 @@ export interface BetaModelInfo {
type: 'model';
}
-export interface ModelListParams extends PageParams {}
+export interface ModelRetrieveParams {
+ /**
+ * Optional header to specify the beta version(s) you want to use.
+ */
+ betas?: Array<BetaAPI.AnthropicBeta>;
+}
+
+export interface ModelListParams extends PageParams {
+ /**
+ * Header param: Optional header to specify the beta version(s) you want to use.
+ */
+ betas?: Array<BetaAPI.AnthropicBeta>;
+}
Models.BetaModelInfosPage = BetaModelInfosPage;
@@ -73,6 +129,7 @@ export declare namespace Models {
export {
type BetaModelInfo as BetaModelInfo,
BetaModelInfosPage as BetaModelInfosPage,
+ type ModelRetrieveParams as ModelRetrieveParams,
type ModelListParams as ModelListParams,
};
}
diff --git src/resources/completions.ts src/resources/completions.ts
index 2260681d..a0bfb0ab 100644
--- src/resources/completions.ts
+++ src/resources/completions.ts
@@ -4,6 +4,7 @@ import { APIResource } from '../resource';
import { APIPromise } from '../core';
import * as Core from '../core';
import * as CompletionsAPI from './completions';
+import * as BetaAPI from './beta/beta';
import * as MessagesAPI from './messages/messages';
import { Stream } from '../streaming';
@@ -17,25 +18,39 @@ export class Completions extends APIResource {
* Future models and features will not be compatible with Text Completions. See our
* [migration guide](https://docs.anthropic.com/en/api/migrating-from-text-completions-to-messages)
* for guidance in migrating from Text Completions to Messages.
+ *
+ * @example
+ * ```ts
+ * const completion = await client.completions.create({
+ * max_tokens_to_sample: 256,
+ * model: 'claude-3-7-sonnet-latest',
+ * prompt: '\n\nHuman: Hello, world!\n\nAssistant:',
+ * });
+ * ```
*/
- create(body: CompletionCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<Completion>;
+ create(params: CompletionCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<Completion>;
create(
- body: CompletionCreateParamsStreaming,
+ params: CompletionCreateParamsStreaming,
options?: Core.RequestOptions,
): APIPromise<Stream<Completion>>;
create(
- body: CompletionCreateParamsBase,
+ params: CompletionCreateParamsBase,
options?: Core.RequestOptions,
): APIPromise<Stream<Completion> | Completion>;
create(
- body: CompletionCreateParams,
+ params: CompletionCreateParams,
options?: Core.RequestOptions,
): APIPromise<Completion> | APIPromise<Stream<Completion>> {
+ const { betas, ...body } = params;
return this._client.post('/v1/complete', {
body,
timeout: (this._client as any)._options.timeout ?? 600000,
...options,
- stream: body.stream ?? false,
+ headers: {
+ ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined),
+ ...options?.headers,
+ },
+ stream: params.stream ?? false,
}) as APIPromise<Completion> | APIPromise<Stream<Completion>>;
}
}
@@ -83,7 +98,7 @@ export type CompletionCreateParams = CompletionCreateParamsNonStreaming | Comple
export interface CompletionCreateParamsBase {
/**
- * The maximum number of tokens to generate before stopping.
+ * Body param: The maximum number of tokens to generate before stopping.
*
* Note that our models may stop _before_ reaching this maximum. This parameter
* only specifies the absolute maximum number of tokens to generate.
@@ -91,14 +106,14 @@ export interface CompletionCreateParamsBase {
max_tokens_to_sample: number;
/**
- * The model that will complete your prompt.\n\nSee
+ * Body param: The model that will complete your prompt.\n\nSee
* [models](https://docs.anthropic.com/en/docs/models-overview) for additional
* details and options.
*/
model: MessagesAPI.Model;
/**
- * The prompt that you want Claude to complete.
+ * Body param: The prompt that you want Claude to complete.
*
* For proper response generation you will need to format your prompt using
* alternating `\n\nHuman:` and `\n\nAssistant:` conversational turns. For example:
@@ -115,12 +130,12 @@ export interface CompletionCreateParamsBase {
prompt: string;
/**
- * An object describing metadata about the request.
+ * Body param: An object describing metadata about the request.
*/
metadata?: MessagesAPI.Metadata;
/**
- * Sequences that will cause the model to stop generating.
+ * Body param: Sequences that will cause the model to stop generating.
*
* Our models stop on `"\n\nHuman:"`, and may include additional built-in stop
* sequences in the future. By providing the stop_sequences parameter, you may
@@ -129,14 +144,15 @@ export interface CompletionCreateParamsBase {
stop_sequences?: Array<string>;
/**
- * Whether to incrementally stream the response using server-sent events.
+ * Body param: Whether to incrementally stream the response using server-sent
+ * events.
*
* See [streaming](https://docs.anthropic.com/en/api/streaming) for details.
*/
stream?: boolean;
/**
- * Amount of randomness injected into the response.
+ * Body param: Amount of randomness injected into the response.
*
* Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0`
* for analytical / multiple choice, and closer to `1.0` for creative and
@@ -148,7 +164,7 @@ export interface CompletionCreateParamsBase {
temperature?: number;
/**
- * Only sample from the top K options for each subsequent token.
+ * Body param: Only sample from the top K options for each subsequent token.
*
* Used to remove "long tail" low probability responses.
* [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).
@@ -159,7 +175,7 @@ export interface CompletionCreateParamsBase {
top_k?: number;
/**
- * Use nucleus sampling.
+ * Body param: Use nucleus sampling.
*
* In nucleus sampling, we compute the cumulative distribution over all the options
* for each subsequent token in decreasing probability order and cut it off once it
@@ -170,6 +186,11 @@ export interface CompletionCreateParamsBase {
* `temperature`.
*/
top_p?: number;
+
+ /**
+ * Header param: Optional header to specify the beta version(s) you want to use.
+ */
+ betas?: Array<BetaAPI.AnthropicBeta>;
}
export namespace CompletionCreateParams {
@@ -184,7 +205,8 @@ export namespace CompletionCreateParams {
export interface CompletionCreateParamsNonStreaming extends CompletionCreateParamsBase {
/**
- * Whether to incrementally stream the response using server-sent events.
+ * Body param: Whether to incrementally stream the response using server-sent
+ * events.
*
* See [streaming](https://docs.anthropic.com/en/api/streaming) for details.
*/
@@ -193,7 +215,8 @@ export interface CompletionCreateParamsNonStreaming extends CompletionCreatePara
export interface CompletionCreateParamsStreaming extends CompletionCreateParamsBase {
/**
- * Whether to incrementally stream the response using server-sent events.
+ * Body param: Whether to incrementally stream the response using server-sent
+ * events.
*
* See [streaming](https://docs.anthropic.com/en/api/streaming) for details.
*/
diff --git src/resources/index.ts src/resources/index.ts
index d08d2619..114b9fe4 100644
--- src/resources/index.ts
+++ src/resources/index.ts
@@ -34,8 +34,10 @@ export {
type CitationContentBlockLocationParam,
type CitationPageLocation,
type CitationPageLocationParam,
+ type CitationWebSearchResultLocationParam,
type CitationsConfigParam,
type CitationsDelta,
+ type CitationsWebSearchResultLocation,
type ContentBlock,
type ContentBlockParam,
type ContentBlockSource,
@@ -63,6 +65,9 @@ export {
type RawMessageStreamEvent,
type RedactedThinkingBlock,
type RedactedThinkingBlockParam,
+ type ServerToolUsage,
+ type ServerToolUseBlock,
+ type ServerToolUseBlockParam,
type SignatureDelta,
type StopReason,
type TextBlock,
@@ -91,6 +96,15 @@ export {
type URLImageSource,
type URLPDFSource,
type Usage,
+ type WebSearchResultBlock,
+ type WebSearchResultBlockParam,
+ type WebSearchTool20250305,
+ type WebSearchToolRequestError,
+ type WebSearchToolResultBlock,
+ type WebSearchToolResultBlockContent,
+ type WebSearchToolResultBlockParam,
+ type WebSearchToolResultBlockParamContent,
+ type WebSearchToolResultError,
type MessageStreamEvent,
type MessageStartEvent,
type MessageDeltaEvent,
@@ -103,4 +117,10 @@ export {
type MessageCreateParamsStreaming,
type MessageCountTokensParams,
} from './messages/messages';
-export { ModelInfosPage, Models, type ModelInfo, type ModelListParams } from './models';
+export {
+ ModelInfosPage,
+ Models,
+ type ModelInfo,
+ type ModelRetrieveParams,
+ type ModelListParams,
+} from './models';
diff --git src/resources/messages/batches.ts src/resources/messages/batches.ts
index e188da1a..c14bc48b 100644
--- src/resources/messages/batches.ts
+++ src/resources/messages/batches.ts
@@ -20,6 +20,24 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const messageBatch = await client.messages.batches.create({
+ * requests: [
+ * {
+ * custom_id: 'my-custom-id-1',
+ * params: {
+ * max_tokens: 1024,
+ * messages: [
+ * { content: 'Hello, world', role: 'user' },
+ * ],
+ * model: 'claude-3-7-sonnet-20250219',
+ * },
+ * },
+ * ],
+ * });
+ * ```
*/
create(body: BatchCreateParams, options?: Core.RequestOptions): Core.APIPromise<MessageBatch> {
return this._client.post('/v1/messages/batches', { body, ...options });
@@ -32,6 +50,13 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const messageBatch = await client.messages.batches.retrieve(
+ * 'message_batch_id',
+ * );
+ * ```
*/
retrieve(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<MessageBatch> {
return this._client.get(`/v1/messages/batches/${messageBatchId}`, options);
@@ -43,6 +68,14 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const messageBatch of client.messages.batches.list()) {
+ * // ...
+ * }
+ * ```
*/
list(
query?: BatchListParams,
@@ -67,6 +100,12 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const deletedMessageBatch =
+ * await client.messages.batches.delete('message_batch_id');
+ * ```
*/
delete(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<DeletedMessageBatch> {
return this._client.delete(`/v1/messages/batches/${messageBatchId}`, options);
@@ -85,6 +124,13 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const messageBatch = await client.messages.batches.cancel(
+ * 'message_batch_id',
+ * );
+ * ```
*/
cancel(messageBatchId: string, options?: Core.RequestOptions): Core.APIPromise<MessageBatch> {
return this._client.post(`/v1/messages/batches/${messageBatchId}/cancel`, options);
@@ -99,6 +145,12 @@ export class Batches extends APIResource {
*
* Learn more about the Message Batches API in our
* [user guide](/en/docs/build-with-claude/batch-processing)
+ *
+ * @example
+ * ```ts
+ * const messageBatchIndividualResponse =
+ * await client.messages.batches.results('message_batch_id');
+ * ```
*/
async results(
messageBatchId: string,
diff --git src/resources/messages/index.ts src/resources/messages/index.ts
index 197baf25..6ecc7f19 100644
--- src/resources/messages/index.ts
+++ src/resources/messages/index.ts
@@ -26,8 +26,10 @@ export {
type CitationContentBlockLocationParam,
type CitationPageLocation,
type CitationPageLocationParam,
+ type CitationWebSearchResultLocationParam,
type CitationsConfigParam,
type CitationsDelta,
+ type CitationsWebSearchResultLocation,
type ContentBlock,
type ContentBlockParam,
type ContentBlockSource,
@@ -53,6 +55,9 @@ export {
type RawMessageStreamEvent,
type RedactedThinkingBlock,
type RedactedThinkingBlockParam,
+ type ServerToolUsage,
+ type ServerToolUseBlock,
+ type ServerToolUseBlockParam,
, type SignatureDelta,
type StopReason,
type TextBlock,
@@ -81,6 +86,15 @@ export {
type URLImageSource,
type URLPDFSource,
type Usage,
+ type WebSearchResultBlock,
+ type WebSearchResultBlockParam,
+ type WebSearchTool20250305,
+ type WebSearchToolRequestError,
+ type WebSearchToolResultBlock,
+ type WebSearchToolResultBlockContent,
+ type WebSearchToolResultBlockParam,
+ type WebSearchToolResultBlockParamContent,
+ type WebSearchToolResultError,
type MessageStreamEvent,
type MessageStartEvent,
type MessageDeltaEvent,
diff --git src/resources/messages/messages.ts src/resources/messages/messages.ts
index c0ab4767..ce2bde21 100644
--- src/resources/messages/messages.ts
+++ src/resources/messages/messages.ts
@@ -36,6 +36,15 @@ export class Messages extends APIResource {
* conversations.
*
* Learn more about the Messages API in our [user guide](/en/docs/initial-setup)
+ *
+ * @example
+ * ```ts
+ * const message = await client.messages.create({
+ * max_tokens: 1024,
+ * messages: [{ content: 'Hello, world', role: 'user' }],
+ * model: 'claude-3-7-sonnet-20250219',
+ * });
+ * ```
*/
create(body: MessageCreateParamsNonStreaming, options?: Core.RequestOptions): APIPromise<Message>;
create(
@@ -82,6 +91,15 @@ export class Messages extends APIResource {
*
* Learn more about token counting in our
* [user guide](/en/docs/build-with-claude/token-counting)
+ *
+ * @example
+ * ```ts
+ * const messageTokensCount =
+ * await client.messages.countTokens({
+ * messages: [{ content: 'string', role: 'user' }],
+ * model: 'claude-3-7-sonnet-latest',
+ * });
+ * ```
*/
countTokens(
body: MessageCountTokensParams,
@@ -195,22 +213,58 @@ export interface CitationPageLocationParam {
type: 'page_location';
}
+export interface CitationWebSearchResultLocationParam {
+ cited_text: string;
+
+ encrypted_index: string;
+
+ title: string | null;
+
+ type: 'web_search_result_location';
+
+ url: string;
+}
+
export interface CitationsConfigParam {
enabled?: boolean;
}
export interface CitationsDelta {
- citation: CitationCharLocation | CitationPageLocation | CitationContentBlockLocation;
+ citation:
+ | CitationCharLocation
+ | CitationPageLocation
+ | CitationContentBlockLocation
+ | CitationsWebSearchResultLocation;
type: 'citations_delta';
}
-export type ContentBlock = TextBlock | ToolUseBlock | ThinkingBlock | RedactedThinkingBlock;
+export interface CitationsWebSearchResultLocation {
+ cited_text: string;
+
+ encrypted_index: string;
+
+ title: string | null;
+
+ type: 'web_search_result_location';
+
+ url: string;
+}
+
+export type ContentBlock =
+ | TextBlock
+ | ToolUseBlock
+ | ServerToolUseBlock
+ | WebSearchToolResultBlock
+ | ThinkingBlock
+ | RedactedThinkingBlock;
export type ContentBlockParam =
| TextBlockParam
| ImageBlockParam
| ToolUseBlockParam
+ | ServerToolUseBlockParam
+ | WebSearchToolResultBlockParam
| ToolResultBlockParam
| DocumentBlockParam
| ThinkingBlockParam
@@ -229,6 +283,9 @@ export interface DocumentBlockParam {
type: 'document';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: CacheControlEphemeral | null;
citations?: CitationsConfigParam;
@@ -243,6 +300,9 @@ export interface ImageBlockParam {
type: 'image';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: CacheControlEphemeral | null;
}
@@ -362,13 +422,33 @@ export interface Message {
usage: Usage;
}
-export type MessageCountTokensTool = Tool | ToolBash20250124 | ToolTextEditor20250124;
+export type MessageCountTokensTool = Tool | ToolBash20250124 | ToolTextEditor20250124 | WebSearchTool20250305;
export interface MessageDeltaUsage {
+ /**
+ * The cumulative number of input tokens used to create the cache entry.
+ */
+ cache_creation_input_tokens: number | null;
+
+ /**
+ * The cumulative number of input tokens read from the cache.
+ */
+ cache_read_input_tokens: number | null;
+
+ /**
+ * The cumulative number of input tokens which were used.
+ */
+ input_tokens: number | null;
+
/**
* The cumulative number of output tokens which were used.
*/
output_tokens: number;
+
+ /**
+ * The number of server tool requests.
+ */
+ server_tool_use: ServerToolUsage | null;
}
export interface MessageParam {
@@ -454,7 +534,13 @@ export interface RawContentBlockDeltaEvent {
}
export interface RawContentBlockStartEvent {
- content_block: TextBlock | ToolUseBlock | ThinkingBlock | RedactedThinkingBlock;
+ content_block:
+ | TextBlock
+ | ToolUseBlock
+ | ServerToolUseBlock
+ | WebSearchToolResultBlock
+ | ThinkingBlock
+ | RedactedThinkingBlock;
index: number;
@@ -530,13 +616,45 @@ export interface RedactedThinkingBlockParam {
type: 'redacted_thinking';
}
+export interface ServerToolUsage {
+ /**
+ * The number of web search tool requests.
+ */
+ web_search_requests: number;
+}
+
+export interface ServerToolUseBlock {
+ id: string;
+
+ input: unknown;
+
+ name: 'web_search';
+
+ type: 'server_tool_use';
+}
+
+export interface ServerToolUseBlockParam {
+ id: string;
+
+ input: unknown;
+
+ name: 'web_search';
+
+ type: 'server_tool_use';
+
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
+ cache_control?: CacheControlEphemeral | null;
+}
+
export interface SignatureDelta {
signature: string;
type: 'signature_delta';
}
-export type StopReason = 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use';
+export type StopReason = 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | 'pause_turn' | 'refusal';
export interface TextBlock {
/**
@@ -558,17 +676,25 @@ export interface TextBlockParam {
type: 'text';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: CacheControlEphemeral | null;
citations?: Array<TextCitationParam> | null;
}
-export type TextCitation = CitationCharLocation | CitationPageLocation | CitationContentBlockLocation;
+export type TextCitation =
+ | CitationCharLocation
+ | CitationPageLocation
+ | CitationContentBlockLocation
+ | CitationsWebSearchResultLocation;
export type TextCitationParam =
| CitationCharLocationParam
| CitationPageLocationParam
- | CitationContentBlockLocationParam;
+ | CitationContentBlockLocationParam
+ | CitationWebSearchResultLocationParam;
export interface TextDelta {
text: string;
@@ -644,10 +770,13 @@ export interface Tool {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: string;
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: CacheControlEphemeral | null;
/**
@@ -659,6 +788,8 @@ export interface Tool {
* aspects of the tool input JSON schema.
*/
description?: string;
+
+ type?: 'custom' | null;
}
export namespace Tool {
@@ -681,12 +812,15 @@ export interface ToolBash20250124 {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: 'bash';
type: 'bash_20250124';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: CacheControlEphemeral | null;
}
@@ -758,6 +892,9 @@ export interface ToolResultBlockParam {
type: 'tool_result';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: CacheControlEphemeral | null;
content?: string | Array<TextBlockParam | ImageBlockParam>;
@@ -769,16 +906,19 @@ export interface ToolTextEditor20250124 {
/**
* Name of the tool.
*
- * This is how the tool will be called by the model and in tool_use blocks.
+ * This is how the tool will be called by the model and in `tool_use` blocks.
*/
name: 'str_replace_editor';
type: 'text_editor_20250124';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: CacheControlEphemeral | null;
}
-export type ToolUnion = Tool | ToolBash20250124 | ToolTextEditor20250124;
+export type ToolUnion = Tool | ToolBash20250124 | ToolTextEditor20250124 | WebSearchTool20250305;
export interface ToolUseBlock {
id: string;
@@ -799,6 +939,9 @@ export interface ToolUseBlockParam {
type: 'tool_use';
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
cache_control?: CacheControlEphemeral | null;
}
@@ -834,6 +977,155 @@ export interface Usage {
* The number of output tokens which were used.
*/
output_tokens: number;
+
+ /**
+ * The number of server tool requests.
+ */
+ server_tool_use: ServerToolUsage | null;
+}
+
+export interface WebSearchResultBlock {
+ encrypted_content: string;
+
+ page_age: string | null;
+
+ title: string;
+
+ type: 'web_search_result';
+
+ url: string;
+}
+
+export interface WebSearchResultBlockParam {
+ encrypted_content: string;
+
+ title: string;
+
+ type: 'web_search_result';
+
+ url: string;
+
+ page_age?: string | null;
+}
+
+export interface WebSearchTool20250305 {
+ /**
+ * Name of the tool.
+ *
+ * This is how the tool will be called by the model and in `tool_use` blocks.
+ */
+ name: 'web_search';
+
+ type: 'web_search_20250305';
+
+ /**
+ * If provided, only these domains will be included in results. Cannot be used
+ * alongside `blocked_domains`.
+ */
+ allowed_domains?: Array<string> | null;
+
+ /**
+ * If provided, these domains will never appear in results. Cannot be used
+ * alongside `allowed_domains`.
+ */
+ blocked_domains?: Array<string> | null;
+
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
+ cache_control?: CacheControlEphemeral | null;
+
+ /**
+ * Maximum number of times the tool can be used in the API request.
+ */
+ max_uses?: number | null;
+
+ /**
+ * Parameters for the user's location. Used to provide more relevant search
+ * results.
+ */
+ user_location?: WebSearchTool20250305.UserLocation | null;
+}
+
+export namespace WebSearchTool20250305 {
+ /**
+ * Parameters for the user's location. Used to provide more relevant search
+ * results.
+ */
+ export interface UserLocation {
+ type: 'approximate';
+
+ /**
+ * The city of the user.
+ */
+ city?: string | null;
+
+ /**
+ * The two letter
+ * [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the
+ * user.
+ */
+ country?: string | null;
+
+ /**
+ * The region of the user.
+ */
+ region?: string | null;
+
+ /**
+ * The [IANA timezone](https://nodatime.org/TimeZones) of the user.
+ */
+ timezone?: string | null;
+ }
+}
+
+export interface WebSearchToolRequestError {
+ error_code:
+ | 'invalid_tool_input'
+ | 'unavailable'
+ | 'max_uses_exceeded'
+ | 'too_many_requests'
+ | 'query_too_long';
+
+ type: 'web_search_tool_result_error';
+}
+
+export interface WebSearchToolResultBlock {
+ content: WebSearchToolResultBlockContent;
+
+ tool_use_id: string;
+
+ type: 'web_search_tool_result';
+}
+
+export type WebSearchToolResultBlockContent = WebSearchToolResultError | Array<WebSearchResultBlock>;
+
+export interface WebSearchToolResultBlockParam {
+ content: WebSearchToolResultBlockParamContent;
+
+ tool_use_id: string;
+
+ type: 'web_search_tool_result';
+
+ /**
+ * Create a cache control breakpoint at this content block.
+ */
+ cache_control?: CacheControlEphemeral | null;
+}
+
+export type WebSearchToolResultBlockParamContent =
+ | Array<WebSearchResultBlockParam>
+ | WebSearchToolRequestError;
+
+export interface WebSearchToolResultError {
+ error_code:
+ | 'invalid_tool_input'
+ | 'unavailable'
+ | 'max_uses_exceeded'
+ | 'too_many_requests'
+ | 'query_too_long';
+
+ type: 'web_search_tool_result_error';
}
export type MessageStreamEvent = RawMessageStreamEvent;
@@ -951,6 +1243,8 @@ export interface MessageCreateParamsBase {
* [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use
* the top-level `system` parameter β there is no `"system"` role for input
* messages in the Messages API.
+ *
+ * There is a limit of 100000 messages in a single request.
*/
messages: Array<MessageParam>;
@@ -1260,6 +1554,8 @@ export interface MessageCountTokensParams {
* [system prompt](https://docs.anthropic.com/en/docs/system-prompts), you can use
* the top-level `system` parameter β there is no `"system"` role for input
* messages in the Messages API.
+ *
+ * There is a limit of 100000 messages in a single request.
*/
messages: Array<MessageParam>;
@@ -1386,8 +1682,10 @@ export declare namespace Messages {
type CitationContentBlockLocationParam as CitationContentBlockLocationParam,
type CitationPageLocation as CitationPageLocation,
type CitationPageLocationParam as CitationPageLocationParam,
+ type CitationWebSearchResultLocationParam as CitationWebSearchResultLocationParam,
type CitationsConfigParam as CitationsConfigParam,
type CitationsDelta as CitationsDelta,
+ type CitationsWebSearchResultLocation as CitationsWebSearchResultLocation,
type ContentBlock as ContentBlock,
type ContentBlockParam as ContentBlockParam,
type ContentBlockSource as ContentBlockSource,
@@ -1414,6 +1712,9 @@ export declare namespace Messages {
type RawMessageStreamEvent as RawMessageStreamEvent,
type RedactedThinkingBlock as RedactedThinkingBlock,
type RedactedThinkingBlockParam as RedactedThinkingBlockParam,
+ type ServerToolUsage as ServerToolUsage,
+ type ServerToolUseBlock as ServerToolUseBlock,
+ type ServerToolUseBlockParam as ServerToolUseBlockParam,
type SignatureDelta as SignatureDelta,
type StopReason as StopReason,
type TextBlock as TextBlock,
@@ -1442,6 +1743,15 @@ export declare namespace Messages {
type URLImageSource as URLImageSource,
type URLPDFSource as URLPDFSource,
type Usage as Usage,
+ type WebSearchResultBlock as WebSearchResultBlock,
+ type WebSearchResultBlockParam as WebSearchResultBlockParam,
+ type WebSearchTool20250305 as WebSearchTool20250305,
+ type WebSearchToolRequestError as WebSearchToolRequestError,
+ type WebSearchToolResultBlock as WebSearchToolResultBlock,
+ type WebSearchToolResultBlockContent as WebSearchToolResultBlockContent,
+ type WebSearchToolResultBlockParam as WebSearchToolResultBlockParam,
+ type WebSearchToolResultBlockParamContent as WebSearchToolResultBlockParamContent,
+ type WebSearchToolResultError as WebSearchToolResultError,
type MessageStreamEvent as MessageStreamEvent,
type MessageStartEvent as MessageStartEvent,
type MessageDeltaEvent as MessageDeltaEvent,
diff --git src/resources/models.ts src/resources/models.ts
index 50e80399..68491b3e 100644
--- src/resources/models.ts
+++ src/resources/models.ts
@@ -3,6 +3,7 @@
import { APIResource } from '../resource';
import { isRequestOptions } from '../core';
import * as Core from '../core';
+import * as BetaAPI from './beta/beta';
import { Page, type PageParams } from '../pagination';
export class Models extends APIResource {
@@ -12,8 +13,28 @@ export class Models extends APIResource {
* The Models API response can be used to determine information about a specific
* model or resolve a model alias to a model ID.
*/
- retrieve(modelId: string, options?: Core.RequestOptions): Core.APIPromise<ModelInfo> {
- return this._client.get(`/v1/models/${modelId}`, options);
+ retrieve(
+ modelId: string,
+ params?: ModelRetrieveParams,
+ options?: Core.RequestOptions,
+ ): Core.APIPromise<ModelInfo>;
+ retrieve(modelId: string, options?: Core.RequestOptions): Core.APIPromise<ModelInfo>;
+ retrieve(
+ modelId: string,
+ params: ModelRetrieveParams | Core.RequestOptions = {},
+ options?: Core.RequestOptions,
+ ): Core.APIPromise<ModelInfo> {
+ if (isRequestOptions(params)) {
+ return this.retrieve(modelId, {}, params);
+ }
+ const { betas } = params;
+ return this._client.get(`/v1/models/${modelId}`, {
+ ...options,
+ headers: {
+ ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined),
+ ...options?.headers,
+ },
+ });
}
/**
@@ -22,16 +43,24 @@ export class Models extends APIResource {
* The Models API response can be used to determine which models are available for
* use in the API. More recently released models are listed first.
*/
- list(query?: ModelListParams, options?: Core.RequestOptions): Core.PagePromise<ModelInfosPage, ModelInfo>;
+ list(params?: ModelListParams, options?: Core.RequestOptions): Core.PagePromise<ModelInfosPage, ModelInfo>;
list(options?: Core.RequestOptions): Core.PagePromise<ModelInfosPage, ModelInfo>;
list(
- query: ModelListParams | Core.RequestOptions = {},
+ params: ModelListParams | Core.RequestOptions = {},
options?: Core.RequestOptions,
): Core.PagePromise<ModelInfosPage, ModelInfo> {
- if (isRequestOptions(query)) {
- return this.list({}, query);
+ if (isRequestOptions(params)) {
+ return this.list({}, params);
}
- return this._client.getAPIList('/v1/models', ModelInfosPage, { query, ...options });
+ const { betas, ...query } = params;
+ return this._client.getAPIList('/v1/models', ModelInfosPage, {
+ query,
+ ...options,
+ headers: {
+ ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined),
+ ...options?.headers,
+ },
+ });
}
}
@@ -62,7 +91,19 @@ export interface ModelInfo {
type: 'model';
}
-export interface ModelListParams extends PageParams {}
+export interface ModelRetrieveParams {
+ /**
+ * Optional header to specify the beta version(s) you want to use.
+ */
+ betas?: Array<BetaAPI.AnthropicBeta>;
+}
+
+export interface ModelListParams extends PageParams {
+ /**
+ * Header param: Optional header to specify the beta version(s) you want to use.
+ */
+ betas?: Array<BetaAPI.AnthropicBeta>;
+}
Models.ModelInfosPage = ModelInfosPage;
@@ -70,6 +111,7 @@ export declare namespace Models {
export {
type ModelInfo as ModelInfo,
ModelInfosPage as ModelInfosPage,
+ type ModelRetrieveParams as ModelRetrieveParams,
type ModelListParams as ModelListParams,
};
}
diff --git src/version.ts src/version.ts
index e88a3c67..2f1576d5 100644
--- src/version.ts
+++ src/version.ts
@@ -1 +1 @@
-export const VERSION = '0.40.1'; // x-release-please-version
+export const VERSION = '0.41.0'; // x-release-please-version
diff --git tests/api-resources/MessageStream.test.ts tests/api-resources/MessageStream.test.ts
index 0788821a..d1912561 100644
--- tests/api-resources/MessageStream.test.ts
+++ tests/api-resources/MessageStream.test.ts
@@ -32,6 +32,19 @@ async function* messageIterable(message: Message): AsyncGenerator<MessageStreamE
}
: content.type === 'thinking' ? { type: 'thinking', thinking: '', signature: '' }
: content.type === 'redacted_thinking' ? { type: 'redacted_thinking', data: '' }
+ : content.type === 'server_tool_use' ?
+ {
+ type: 'server_tool_use',
+ id: 'toolu_01Up7oRoHeGvhded7n66nPzP',
+ name: 'web_search',
+ input: {},
+ }
+ : content.type === 'web_search_tool_result' ?
+ {
+ type: 'web_search_tool_result',
+ tool_use_id: 'toolu_01Up7oRoHeGvhded7n66nPzP',
+ content: [],
+ }
: assertNever(content),
index: idx,
};
@@ -58,6 +71,10 @@ async function* messageIterable(message: Message): AsyncGenerator<MessageStreamE
throw new Error('thinking not implemented yet');
} else if (content.type === 'redacted_thinking') {
throw new Error('redacted_thinking not implemented yet');
+ } else if (content.type === 'server_tool_use') {
+ throw new Error('server_tool_use not implemented yet');
+ } else if (content.type === 'web_search_tool_result') {
+ throw new Error('web_search_tool_result not implemented yet');
} else {
assertNever(content);
}
@@ -70,7 +87,13 @@ async function* messageIterable(message: Message): AsyncGenerator<MessageStreamE
yield {
type: 'message_delta',
- usage: { output_tokens: 6 },
+ usage: {
+ output_tokens: 6,
+ input_tokens: null,
+ cache_creation_input_tokens: null,
+ cache_read_input_tokens: null,
+ server_tool_use: null,
+ },
// @ts-ignore
delta: { stop_reason: message.stop_reason, stop_sequence: message.stop_sequence },
};
@@ -160,6 +183,7 @@ describe('MessageStream class', () => {
input_tokens: 10,
cache_creation_input_tokens: null,
cache_read_input_tokens: null,
+ server_tool_use: null,
},
}),
);
@@ -220,22 +244,22 @@ describe('MessageStream class', () => {
},
{
"args": [
- "{"type":"message_start","message":{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}}",
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message_start","message":{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "streamEvent",
},
{
"args": [
"{"type":"content_block_start","content_block":{"type":"text","text":"","citations":null},"index":0}",
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "streamEvent",
},
{
"args": [
"{"type":"content_block_delta","delta":{"type":"text_delta","text":"Hello"},"index":0}",
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "streamEvent",
},
@@ -249,7 +273,7 @@ describe('MessageStream class', () => {
{
"args": [
"{"type":"content_block_delta","delta":{"type":"text_delta","text":" ther"},"index":0}",
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello ther","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello ther","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "streamEvent",
},
@@ -263,7 +287,7 @@ describe('MessageStream class', () => {
{
"args": [
"{"type":"content_block_delta","delta":{"type":"text_delta","text":"e!"},"index":0}",
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "streamEvent",
},
@@ -277,7 +301,7 @@ describe('MessageStream class', () => {
{
"args": [
"{"type":"content_block_stop","index":0}",
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":null,"stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "streamEvent",
},
@@ -289,27 +313,27 @@ describe('MessageStream class', () => {
},
{
"args": [
- "{"type":"message_delta","usage":{"output_tokens":6},"delta":{"stop_reason":"end_turn","stop_sequence":null}}",
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":"end_turn","stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message_delta","usage":{"output_tokens":6,"input_tokens":null,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null},"delta":{"stop_reason":"end_turn","stop_sequence":null}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":"end_turn","stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "streamEvent",
},
{
"args": [
"{"type":"message_stop"}",
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":"end_turn","stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":"end_turn","stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "streamEvent",
},
{
"args": [
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":"end_turn","stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":"end_turn","stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "message",
},
{
"args": [
- "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":"end_turn","stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null}}",
+ "{"type":"message","id":"msg_01hhptzfxdaeehfxfv070yb6b8","role":"assistant","content":[{"type":"text","text":"Hello there!","citations":null}],"model":"claude-3-opus-20240229","stop_reason":"end_turn","stop_sequence":null,"usage":{"output_tokens":6,"input_tokens":10,"cache_creation_input_tokens":null,"cache_read_input_tokens":null,"server_tool_use":null}}",
],
"type": "finalMessage",
},
@@ -342,6 +366,7 @@ describe('MessageStream class', () => {
"cache_read_input_tokens": null,
"input_tokens": 10,
"output_tokens": 6,
+ "server_tool_use": null,
},
}
`);
@@ -372,6 +397,7 @@ describe('MessageStream class', () => {
input_tokens: 10,
cache_creation_input_tokens: null,
cache_read_input_tokens: null,
+ server_tool_use: null,
},
}),
);
@@ -399,7 +425,7 @@ describe('MessageStream class', () => {
const stream = anthropic.messages.stream(
{
max_tokens: 1024,
- model: 'claude-2.1',
+ model: 'claude-3-7-sonnet-20250219',
messages: [{ role: 'user', content: 'Say hello there!' }],
},
{ maxRetries: 0 },
@@ -424,7 +450,7 @@ describe('MessageStream class', () => {
const stream = anthropic.messages.stream(
{
max_tokens: 1024,
- model: 'claude-2.1',
+ model: 'claude-3-7-sonnet-20250219',
messages: [{ role: 'user', content: 'Say hello there!' }],
},
{ maxRetries: 0 },
diff --git tests/api-resources/beta/models.test.ts tests/api-resources/beta/models.test.ts
index f155b632..ce7c72ab 100644
--- tests/api-resources/beta/models.test.ts
+++ tests/api-resources/beta/models.test.ts
@@ -27,6 +27,13 @@ describe('resource models', () => {
).rejects.toThrow(Anthropic.NotFoundError);
});
+ test('retrieve: request options and params are passed correctly', async () => {
+ // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error
+ await expect(
+ client.beta.models.retrieve('model_id', { betas: ['string'] }, { path: '/_stainless_unknown_path' }),
+ ).rejects.toThrow(Anthropic.NotFoundError);
+ });
+
test('list', async () => {
const responsePromise = client.beta.models.list();
const rawResponse = await responsePromise.asResponse();
@@ -49,7 +56,7 @@ describe('resource models', () => {
// ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error
await expect(
client.beta.models.list(
- { after_id: 'after_id', before_id: 'before_id', limit: 1 },
+ { after_id: 'after_id', before_id: 'before_id', limit: 1, betas: ['string'] },
{ path: '/_stainless_unknown_path' },
),
).rejects.toThrow(Anthropic.NotFoundError);
diff --git tests/api-resources/completions.test.ts tests/api-resources/completions.test.ts
index e3ebaa07..b372e474 100644
--- tests/api-resources/completions.test.ts
+++ tests/api-resources/completions.test.ts
@@ -35,6 +35,7 @@ describe('resource completions', () => {
temperature: 1,
top_k: 5,
top_p: 0.7,
+ betas: ['string'],
});
});
});
diff --git tests/api-resources/messages/batches.test.ts tests/api-resources/messages/batches.test.ts
index 95712a32..7c58ca3c 100644
--- tests/api-resources/messages/batches.test.ts
+++ tests/api-resources/messages/batches.test.ts
@@ -77,6 +77,7 @@ describe('resource batches', () => {
name: 'name',
cache_control: { type: 'ephemeral' },
description: 'Get the current weather in a given location',
+ type: 'custom',
},
],
top_k: 5,
diff --git tests/api-resources/messages/messages.test.ts tests/api-resources/messages/messages.test.ts
index 051a2c4f..b9b7bbc2 100644
--- tests/api-resources/messages/messages.test.ts
+++ tests/api-resources/messages/messages.test.ts
@@ -64,6 +64,7 @@ describe('resource messages', () => {
name: 'name',
cache_control: { type: 'ephemeral' },
description: 'Get the current weather in a given location',
+ type: 'custom',
},
],
top_k: 5,
@@ -120,6 +121,7 @@ describe('resource messages', () => {
name: 'name',
cache_control: { type: 'ephemeral' },
description: 'Get the current weather in a given location',
+ type: 'custom',
},
],
});
diff --git tests/api-resources/models.test.ts tests/api-resources/models.test.ts
index 7f5c0411..dc73dc26 100644
--- tests/api-resources/models.test.ts
+++ tests/api-resources/models.test.ts
@@ -27,6 +27,13 @@ describe('resource models', () => {
);
});
+ test('retrieve: request options and params are passed correctly', async () => {
+ // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error
+ await expect(
+ client.models.retrieve('model_id', { betas: ['string'] }, { path: '/_stainless_unknown_path' }),
+ ).rejects.toThrow(Anthropic.NotFoundError);
+ });
+
test('list', async () => {
const responsePromise = client.models.list();
const rawResponse = await responsePromise.asResponse();
@@ -49,7 +56,7 @@ describe('resource models', () => {
// ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error
await expect(
client.models.list(
- { after_id: 'after_id', before_id: 'before_id', limit: 1 },
+ { after_id: 'after_id', before_id: 'before_id', limit: 1, betas: ['string'] },
{ path: '/_stainless_unknown_path' },
),
).rejects.toThrow(Anthropic.NotFoundError);
Description
This PR adds web search capabilities to the Claude API in the TypeScript SDK. It also updates the Node.js version from 18 to 20 in CI workflows, fixes typos in the README, and adds better code examples in TSDoc comments.
Changes
Changes
CI and Version Updates
- Updated Node.js version from 18 to 20 in CI workflows
- Bumped package version from 0.40.1 to 0.41.0
- Updated changelog with new features, chores, and documentation changes
- Updated OpenAPI spec URL and associated hashes
New Web Search Functionality
- Added new types to support web search capabilities:
-
WebSearchTool20250305- Tool configuration for web search -
WebSearchResultBlock- Content block for web search results -
ServerToolUseBlock- Block for server-side tool usage -
WebSearchToolResultBlock- Results from web search queries - Various supporting types for errors, citations, and parameters
-
Documentation Improvements
- Added comprehensive JSDoc examples to API methods
- Changed "Tool use beta" to just "Tool use" in README, indicating it's now a stable feature
- Fixed typos in the README ("followed" β "follows")
- Added two new examples demonstrating web search functionality:
-
web-search.ts- Basic web search example -
web-search-stream.ts- Streaming web search example
-
Code Enhancements
- Updated
MessageStreamto handle new usage fields in the event objects - Added support for new types of content blocks in message responses
- Enhanced models API with optional beta parameter support
- Updated tool functionality to support web search tools
- Added beta parameters to various API endpoints
sequenceDiagram
participant Client
participant Anthropic as Anthropic API
participant WebSearch as Web Search System
Client->>Anthropic: Create message with web_search tool enabled
Anthropic-->>Client: Stream begins
Anthropic->>WebSearch: Perform search query
WebSearch-->>Anthropic: Return search results
Anthropic-->>Client: server_tool_use block
Anthropic-->>Client: web_search_tool_result block with results
Anthropic-->>Client: Text response based on search results
Anthropic-->>Client: Message completion with usage stats
Client->>Client: Process response with search data