# Anthropic
> Rewrite text following user-given instructions, such as with a different tone, audience, or style.
---
# Source: https://platform.claude.com/docs/en/resources/prompt-library/adaptive-editor.md
# Adaptive editor
Rewrite text following user-given instructions, such as with a different tone, audience, or style.
---
> Copy this prompt into our developer [Console](/dashboard) to try it for yourself!
| | Content |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| User | Rewrite the following paragraph using the following instructions: in the style of a pirate. Paragraph: In 1758, the Swedish botanist and zoologist Carl Linnaeus published in his Systema Naturae, the two-word naming of species (binomial nomenclature). Canis is the Latin word meaning "dog", and under this genus, he listed the domestic dog, the wolf, and the golden jackal. |
### Example output
> Ahoy mateys! Back in 1758, that scurvy botanist and animal lover Carl Linnaeus put out his book Systema Naturae, which had them fancy two-word names for all manner o' creatures (binomial nomenclature he called it). Canis be the pirate word for ""dog"", and under that heading he listed regular dogs, wolves, and golden jackals too. Arrr! All them dogs be the same to ol' Captain Linnaeus. He may have had a wooden leg and a parrot on his shoulder when he wrote that book! Haha! Now swab the deck ye scallywags before I make ye walk the plank!
---
### API request
```python Python
import anthropic
client = anthropic.Anthropic(
# defaults to os.environ.get("ANTHROPIC_API_KEY")
api_key="my_api_key",
)
message = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=2000,
temperature=1,
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "Rewrite the following paragraph using the following instructions: in the style of a pirate. \n \nParagraph: \nIn 1758, the Swedish botanist and zoologist Carl Linnaeus published in his Systema Naturae, the two-word naming of species (binomial nomenclature). Canis is the Latin word meaning \"dog\", and under this genus, he listed the domestic dog, the wolf, and the golden jackal."
}
]
}
]
)
print(message.content)
```
```typescript TypeScript
import Anthropic from "@anthropic-ai/sdk";
const anthropic = new Anthropic({
apiKey: "my_api_key", // defaults to process.env["ANTHROPIC_API_KEY"]
});
const msg = await anthropic.messages.create({
model: "claude-sonnet-4-5",
max_tokens: 2000,
temperature: 1,
messages: [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Rewrite the following paragraph using the following instructions: in the style of a pirate. \n \nParagraph: \nIn 1758, the Swedish botanist and zoologist Carl Linnaeus published in his Systema Naturae, the two-word naming of species (binomial nomenclature). Canis is the Latin word meaning \"dog\", and under this genus, he listed the domestic dog, the wolf, and the golden jackal."
}
]
}
]
});
console.log(msg);
```
```python AWS Bedrock Python
from anthropic import AnthropicBedrock
# See https://docs.claude.com/claude/reference/claude-on-amazon-bedrock
# for authentication options
client = AnthropicBedrock()
message = client.messages.create(
model="anthropic.claude-sonnet-4-5-20250929-v1:0",
max_tokens=2000,
temperature=1,
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "Rewrite the following paragraph using the following instructions: in the style of a pirate. \n \nParagraph: \nIn 1758, the Swedish botanist and zoologist Carl Linnaeus published in his Systema Naturae, the two-word naming of species (binomial nomenclature). Canis is the Latin word meaning \"dog\", and under this genus, he listed the domestic dog, the wolf, and the golden jackal."
}
]
}
]
)
print(message.content)
```
```typescript AWS Bedrock TypeScript
import AnthropicBedrock from "@anthropic-ai/bedrock-sdk";
// See https://docs.claude.com/claude/reference/claude-on-amazon-bedrock
// for authentication options
const client = new AnthropicBedrock();
const msg = await client.messages.create({
model: "anthropic.claude-sonnet-4-5-20250929-v1:0",
max_tokens: 2000,
temperature: 1,
messages: [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Rewrite the following paragraph using the following instructions: in the style of a pirate. \n \nParagraph: \nIn 1758, the Swedish botanist and zoologist Carl Linnaeus published in his Systema Naturae, the two-word naming of species (binomial nomenclature). Canis is the Latin word meaning \"dog\", and under this genus, he listed the domestic dog, the wolf, and the golden jackal."
}
]
}
]
});
console.log(msg);
```
```python Vertex AI Python
from anthropic import AnthropicVertex
client = AnthropicVertex()
message = client.messages.create(
model="claude-sonnet-4@20250514",
max_tokens=2000,
temperature=1,
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "Rewrite the following paragraph using the following instructions: in the style of a pirate. \n \nParagraph: \nIn 1758, the Swedish botanist and zoologist Carl Linnaeus published in his Systema Naturae, the two-word naming of species (binomial nomenclature). Canis is the Latin word meaning \"dog\", and under this genus, he listed the domestic dog, the wolf, and the golden jackal."
}
]
}
]
)
print(message.content)
```
```typescript Vertex AI TypeScript
import { AnthropicVertex } from '@anthropic-ai/vertex-sdk';
// Reads from the `CLOUD_ML_REGION` & `ANTHROPIC_VERTEX_PROJECT_ID` environment variables.
// Additionally goes through the standard `google-auth-library` flow.
const client = new AnthropicVertex();
const msg = await client.messages.create({
model: "claude-sonnet-4@20250514",
max_tokens: 2000,
temperature: 1,
messages: [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Rewrite the following paragraph using the following instructions: in the style of a pirate. \n \nParagraph: \nIn 1758, the Swedish botanist and zoologist Carl Linnaeus published in his Systema Naturae, the two-word naming of species (binomial nomenclature). Canis is the Latin word meaning \"dog\", and under this genus, he listed the domestic dog, the wolf, and the golden jackal."
}
]
}
]
});
console.log(msg);
```
---
# Source: https://platform.claude.com/docs/en/api/admin.md
# Admin
# Organizations
## Me
**get** `/v1/organizations/me`
Retrieve information about the organization associated with the authenticated API key.
### Returns
- `Organization = object { id, name, type }`
- `id: string`
ID of the Organization.
- `name: string`
Name of the Organization.
- `type: "organization"`
Object type.
For Organizations, this is always `"organization"`.
- `"organization"`
### Example
```http
curl https://api.anthropic.com/v1/organizations/me \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY"
```
## Domain Types
### Organization
- `Organization = object { id, name, type }`
- `id: string`
ID of the Organization.
- `name: string`
Name of the Organization.
- `type: "organization"`
Object type.
For Organizations, this is always `"organization"`.
- `"organization"`
# Invites
## Create
**post** `/v1/organizations/invites`
Create Invite
### Body Parameters
- `email: string`
Email of the User.
- `role: "user" or "developer" or "billing" or "claude_code_user"`
Role for the invited User. Cannot be "admin".
- `"user"`
- `"developer"`
- `"billing"`
- `"claude_code_user"`
### Returns
- `Invite = object { id, email, expires_at, 4 more }`
- `id: string`
ID of the Invite.
- `email: string`
Email of the User being invited.
- `expires_at: string`
RFC 3339 datetime string indicating when the Invite expires.
- `invited_at: string`
RFC 3339 datetime string indicating when the Invite was created.
- `role: "user" or "developer" or "billing" or 2 more`
Organization role of the User.
- `"user"`
- `"developer"`
- `"billing"`
- `"admin"`
- `"claude_code_user"`
- `status: "accepted" or "expired" or "deleted" or "pending"`
Status of the Invite.
- `"accepted"`
- `"expired"`
- `"deleted"`
- `"pending"`
- `type: "invite"`
Object type.
For Invites, this is always `"invite"`.
- `"invite"`
### Example
```http
curl https://api.anthropic.com/v1/organizations/invites \
-H 'Content-Type: application/json' \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY" \
-d '{
"email": "user@emaildomain.com",
"role": "user"
}'
```
## Retrieve
**get** `/v1/organizations/invites/{invite_id}`
Get Invite
### Path Parameters
- `invite_id: string`
ID of the Invite.
### Returns
- `Invite = object { id, email, expires_at, 4 more }`
- `id: string`
ID of the Invite.
- `email: string`
Email of the User being invited.
- `expires_at: string`
RFC 3339 datetime string indicating when the Invite expires.
- `invited_at: string`
RFC 3339 datetime string indicating when the Invite was created.
- `role: "user" or "developer" or "billing" or 2 more`
Organization role of the User.
- `"user"`
- `"developer"`
- `"billing"`
- `"admin"`
- `"claude_code_user"`
- `status: "accepted" or "expired" or "deleted" or "pending"`
Status of the Invite.
- `"accepted"`
- `"expired"`
- `"deleted"`
- `"pending"`
- `type: "invite"`
Object type.
For Invites, this is always `"invite"`.
- `"invite"`
### Example
```http
curl https://api.anthropic.com/v1/organizations/invites/$INVITE_ID \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY"
```
## List
**get** `/v1/organizations/invites`
List Invites
### Query Parameters
- `after_id: optional string`
ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately after this object.
- `before_id: optional string`
ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately before this object.
- `limit: optional number`
Number of items to return per page.
Defaults to `20`. Ranges from `1` to `1000`.
### Returns
- `data: array of Invite`
- `id: string`
ID of the Invite.
- `email: string`
Email of the User being invited.
- `expires_at: string`
RFC 3339 datetime string indicating when the Invite expires.
- `invited_at: string`
RFC 3339 datetime string indicating when the Invite was created.
- `role: "user" or "developer" or "billing" or 2 more`
Organization role of the User.
- `"user"`
- `"developer"`
- `"billing"`
- `"admin"`
- `"claude_code_user"`
- `status: "accepted" or "expired" or "deleted" or "pending"`
Status of the Invite.
- `"accepted"`
- `"expired"`
- `"deleted"`
- `"pending"`
- `type: "invite"`
Object type.
For Invites, this is always `"invite"`.
- `"invite"`
- `first_id: string`
First ID in the `data` list. Can be used as the `before_id` for the previous page.
- `has_more: boolean`
Indicates if there are more results in the requested page direction.
- `last_id: string`
Last ID in the `data` list. Can be used as the `after_id` for the next page.
### Example
```http
curl https://api.anthropic.com/v1/organizations/invites \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY"
```
## Delete
**delete** `/v1/organizations/invites/{invite_id}`
Delete Invite
### Path Parameters
- `invite_id: string`
ID of the Invite.
### Returns
- `id: string`
ID of the Invite.
- `type: "invite_deleted"`
Deleted object type.
For Invites, this is always `"invite_deleted"`.
- `"invite_deleted"`
### Example
```http
curl https://api.anthropic.com/v1/organizations/invites/$INVITE_ID \
-X DELETE \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY"
```
## Domain Types
### Invite
- `Invite = object { id, email, expires_at, 4 more }`
- `id: string`
ID of the Invite.
- `email: string`
Email of the User being invited.
- `expires_at: string`
RFC 3339 datetime string indicating when the Invite expires.
- `invited_at: string`
RFC 3339 datetime string indicating when the Invite was created.
- `role: "user" or "developer" or "billing" or 2 more`
Organization role of the User.
- `"user"`
- `"developer"`
- `"billing"`
- `"admin"`
- `"claude_code_user"`
- `status: "accepted" or "expired" or "deleted" or "pending"`
Status of the Invite.
- `"accepted"`
- `"expired"`
- `"deleted"`
- `"pending"`
- `type: "invite"`
Object type.
For Invites, this is always `"invite"`.
- `"invite"`
# Users
## Retrieve
**get** `/v1/organizations/users/{user_id}`
Get User
### Path Parameters
- `user_id: string`
ID of the User.
### Returns
- `User = object { id, added_at, email, 3 more }`
- `id: string`
ID of the User.
- `added_at: string`
RFC 3339 datetime string indicating when the User joined the Organization.
- `email: string`
Email of the User.
- `name: string`
Name of the User.
- `role: "user" or "developer" or "billing" or 2 more`
Organization role of the User.
- `"user"`
- `"developer"`
- `"billing"`
- `"admin"`
- `"claude_code_user"`
- `type: "user"`
Object type.
For Users, this is always `"user"`.
- `"user"`
### Example
```http
curl https://api.anthropic.com/v1/organizations/users/$USER_ID \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY"
```
## List
**get** `/v1/organizations/users`
List Users
### Query Parameters
- `after_id: optional string`
ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately after this object.
- `before_id: optional string`
ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately before this object.
- `email: optional string`
Filter by user email.
- `limit: optional number`
Number of items to return per page.
Defaults to `20`. Ranges from `1` to `1000`.
### Returns
- `data: array of User`
- `id: string`
ID of the User.
- `added_at: string`
RFC 3339 datetime string indicating when the User joined the Organization.
- `email: string`
Email of the User.
- `name: string`
Name of the User.
- `role: "user" or "developer" or "billing" or 2 more`
Organization role of the User.
- `"user"`
- `"developer"`
- `"billing"`
- `"admin"`
- `"claude_code_user"`
- `type: "user"`
Object type.
For Users, this is always `"user"`.
- `"user"`
- `first_id: string`
First ID in the `data` list. Can be used as the `before_id` for the previous page.
- `has_more: boolean`
Indicates if there are more results in the requested page direction.
- `last_id: string`
Last ID in the `data` list. Can be used as the `after_id` for the next page.
### Example
```http
curl https://api.anthropic.com/v1/organizations/users \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY"
```
## Update
**post** `/v1/organizations/users/{user_id}`
Update User
### Path Parameters
- `user_id: string`
ID of the User.
### Body Parameters
- `role: "user" or "developer" or "billing" or "claude_code_user"`
New role for the User. Cannot be "admin".
- `"user"`
- `"developer"`
- `"billing"`
- `"claude_code_user"`
### Returns
- `User = object { id, added_at, email, 3 more }`
- `id: string`
ID of the User.
- `added_at: string`
RFC 3339 datetime string indicating when the User joined the Organization.
- `email: string`
Email of the User.
- `name: string`
Name of the User.
- `role: "user" or "developer" or "billing" or 2 more`
Organization role of the User.
- `"user"`
- `"developer"`
- `"billing"`
- `"admin"`
- `"claude_code_user"`
- `type: "user"`
Object type.
For Users, this is always `"user"`.
- `"user"`
### Example
```http
curl https://api.anthropic.com/v1/organizations/users/$USER_ID \
-H 'Content-Type: application/json' \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY" \
-d '{
"role": "user"
}'
```
## Delete
**delete** `/v1/organizations/users/{user_id}`
Remove User
### Path Parameters
- `user_id: string`
ID of the User.
### Returns
- `id: string`
ID of the User.
- `type: "user_deleted"`
Deleted object type.
For Users, this is always `"user_deleted"`.
- `"user_deleted"`
### Example
```http
curl https://api.anthropic.com/v1/organizations/users/$USER_ID \
-X DELETE \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY"
```
## Domain Types
### User
- `User = object { id, added_at, email, 3 more }`
- `id: string`
ID of the User.
- `added_at: string`
RFC 3339 datetime string indicating when the User joined the Organization.
- `email: string`
Email of the User.
- `name: string`
Name of the User.
- `role: "user" or "developer" or "billing" or 2 more`
Organization role of the User.
- `"user"`
- `"developer"`
- `"billing"`
- `"admin"`
- `"claude_code_user"`
- `type: "user"`
Object type.
For Users, this is always `"user"`.
- `"user"`
# Workspaces
## Create
**post** `/v1/organizations/workspaces`
Create Workspace
### Body Parameters
- `name: string`
Name of the Workspace.
### Returns
- `Workspace = object { id, archived_at, created_at, 3 more }`
- `id: string`
ID of the Workspace.
- `archived_at: string`
RFC 3339 datetime string indicating when the Workspace was archived, or null if the Workspace is not archived.
- `created_at: string`
RFC 3339 datetime string indicating when the Workspace was created.
- `display_color: string`
Hex color code representing the Workspace in the Anthropic Console.
- `name: string`
Name of the Workspace.
- `type: "workspace"`
Object type.
For Workspaces, this is always `"workspace"`.
- `"workspace"`
### Example
```http
curl https://api.anthropic.com/v1/organizations/workspaces \
-H 'Content-Type: application/json' \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY" \
-d '{
"name": "x"
}'
```
## Retrieve
**get** `/v1/organizations/workspaces/{workspace_id}`
Get Workspace
### Path Parameters
- `workspace_id: string`
ID of the Workspace.
### Returns
- `Workspace = object { id, archived_at, created_at, 3 more }`
- `id: string`
ID of the Workspace.
- `archived_at: string`
RFC 3339 datetime string indicating when the Workspace was archived, or null if the Workspace is not archived.
- `created_at: string`
RFC 3339 datetime string indicating when the Workspace was created.
- `display_color: string`
Hex color code representing the Workspace in the Anthropic Console.
- `name: string`
Name of the Workspace.
- `type: "workspace"`
Object type.
For Workspaces, this is always `"workspace"`.
- `"workspace"`
### Example
```http
curl https://api.anthropic.com/v1/organizations/workspaces/$WORKSPACE_ID \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY"
```
## List
**get** `/v1/organizations/workspaces`
List Workspaces
### Query Parameters
- `after_id: optional string`
ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately after this object.
- `before_id: optional string`
ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately before this object.
- `include_archived: optional boolean`
Whether to include Workspaces that have been archived in the response
- `limit: optional number`
Number of items to return per page.
Defaults to `20`. Ranges from `1` to `1000`.
### Returns
- `data: array of Workspace`
- `id: string`
ID of the Workspace.
- `archived_at: string`
RFC 3339 datetime string indicating when the Workspace was archived, or null if the Workspace is not archived.
- `created_at: string`
RFC 3339 datetime string indicating when the Workspace was created.
- `display_color: string`
Hex color code representing the Workspace in the Anthropic Console.
- `name: string`
Name of the Workspace.
- `type: "workspace"`
Object type.
For Workspaces, this is always `"workspace"`.
- `"workspace"`
- `first_id: string`
First ID in the `data` list. Can be used as the `before_id` for the previous page.
- `has_more: boolean`
Indicates if there are more results in the requested page direction.
- `last_id: string`
Last ID in the `data` list. Can be used as the `after_id` for the next page.
### Example
```http
curl https://api.anthropic.com/v1/organizations/workspaces \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY"
```
## Update
**post** `/v1/organizations/workspaces/{workspace_id}`
Update Workspace
### Path Parameters
- `workspace_id: string`
ID of the Workspace.
### Body Parameters
- `name: string`
Name of the Workspace.
### Returns
- `Workspace = object { id, archived_at, created_at, 3 more }`
- `id: string`
ID of the Workspace.
- `archived_at: string`
RFC 3339 datetime string indicating when the Workspace was archived, or null if the Workspace is not archived.
- `created_at: string`
RFC 3339 datetime string indicating when the Workspace was created.
- `display_color: string`
Hex color code representing the Workspace in the Anthropic Console.
- `name: string`
Name of the Workspace.
- `type: "workspace"`
Object type.
For Workspaces, this is always `"workspace"`.
- `"workspace"`
### Example
```http
curl https://api.anthropic.com/v1/organizations/workspaces/$WORKSPACE_ID \
-H 'Content-Type: application/json' \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY" \
-d '{
"name": "x"
}'
```
## Archive
**post** `/v1/organizations/workspaces/{workspace_id}/archive`
Archive Workspace
### Path Parameters
- `workspace_id: string`
ID of the Workspace.
### Returns
- `Workspace = object { id, archived_at, created_at, 3 more }`
- `id: string`
ID of the Workspace.
- `archived_at: string`
RFC 3339 datetime string indicating when the Workspace was archived, or null if the Workspace is not archived.
- `created_at: string`
RFC 3339 datetime string indicating when the Workspace was created.
- `display_color: string`
Hex color code representing the Workspace in the Anthropic Console.
- `name: string`
Name of the Workspace.
- `type: "workspace"`
Object type.
For Workspaces, this is always `"workspace"`.
- `"workspace"`
### Example
```http
curl https://api.anthropic.com/v1/organizations/workspaces/$WORKSPACE_ID/archive \
-X POST \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY"
```
# Members
## Create
**post** `/v1/organizations/workspaces/{workspace_id}/members`
Create Workspace Member
### Path Parameters
- `workspace_id: string`
ID of the Workspace.
### Body Parameters
- `user_id: string`
ID of the User.
- `workspace_role: "workspace_user" or "workspace_developer" or "workspace_admin"`
Role of the new Workspace Member. Cannot be "workspace_billing".
- `"workspace_user"`
- `"workspace_developer"`
- `"workspace_admin"`
### Returns
- `WorkspaceMember = object { type, user_id, workspace_id, workspace_role }`
- `type: "workspace_member"`
Object type.
For Workspace Members, this is always `"workspace_member"`.
- `"workspace_member"`
- `user_id: string`
ID of the User.
- `workspace_id: string`
ID of the Workspace.
- `workspace_role: "workspace_user" or "workspace_developer" or "workspace_admin" or "workspace_billing"`
Role of the Workspace Member.
- `"workspace_user"`
- `"workspace_developer"`
- `"workspace_admin"`
- `"workspace_billing"`
### Example
```http
curl https://api.anthropic.com/v1/organizations/workspaces/$WORKSPACE_ID/members \
-H 'Content-Type: application/json' \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY" \
-d '{
"user_id": "user_01WCz1FkmYMm4gnmykNKUu3Q",
"workspace_role": "workspace_user"
}'
```
## Retrieve
**get** `/v1/organizations/workspaces/{workspace_id}/members/{user_id}`
Get Workspace Member
### Path Parameters
- `workspace_id: string`
ID of the Workspace.
- `user_id: string`
ID of the User.
### Returns
- `WorkspaceMember = object { type, user_id, workspace_id, workspace_role }`
- `type: "workspace_member"`
Object type.
For Workspace Members, this is always `"workspace_member"`.
- `"workspace_member"`
- `user_id: string`
ID of the User.
- `workspace_id: string`
ID of the Workspace.
- `workspace_role: "workspace_user" or "workspace_developer" or "workspace_admin" or "workspace_billing"`
Role of the Workspace Member.
- `"workspace_user"`
- `"workspace_developer"`
- `"workspace_admin"`
- `"workspace_billing"`
### Example
```http
curl https://api.anthropic.com/v1/organizations/workspaces/$WORKSPACE_ID/members/$USER_ID \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY"
```
## List
**get** `/v1/organizations/workspaces/{workspace_id}/members`
List Workspace Members
### Path Parameters
- `workspace_id: string`
ID of the Workspace.
### Query Parameters
- `after_id: optional string`
ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately after this object.
- `before_id: optional string`
ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately before this object.
- `limit: optional number`
Number of items to return per page.
Defaults to `20`. Ranges from `1` to `1000`.
### Returns
- `data: array of WorkspaceMember`
- `type: "workspace_member"`
Object type.
For Workspace Members, this is always `"workspace_member"`.
- `"workspace_member"`
- `user_id: string`
ID of the User.
- `workspace_id: string`
ID of the Workspace.
- `workspace_role: "workspace_user" or "workspace_developer" or "workspace_admin" or "workspace_billing"`
Role of the Workspace Member.
- `"workspace_user"`
- `"workspace_developer"`
- `"workspace_admin"`
- `"workspace_billing"`
- `first_id: string`
First ID in the `data` list. Can be used as the `before_id` for the previous page.
- `has_more: boolean`
Indicates if there are more results in the requested page direction.
- `last_id: string`
Last ID in the `data` list. Can be used as the `after_id` for the next page.
### Example
```http
curl https://api.anthropic.com/v1/organizations/workspaces/$WORKSPACE_ID/members \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY"
```
## Update
**post** `/v1/organizations/workspaces/{workspace_id}/members/{user_id}`
Update Workspace Member
### Path Parameters
- `workspace_id: string`
ID of the Workspace.
- `user_id: string`
ID of the User.
### Body Parameters
- `workspace_role: "workspace_user" or "workspace_developer" or "workspace_admin" or "workspace_billing"`
New workspace role for the User.
- `"workspace_user"`
- `"workspace_developer"`
- `"workspace_admin"`
- `"workspace_billing"`
### Returns
- `WorkspaceMember = object { type, user_id, workspace_id, workspace_role }`
- `type: "workspace_member"`
Object type.
For Workspace Members, this is always `"workspace_member"`.
- `"workspace_member"`
- `user_id: string`
ID of the User.
- `workspace_id: string`
ID of the Workspace.
- `workspace_role: "workspace_user" or "workspace_developer" or "workspace_admin" or "workspace_billing"`
Role of the Workspace Member.
- `"workspace_user"`
- `"workspace_developer"`
- `"workspace_admin"`
- `"workspace_billing"`
### Example
```http
curl https://api.anthropic.com/v1/organizations/workspaces/$WORKSPACE_ID/members/$USER_ID \
-H 'Content-Type: application/json' \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY" \
-d '{
"workspace_role": "workspace_user"
}'
```
## Delete
**delete** `/v1/organizations/workspaces/{workspace_id}/members/{user_id}`
Delete Workspace Member
### Path Parameters
- `workspace_id: string`
ID of the Workspace.
- `user_id: string`
ID of the User.
### Returns
- `type: "workspace_member_deleted"`
Deleted object type.
For Workspace Members, this is always `"workspace_member_deleted"`.
- `"workspace_member_deleted"`
- `user_id: string`
ID of the User.
- `workspace_id: string`
ID of the Workspace.
### Example
```http
curl https://api.anthropic.com/v1/organizations/workspaces/$WORKSPACE_ID/members/$USER_ID \
-X DELETE \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY"
```
## Domain Types
### Workspace Member
- `WorkspaceMember = object { type, user_id, workspace_id, workspace_role }`
- `type: "workspace_member"`
Object type.
For Workspace Members, this is always `"workspace_member"`.
- `"workspace_member"`
- `user_id: string`
ID of the User.
- `workspace_id: string`
ID of the Workspace.
- `workspace_role: "workspace_user" or "workspace_developer" or "workspace_admin" or "workspace_billing"`
Role of the Workspace Member.
- `"workspace_user"`
- `"workspace_developer"`
- `"workspace_admin"`
- `"workspace_billing"`
# API Keys
## Retrieve
**get** `/v1/organizations/api_keys/{api_key_id}`
Get Api Key
### Path Parameters
- `api_key_id: string`
ID of the API key.
### Returns
- `APIKey = object { id, created_at, created_by, 5 more }`
- `id: string`
ID of the API key.
- `created_at: string`
RFC 3339 datetime string indicating when the API Key was created.
- `created_by: object { id, type }`
The ID and type of the actor that created the API key.
- `id: string`
ID of the actor that created the object.
- `type: string`
Type of the actor that created the object.
- `name: string`
Name of the API key.
- `partial_key_hint: string`
Partially redacted hint for the API key.
- `status: "active" or "inactive" or "archived"`
Status of the API key.
- `"active"`
- `"inactive"`
- `"archived"`
- `type: "api_key"`
Object type.
For API Keys, this is always `"api_key"`.
- `"api_key"`
- `workspace_id: string`
ID of the Workspace associated with the API key, or null if the API key belongs to the default Workspace.
### Example
```http
curl https://api.anthropic.com/v1/organizations/api_keys/$API_KEY_ID \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY"
```
## List
**get** `/v1/organizations/api_keys`
List Api Keys
### Query Parameters
- `after_id: optional string`
ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately after this object.
- `before_id: optional string`
ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately before this object.
- `created_by_user_id: optional string`
Filter by the ID of the User who created the object.
- `limit: optional number`
Number of items to return per page.
Defaults to `20`. Ranges from `1` to `1000`.
- `status: optional "active" or "inactive" or "archived"`
Filter by API key status.
- `"active"`
- `"inactive"`
- `"archived"`
- `workspace_id: optional string`
Filter by Workspace ID.
### Returns
- `data: array of APIKey`
- `id: string`
ID of the API key.
- `created_at: string`
RFC 3339 datetime string indicating when the API Key was created.
- `created_by: object { id, type }`
The ID and type of the actor that created the API key.
- `id: string`
ID of the actor that created the object.
- `type: string`
Type of the actor that created the object.
- `name: string`
Name of the API key.
- `partial_key_hint: string`
Partially redacted hint for the API key.
- `status: "active" or "inactive" or "archived"`
Status of the API key.
- `"active"`
- `"inactive"`
- `"archived"`
- `type: "api_key"`
Object type.
For API Keys, this is always `"api_key"`.
- `"api_key"`
- `workspace_id: string`
ID of the Workspace associated with the API key, or null if the API key belongs to the default Workspace.
- `first_id: string`
First ID in the `data` list. Can be used as the `before_id` for the previous page.
- `has_more: boolean`
Indicates if there are more results in the requested page direction.
- `last_id: string`
Last ID in the `data` list. Can be used as the `after_id` for the next page.
### Example
```http
curl https://api.anthropic.com/v1/organizations/api_keys \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY"
```
## Update
**post** `/v1/organizations/api_keys/{api_key_id}`
Update Api Key
### Path Parameters
- `api_key_id: string`
ID of the API key.
### Body Parameters
- `name: optional string`
Name of the API key.
- `status: optional "active" or "inactive" or "archived"`
Status of the API key.
- `"active"`
- `"inactive"`
- `"archived"`
### Returns
- `APIKey = object { id, created_at, created_by, 5 more }`
- `id: string`
ID of the API key.
- `created_at: string`
RFC 3339 datetime string indicating when the API Key was created.
- `created_by: object { id, type }`
The ID and type of the actor that created the API key.
- `id: string`
ID of the actor that created the object.
- `type: string`
Type of the actor that created the object.
- `name: string`
Name of the API key.
- `partial_key_hint: string`
Partially redacted hint for the API key.
- `status: "active" or "inactive" or "archived"`
Status of the API key.
- `"active"`
- `"inactive"`
- `"archived"`
- `type: "api_key"`
Object type.
For API Keys, this is always `"api_key"`.
- `"api_key"`
- `workspace_id: string`
ID of the Workspace associated with the API key, or null if the API key belongs to the default Workspace.
### Example
```http
curl https://api.anthropic.com/v1/organizations/api_keys/$API_KEY_ID \
-H 'Content-Type: application/json' \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY" \
-d '{}'
```
# Usage Report
## Retrieve Messages
**get** `/v1/organizations/usage_report/messages`
Get Messages Usage Report
### Query Parameters
- `starting_at: string`
Time buckets that start on or after this RFC 3339 timestamp will be returned.
Each time bucket will be snapped to the start of the minute/hour/day in UTC.
- `api_key_ids: optional array of string`
Restrict usage returned to the specified API key ID(s).
- `bucket_width: optional "1d" or "1m" or "1h"`
Time granularity of the response data.
- `"1d"`
- `"1m"`
- `"1h"`
- `context_window: optional array of "0-200k" or "200k-1M"`
Restrict usage returned to the specified context window(s).
- `"0-200k"`
- `"200k-1M"`
- `ending_at: optional string`
Time buckets that end before this RFC 3339 timestamp will be returned.
- `group_by: optional array of "api_key_id" or "workspace_id" or "model" or 2 more`
Group by any subset of the available options.
- `"api_key_id"`
- `"workspace_id"`
- `"model"`
- `"service_tier"`
- `"context_window"`
- `limit: optional number`
Maximum number of time buckets to return in the response.
The default and max limits depend on `bucket_width`:
• `"1d"`: Default of 7 days, maximum of 31 days
• `"1h"`: Default of 24 hours, maximum of 168 hours
• `"1m"`: Default of 60 minutes, maximum of 1440 minutes
- `models: optional array of string`
Restrict usage returned to the specified model(s).
- `page: optional string`
Optionally set to the `next_page` token from the previous response.
- `service_tiers: optional array of "standard" or "batch" or "priority" or 3 more`
Restrict usage returned to the specified service tier(s).
- `"standard"`
- `"batch"`
- `"priority"`
- `"priority_on_demand"`
- `"flex"`
- `"flex_discount"`
- `workspace_ids: optional array of string`
Restrict usage returned to the specified workspace ID(s).
### Returns
- `MessagesUsageReport = object { data, has_more, next_page }`
- `data: array of object { ending_at, results, starting_at }`
- `ending_at: string`
End of the time bucket (exclusive) in RFC 3339 format.
- `results: array of object { api_key_id, cache_creation, cache_read_input_tokens, 7 more }`
List of usage items for this time bucket. There may be multiple items if one or more `group_by[]` parameters are specified.
- `api_key_id: string`
ID of the API key used. Null if not grouping by API key or for usage in the Anthropic Console.
- `cache_creation: object { ephemeral_1h_input_tokens, ephemeral_5m_input_tokens }`
The number of input tokens for cache creation.
- `ephemeral_1h_input_tokens: number`
The number of input tokens used to create the 1 hour cache entry.
- `ephemeral_5m_input_tokens: number`
The number of input tokens used to create the 5 minute cache entry.
- `cache_read_input_tokens: number`
The number of input tokens read from the cache.
- `context_window: "0-200k" or "200k-1M"`
Context window used. Null if not grouping by context window.
- `"0-200k"`
- `"200k-1M"`
- `model: string`
Model used. Null if not grouping by model.
- `output_tokens: number`
The number of output tokens generated.
- `server_tool_use: object { web_search_requests }`
Server-side tool usage metrics.
- `web_search_requests: number`
The number of web search requests made.
- `service_tier: "standard" or "batch" or "priority" or 3 more`
Service tier used. Null if not grouping by service tier.
- `"standard"`
- `"batch"`
- `"priority"`
- `"priority_on_demand"`
- `"flex"`
- `"flex_discount"`
- `uncached_input_tokens: number`
The number of uncached input tokens processed.
- `workspace_id: string`
ID of the Workspace used. Null if not grouping by workspace or for the default workspace.
- `starting_at: string`
Start of the time bucket (inclusive) in RFC 3339 format.
- `has_more: boolean`
Indicates if there are more results.
- `next_page: string`
Token to provide in as `page` in the subsequent request to retrieve the next page of data.
### Example
```http
curl https://api.anthropic.com/v1/organizations/usage_report/messages \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY"
```
## Retrieve Claude Code
**get** `/v1/organizations/usage_report/claude_code`
Retrieve daily aggregated usage metrics for Claude Code users.
Enables organizations to analyze developer productivity and build custom dashboards.
### Query Parameters
- `starting_at: string`
UTC date in YYYY-MM-DD format. Returns metrics for this single day only.
- `limit: optional number`
Number of records per page (default: 20, max: 1000).
- `page: optional string`
Opaque cursor token from previous response's `next_page` field.
### Returns
- `ClaudeCodeUsageReport = object { data, has_more, next_page }`
- `data: array of object { actor, core_metrics, customer_type, 6 more }`
List of Claude Code usage records for the requested date.
- `actor: object { email_address, type } or object { api_key_name, type }`
The user or API key that performed the Claude Code actions.
- `UserActor = object { email_address, type }`
- `email_address: string`
Email address of the user who performed Claude Code actions.
- `type: "user_actor"`
- `"user_actor"`
- `APIActor = object { api_key_name, type }`
- `api_key_name: string`
Name of the API key used to perform Claude Code actions.
- `type: "api_actor"`
- `"api_actor"`
- `core_metrics: object { commits_by_claude_code, lines_of_code, num_sessions, pull_requests_by_claude_code }`
Core productivity metrics measuring Claude Code usage and impact.
- `commits_by_claude_code: number`
Number of git commits created through Claude Code's commit functionality.
- `lines_of_code: object { added, removed }`
Statistics on code changes made through Claude Code.
- `added: number`
Total number of lines of code added across all files by Claude Code.
- `removed: number`
Total number of lines of code removed across all files by Claude Code.
- `num_sessions: number`
Number of distinct Claude Code sessions initiated by this actor.
- `pull_requests_by_claude_code: number`
Number of pull requests created through Claude Code's PR functionality.
- `customer_type: "api" or "subscription"`
Type of customer account (api for API customers, subscription for Pro/Team customers).
- `"api"`
- `"subscription"`
- `date: string`
UTC date for the usage metrics in YYYY-MM-DD format.
- `model_breakdown: array of object { estimated_cost, model, tokens }`
Token usage and cost breakdown by AI model used.
- `estimated_cost: object { amount, currency }`
Estimated cost for using this model
- `amount: number`
Estimated cost amount in minor currency units (e.g., cents for USD).
- `currency: string`
Currency code for the estimated cost (e.g., 'USD').
- `model: string`
Name of the AI model used for Claude Code interactions.
- `tokens: object { cache_creation, cache_read, input, output }`
Token usage breakdown for this model
- `cache_creation: number`
Number of cache creation tokens consumed by this model.
- `cache_read: number`
Number of cache read tokens consumed by this model.
- `input: number`
Number of input tokens consumed by this model.
- `output: number`
Number of output tokens generated by this model.
- `organization_id: string`
ID of the organization that owns the Claude Code usage.
- `terminal_type: string`
Type of terminal or environment where Claude Code was used.
- `tool_actions: map[object { accepted, rejected } ]`
Breakdown of tool action acceptance and rejection rates by tool type.
- `accepted: number`
Number of tool action proposals that the user accepted.
- `rejected: number`
Number of tool action proposals that the user rejected.
- `subscription_type: optional "enterprise" or "team"`
Subscription tier for subscription customers. Null for API customers.
- `"enterprise"`
- `"team"`
- `has_more: boolean`
True if there are more records available beyond the current page.
- `next_page: string`
Opaque cursor token for fetching the next page of results, or null if no more pages are available.
### Example
```http
curl https://api.anthropic.com/v1/organizations/usage_report/claude_code \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY"
```
## Domain Types
### Claude Code Usage Report
- `ClaudeCodeUsageReport = object { data, has_more, next_page }`
- `data: array of object { actor, core_metrics, customer_type, 6 more }`
List of Claude Code usage records for the requested date.
- `actor: object { email_address, type } or object { api_key_name, type }`
The user or API key that performed the Claude Code actions.
- `UserActor = object { email_address, type }`
- `email_address: string`
Email address of the user who performed Claude Code actions.
- `type: "user_actor"`
- `"user_actor"`
- `APIActor = object { api_key_name, type }`
- `api_key_name: string`
Name of the API key used to perform Claude Code actions.
- `type: "api_actor"`
- `"api_actor"`
- `core_metrics: object { commits_by_claude_code, lines_of_code, num_sessions, pull_requests_by_claude_code }`
Core productivity metrics measuring Claude Code usage and impact.
- `commits_by_claude_code: number`
Number of git commits created through Claude Code's commit functionality.
- `lines_of_code: object { added, removed }`
Statistics on code changes made through Claude Code.
- `added: number`
Total number of lines of code added across all files by Claude Code.
- `removed: number`
Total number of lines of code removed across all files by Claude Code.
- `num_sessions: number`
Number of distinct Claude Code sessions initiated by this actor.
- `pull_requests_by_claude_code: number`
Number of pull requests created through Claude Code's PR functionality.
- `customer_type: "api" or "subscription"`
Type of customer account (api for API customers, subscription for Pro/Team customers).
- `"api"`
- `"subscription"`
- `date: string`
UTC date for the usage metrics in YYYY-MM-DD format.
- `model_breakdown: array of object { estimated_cost, model, tokens }`
Token usage and cost breakdown by AI model used.
- `estimated_cost: object { amount, currency }`
Estimated cost for using this model
- `amount: number`
Estimated cost amount in minor currency units (e.g., cents for USD).
- `currency: string`
Currency code for the estimated cost (e.g., 'USD').
- `model: string`
Name of the AI model used for Claude Code interactions.
- `tokens: object { cache_creation, cache_read, input, output }`
Token usage breakdown for this model
- `cache_creation: number`
Number of cache creation tokens consumed by this model.
- `cache_read: number`
Number of cache read tokens consumed by this model.
- `input: number`
Number of input tokens consumed by this model.
- `output: number`
Number of output tokens generated by this model.
- `organization_id: string`
ID of the organization that owns the Claude Code usage.
- `terminal_type: string`
Type of terminal or environment where Claude Code was used.
- `tool_actions: map[object { accepted, rejected } ]`
Breakdown of tool action acceptance and rejection rates by tool type.
- `accepted: number`
Number of tool action proposals that the user accepted.
- `rejected: number`
Number of tool action proposals that the user rejected.
- `subscription_type: optional "enterprise" or "team"`
Subscription tier for subscription customers. Null for API customers.
- `"enterprise"`
- `"team"`
- `has_more: boolean`
True if there are more records available beyond the current page.
- `next_page: string`
Opaque cursor token for fetching the next page of results, or null if no more pages are available.
### Messages Usage Report
- `MessagesUsageReport = object { data, has_more, next_page }`
- `data: array of object { ending_at, results, starting_at }`
- `ending_at: string`
End of the time bucket (exclusive) in RFC 3339 format.
- `results: array of object { api_key_id, cache_creation, cache_read_input_tokens, 7 more }`
List of usage items for this time bucket. There may be multiple items if one or more `group_by[]` parameters are specified.
- `api_key_id: string`
ID of the API key used. Null if not grouping by API key or for usage in the Anthropic Console.
- `cache_creation: object { ephemeral_1h_input_tokens, ephemeral_5m_input_tokens }`
The number of input tokens for cache creation.
- `ephemeral_1h_input_tokens: number`
The number of input tokens used to create the 1 hour cache entry.
- `ephemeral_5m_input_tokens: number`
The number of input tokens used to create the 5 minute cache entry.
- `cache_read_input_tokens: number`
The number of input tokens read from the cache.
- `context_window: "0-200k" or "200k-1M"`
Context window used. Null if not grouping by context window.
- `"0-200k"`
- `"200k-1M"`
- `model: string`
Model used. Null if not grouping by model.
- `output_tokens: number`
The number of output tokens generated.
- `server_tool_use: object { web_search_requests }`
Server-side tool usage metrics.
- `web_search_requests: number`
The number of web search requests made.
- `service_tier: "standard" or "batch" or "priority" or 3 more`
Service tier used. Null if not grouping by service tier.
- `"standard"`
- `"batch"`
- `"priority"`
- `"priority_on_demand"`
- `"flex"`
- `"flex_discount"`
- `uncached_input_tokens: number`
The number of uncached input tokens processed.
- `workspace_id: string`
ID of the Workspace used. Null if not grouping by workspace or for the default workspace.
- `starting_at: string`
Start of the time bucket (inclusive) in RFC 3339 format.
- `has_more: boolean`
Indicates if there are more results.
- `next_page: string`
Token to provide in as `page` in the subsequent request to retrieve the next page of data.
# Cost Report
## Retrieve
**get** `/v1/organizations/cost_report`
Get Cost Report
### Query Parameters
- `starting_at: string`
Time buckets that start on or after this RFC 3339 timestamp will be returned.
Each time bucket will be snapped to the start of the minute/hour/day in UTC.
- `bucket_width: optional "1d"`
Time granularity of the response data.
- `"1d"`
- `ending_at: optional string`
Time buckets that end before this RFC 3339 timestamp will be returned.
- `group_by: optional array of "workspace_id" or "description"`
Group by any subset of the available options.
- `"workspace_id"`
- `"description"`
- `limit: optional number`
Maximum number of time buckets to return in the response.
- `page: optional string`
Optionally set to the `next_page` token from the previous response.
### Returns
- `CostReport = object { data, has_more, next_page }`
- `data: array of object { ending_at, results, starting_at }`
- `ending_at: string`
End of the time bucket (exclusive) in RFC 3339 format.
- `results: array of object { amount, context_window, cost_type, 6 more }`
List of cost items for this time bucket. There may be multiple items if one or more `group_by[]` parameters are specified.
- `amount: string`
Cost amount in lowest currency units (e.g. cents) as a decimal string. For example, `"123.45"` in `"USD"` represents `$1.23`.
- `context_window: "0-200k" or "200k-1M"`
Input context window used. Null if not grouping by description or for non-token costs.
- `"0-200k"`
- `"200k-1M"`
- `cost_type: "tokens" or "web_search" or "code_execution"`
Type of cost. Null if not grouping by description.
- `"tokens"`
- `"web_search"`
- `"code_execution"`
- `currency: string`
Currency code for the cost amount. Currently always `"USD"`.
- `description: string`
Description of the cost item. Null if not grouping by description.
- `model: string`
Model name used. Null if not grouping by description or for non-token costs.
- `service_tier: "standard" or "batch"`
Service tier used. Null if not grouping by description or for non-token costs.
- `"standard"`
- `"batch"`
- `token_type: "uncached_input_tokens" or "output_tokens" or "cache_read_input_tokens" or 2 more`
Type of token. Null if not grouping by description or for non-token costs.
- `"uncached_input_tokens"`
- `"output_tokens"`
- `"cache_read_input_tokens"`
- `"cache_creation.ephemeral_1h_input_tokens"`
- `"cache_creation.ephemeral_5m_input_tokens"`
- `workspace_id: string`
ID of the Workspace this cost is associated with. Null if not grouping by workspace or for the default workspace.
- `starting_at: string`
Start of the time bucket (inclusive) in RFC 3339 format.
- `has_more: boolean`
Indicates if there are more results.
- `next_page: string`
Token to provide in as `page` in the subsequent request to retrieve the next page of data.
### Example
```http
curl https://api.anthropic.com/v1/organizations/cost_report \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY"
```
## Domain Types
### Cost Report
- `CostReport = object { data, has_more, next_page }`
- `data: array of object { ending_at, results, starting_at }`
- `ending_at: string`
End of the time bucket (exclusive) in RFC 3339 format.
- `results: array of object { amount, context_window, cost_type, 6 more }`
List of cost items for this time bucket. There may be multiple items if one or more `group_by[]` parameters are specified.
- `amount: string`
Cost amount in lowest currency units (e.g. cents) as a decimal string. For example, `"123.45"` in `"USD"` represents `$1.23`.
- `context_window: "0-200k" or "200k-1M"`
Input context window used. Null if not grouping by description or for non-token costs.
- `"0-200k"`
- `"200k-1M"`
- `cost_type: "tokens" or "web_search" or "code_execution"`
Type of cost. Null if not grouping by description.
- `"tokens"`
- `"web_search"`
- `"code_execution"`
- `currency: string`
Currency code for the cost amount. Currently always `"USD"`.
- `description: string`
Description of the cost item. Null if not grouping by description.
- `model: string`
Model name used. Null if not grouping by description or for non-token costs.
- `service_tier: "standard" or "batch"`
Service tier used. Null if not grouping by description or for non-token costs.
- `"standard"`
- `"batch"`
- `token_type: "uncached_input_tokens" or "output_tokens" or "cache_read_input_tokens" or 2 more`
Type of token. Null if not grouping by description or for non-token costs.
- `"uncached_input_tokens"`
- `"output_tokens"`
- `"cache_read_input_tokens"`
- `"cache_creation.ephemeral_1h_input_tokens"`
- `"cache_creation.ephemeral_5m_input_tokens"`
- `workspace_id: string`
ID of the Workspace this cost is associated with. Null if not grouping by workspace or for the default workspace.
- `starting_at: string`
Start of the time bucket (inclusive) in RFC 3339 format.
- `has_more: boolean`
Indicates if there are more results.
- `next_page: string`
Token to provide in as `page` in the subsequent request to retrieve the next page of data.
---
# Source: https://platform.claude.com/docs/en/build-with-claude/administration-api.md
# Admin API overview
---
**The Admin API is unavailable for individual accounts.** To collaborate with teammates and add members, set up your organization in **Console → Settings → Organization**.
The [Admin API](/docs/en/api/admin) allows you to programmatically manage your organization's resources, including organization members, workspaces, and API keys. This provides programmatic control over administrative tasks that would otherwise require manual configuration in the [Claude Console](/).
**The Admin API requires special access**
The Admin API requires a special Admin API key (starting with `sk-ant-admin...`) that differs from standard API keys. Only organization members with the admin role can provision Admin API keys through the Claude Console.
## How the Admin API works
When you use the Admin API:
1. You make requests using your Admin API key in the `x-api-key` header
2. The API allows you to manage:
- Organization members and their roles
- Organization member invites
- Workspaces and their members
- API keys
This is useful for:
- Automating user onboarding/offboarding
- Programmatically managing workspace access
- Monitoring and managing API key usage
## Organization roles and permissions
There are five organization-level roles. See more details [here](https://support.claude.com/en/articles/10186004-api-console-roles-and-permissions).
| Role | Permissions |
|------|-------------|
| user | Can use Workbench |
| claude_code_user | Can use Workbench and [Claude Code](https://code.claude.com/docs/en/overview) |
| developer | Can use Workbench and manage API keys |
| billing | Can use Workbench and manage billing details |
| admin | Can do all of the above, plus manage users |
## Key concepts
### Organization Members
You can list [organization members](/docs/en/api/admin-api/users/get-user), update member roles, and remove members.
```bash Shell
# List organization members
curl "https://api.anthropic.com/v1/organizations/users?limit=10" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY"
# Update member role
curl "https://api.anthropic.com/v1/organizations/users/{user_id}" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY" \
--data '{"role": "developer"}'
# Remove member
curl --request DELETE "https://api.anthropic.com/v1/organizations/users/{user_id}" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY"
```
### Organization Invites
You can invite users to organizations and manage those [invites](/docs/en/api/admin-api/invites/get-invite).
```bash Shell
# Create invite
curl --request POST "https://api.anthropic.com/v1/organizations/invites" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY" \
--data '{
"email": "newuser@domain.com",
"role": "developer"
}'
# List invites
curl "https://api.anthropic.com/v1/organizations/invites?limit=10" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY"
# Delete invite
curl --request DELETE "https://api.anthropic.com/v1/organizations/invites/{invite_id}" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY"
```
### Workspaces
For a comprehensive guide to workspaces, see [Workspaces](/docs/en/build-with-claude/workspaces).
Create and manage [workspaces](/docs/en/api/admin-api/workspaces/get-workspace) ([console](/settings/workspaces)) to organize your resources:
```bash Shell
# Create workspace
curl --request POST "https://api.anthropic.com/v1/organizations/workspaces" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY" \
--data '{"name": "Production"}'
# List workspaces
curl "https://api.anthropic.com/v1/organizations/workspaces?limit=10&include_archived=false" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY"
# Archive workspace
curl --request POST "https://api.anthropic.com/v1/organizations/workspaces/{workspace_id}/archive" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY"
```
### Workspace Members
Manage [user access to specific workspaces](/docs/en/api/admin-api/workspace_members/get-workspace-member):
```bash Shell
# Add member to workspace
curl --request POST "https://api.anthropic.com/v1/organizations/workspaces/{workspace_id}/members" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY" \
--data '{
"user_id": "user_xxx",
"workspace_role": "workspace_developer"
}'
# List workspace members
curl "https://api.anthropic.com/v1/organizations/workspaces/{workspace_id}/members?limit=10" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY"
# Update member role
curl --request POST "https://api.anthropic.com/v1/organizations/workspaces/{workspace_id}/members/{user_id}" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY" \
--data '{
"workspace_role": "workspace_admin"
}'
# Remove member from workspace
curl --request DELETE "https://api.anthropic.com/v1/organizations/workspaces/{workspace_id}/members/{user_id}" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY"
```
### API Keys
Monitor and manage [API keys](/docs/en/api/admin-api/apikeys/get-api-key):
```bash Shell
# List API keys
curl "https://api.anthropic.com/v1/organizations/api_keys?limit=10&status=active&workspace_id=wrkspc_xxx" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY"
# Update API key
curl --request POST "https://api.anthropic.com/v1/organizations/api_keys/{api_key_id}" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY" \
--data '{
"status": "inactive",
"name": "New Key Name"
}'
```
## Accessing organization info
Get information about your organization programmatically with the `/v1/organizations/me` endpoint.
For example:
```bash
curl "https://api.anthropic.com/v1/organizations/me" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ADMIN_API_KEY"
```
```json
{
"id": "12345678-1234-5678-1234-567812345678",
"type": "organization",
"name": "Organization Name"
}
```
This endpoint is useful for programmatically determining which organization an Admin API key belongs to.
For complete parameter details and response schemas, see the [Organization Info API reference](/docs/en/api/admin-api/organization/get-me).
## Accessing usage and cost reports
To access usage and cost reports for your organization, use the Usage and Cost API endpoints:
- The [**Usage endpoint**](/docs/en/build-with-claude/usage-cost-api#usage-api) (`/v1/organizations/usage_report/messages`) provides detailed usage data, including token counts and request metrics, grouped by various dimensions such as workspace, user, and model.
- The [**Cost endpoint**](/docs/en/build-with-claude/usage-cost-api#cost-api) (`/v1/organizations/cost_report`) provides cost data associated with your organization's usage, allowing you to track expenses and allocate costs by workspace or description.
These endpoints provide detailed insights into your organization's usage and associated costs.
## Accessing Claude Code analytics
For organizations using Claude Code, the [**Claude Code Analytics API**](/docs/en/build-with-claude/claude-code-analytics-api) provides detailed productivity metrics and usage insights:
- The [**Claude Code Analytics endpoint**](/docs/en/build-with-claude/claude-code-analytics-api) (`/v1/organizations/usage_report/claude_code`) provides daily aggregated metrics for Claude Code usage, including sessions, lines of code, commits, pull requests, tool usage statistics, and cost data broken down by user and model.
This API enables you to track developer productivity, analyze Claude Code adoption, and build custom dashboards for your organization.
## Best practices
To effectively use the Admin API:
- Use meaningful names and descriptions for workspaces and API keys
- Implement proper error handling for failed operations
- Regularly audit member roles and permissions
- Clean up unused workspaces and expired invites
- Monitor API key usage and rotate keys periodically
## FAQ
Only organization members with the admin role can use the Admin API. They must also have a special Admin API key (starting with `sk-ant-admin`).
No, new API keys can only be created through the Claude Console for security reasons. The Admin API can only manage existing API keys.
API keys persist in their current state as they are scoped to the Organization, not to individual users.
No, organization members with the admin role cannot be removed via the API for security reasons.
Organization invites expire after 21 days. There is currently no way to modify this expiration period.
Yes, you can have a maximum of 100 workspaces per Organization. Archived workspaces do not count towards this limit.
Every Organization has a "Default Workspace" that cannot be edited or removed, and has no ID. This Workspace does not appear in workspace list endpoints.
Organization admins automatically get the `workspace_admin` role to all workspaces. Organization billing members automatically get the `workspace_billing` role. Organization users and developers must be manually added to each workspace.
Organization users and developers can be assigned `workspace_admin`, `workspace_developer`, or `workspace_user` roles. The `workspace_billing` role can't be manually assigned - it's inherited from having the organization `billing` role.
Only organization billing members can have their workspace role upgraded to an admin role. Otherwise, organization admins and billing members can't have their workspace roles changed or be removed from workspaces while they hold those organization roles. Their workspace access must be modified by changing their organization role first.
If an organization admin or billing member is demoted to user or developer, they lose access to all workspaces except ones where they were manually assigned roles. When users are promoted to admin or billing roles, they gain automatic access to all workspaces.
---
# Source: https://platform.claude.com/docs/en/resources/prompt-library/airport-code-analyst.md
# Airport code analyst
Find and extract airport codes from text.
---
> Copy this prompt into our developer [Console](/dashboard) to try it for yourself!
| | Content |
| ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| System | Your task is to analyze the provided text and identify any airport codes mentioned within it. Present these airport codes as a list in the order they appear in the text. If no airport codes are found, return an empty list. |
| User | My next trip involves flying from Seattle to Amsterdam. I'll be spending a few days in Amsterdam before heading to Paris for a connecting flight to Rome. |
### Example Output
> Here is the list of airport codes mentioned in the text, in the order they appear:
>
> 1. SEA (Seattle)
> 2. AMS (Amsterdam)
> 3. CDG (Paris)
> 4. FCO (Rome)
### API request
```python Python
import anthropic
client = anthropic.Anthropic(
# defaults to os.environ.get("ANTHROPIC_API_KEY")
api_key="my_api_key",
)
message = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1000,
temperature=0,
system="Your task is to analyze the provided text and identify any airport codes mentioned within it. Present these airport codes as a list in the order they appear in the text. If no airport codes are found, return an empty list.",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "My next trip involves flying from Seattle to Amsterdam. I'll be spending a few days in Amsterdam before heading to Paris for a connecting flight to Rome."
}
]
}
]
)
print(message.content)
```
```typescript TypeScript
import Anthropic from "@anthropic-ai/sdk";
const anthropic = new Anthropic({
apiKey: "my_api_key", // defaults to process.env["ANTHROPIC_API_KEY"]
});
const msg = await anthropic.messages.create({
model: "claude-sonnet-4-5",
max_tokens: 1000,
temperature: 0,
system: "Your task is to analyze the provided text and identify any airport codes mentioned within it. Present these airport codes as a list in the order they appear in the text. If no airport codes are found, return an empty list.",
messages: [
{
"role": "user",
"content": [
{
"type": "text",
"text": "My next trip involves flying from Seattle to Amsterdam. I'll be spending a few days in Amsterdam before heading to Paris for a connecting flight to Rome."
}
]
}
]
});
console.log(msg);
```
```python AWS Bedrock Python
from anthropic import AnthropicBedrock
# See https://docs.claude.com/claude/reference/claude-on-amazon-bedrock
# for authentication options
client = AnthropicBedrock()
message = client.messages.create(
model="anthropic.claude-sonnet-4-5-20250929-v1:0",
max_tokens=1000,
temperature=0,
system="Your task is to analyze the provided text and identify any airport codes mentioned within it. Present these airport codes as a list in the order they appear in the text. If no airport codes are found, return an empty list.",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "My next trip involves flying from Seattle to Amsterdam. I'll be spending a few days in Amsterdam before heading to Paris for a connecting flight to Rome."
}
]
}
]
)
print(message.content)
```
```typescript AWS Bedrock TypeScript
import AnthropicBedrock from "@anthropic-ai/bedrock-sdk";
// See https://docs.claude.com/claude/reference/claude-on-amazon-bedrock
// for authentication options
const client = new AnthropicBedrock();
const msg = await client.messages.create({
model: "anthropic.claude-sonnet-4-5-20250929-v1:0",
max_tokens: 1000,
temperature: 0,
system: "Your task is to analyze the provided text and identify any airport codes mentioned within it. Present these airport codes as a list in the order they appear in the text. If no airport codes are found, return an empty list.",
messages: [
{
"role": "user",
"content": [
{
"type": "text",
"text": "My next trip involves flying from Seattle to Amsterdam. I'll be spending a few days in Amsterdam before heading to Paris for a connecting flight to Rome."
}
]
}
]
});
console.log(msg);
```
```python Vertex AI Python
from anthropic import AnthropicVertex
client = AnthropicVertex()
message = client.messages.create(
model="claude-sonnet-4@20250514",
max_tokens=1000,
temperature=0,
system="Your task is to analyze the provided text and identify any airport codes mentioned within it. Present these airport codes as a list in the order they appear in the text. If no airport codes are found, return an empty list.",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "My next trip involves flying from Seattle to Amsterdam. I'll be spending a few days in Amsterdam before heading to Paris for a connecting flight to Rome."
}
]
}
]
)
print(message.content)
```
```typescript Vertex AI TypeScript
import { AnthropicVertex } from '@anthropic-ai/vertex-sdk';
// Reads from the `CLOUD_ML_REGION` & `ANTHROPIC_VERTEX_PROJECT_ID` environment variables.
// Additionally goes through the standard `google-auth-library` flow.
const client = new AnthropicVertex();
const msg = await client.messages.create({
model: "claude-sonnet-4@20250514",
max_tokens: 1000,
temperature: 0,
system: "Your task is to analyze the provided text and identify any airport codes mentioned within it. Present these airport codes as a list in the order they appear in the text. If no airport codes are found, return an empty list.",
messages: [
{
"role": "user",
"content": [
{
"type": "text",
"text": "My next trip involves flying from Seattle to Amsterdam. I'll be spending a few days in Amsterdam before heading to Paris for a connecting flight to Rome."
}
]
}
]
});
console.log(msg);
```
---
# Source: https://platform.claude.com/docs/en/resources/prompt-library/alien-anthropologist.md
# Alien anthropologist
Analyze human culture and customs from the perspective of an alien anthropologist.
---
> Copy this prompt into our developer [Console](/dashboard) to try it for yourself!
| | Content |
| ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| System | Imagine you are an alien anthropologist studying human culture and customs. Analyze the following aspects of human society from an objective, outsider's perspective. Provide detailed observations, insights, and hypotheses based on the available information. |
| User | Human social interactions and relationships |
### Example output
> - Humans form various types of social bonds, including familial, romantic, and platonic relationships.
> - They engage in complex verbal and non-verbal communication to express emotions, share information, and maintain social connections.
> - Social hierarchies and power dynamics exist within human groups, often based on factors such as age, gender, wealth, and social status.
> - Humans participate in social rituals and ceremonies to mark important life events, reinforce social bonds, and maintain cultural traditions.
>
> Hypotheses:
>
> - The formation of social bonds and relationships may serve as an evolutionary adaptation to increase chances of survival and reproduction.
> - Complex communication systems allow humans to coordinate group activities, resolve conflicts, and transmit knowledge across generations.
> - Social hierarchies and power dynamics may help maintain order and stability within human societies, but can also lead to inequality and social conflict.
> - Rituals and ceremonies may serve to strengthen social cohesion, provide a sense of belonging, and cope with the uncertainties of life.
---
### API Request
```python Python
import anthropic
client = anthropic.Anthropic(
# defaults to os.environ.get("ANTHROPIC_API_KEY")
api_key="my_api_key",
)
message = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=2000,
temperature=1,
system="Imagine you are an alien anthropologist studying human culture and customs. Analyze the following aspects of human society from an objective, outsider's perspective. Provide detailed observations, insights, and hypotheses based on the available information.",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "Human social interactions and relationships"
}
]
}
]
)
print(message.content)
```
```typescript TypeScript
import Anthropic from "@anthropic-ai/sdk";
const anthropic = new Anthropic({
apiKey: "my_api_key", // defaults to process.env["ANTHROPIC_API_KEY"]
});
const msg = await anthropic.messages.create({
model: "claude-sonnet-4-5",
max_tokens: 2000,
temperature: 1,
system: "Imagine you are an alien anthropologist studying human culture and customs. Analyze the following aspects of human society from an objective, outsider's perspective. Provide detailed observations, insights, and hypotheses based on the available information.",
messages: [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Human social interactions and relationships"
}
]
}
]
});
console.log(msg);
```
```python AWS Bedrock Python
from anthropic import AnthropicBedrock
# See https://docs.claude.com/claude/reference/claude-on-amazon-bedrock
# for authentication options
client = AnthropicBedrock()
message = client.messages.create(
model="anthropic.claude-sonnet-4-5-20250929-v1:0",
max_tokens=2000,
temperature=1,
system="Imagine you are an alien anthropologist studying human culture and customs. Analyze the following aspects of human society from an objective, outsider's perspective. Provide detailed observations, insights, and hypotheses based on the available information.",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "Human social interactions and relationships"
}
]
}
]
)
print(message.content)
```
```typescript AWS Bedrock TypeScript
import AnthropicBedrock from "@anthropic-ai/bedrock-sdk";
// See https://docs.claude.com/claude/reference/claude-on-amazon-bedrock
// for authentication options
const client = new AnthropicBedrock();
const msg = await client.messages.create({
model: "anthropic.claude-sonnet-4-5-20250929-v1:0",
max_tokens: 2000,
temperature: 1,
system: "Imagine you are an alien anthropologist studying human culture and customs. Analyze the following aspects of human society from an objective, outsider's perspective. Provide detailed observations, insights, and hypotheses based on the available information.",
messages: [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Human social interactions and relationships"
}
]
}
]
});
console.log(msg);
```
```python Vertex AI Python
from anthropic import AnthropicVertex
client = AnthropicVertex()
message = client.messages.create(
model="claude-sonnet-4@20250514",
max_tokens=2000,
temperature=1,
system="Imagine you are an alien anthropologist studying human culture and customs. Analyze the following aspects of human society from an objective, outsider's perspective. Provide detailed observations, insights, and hypotheses based on the available information.",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "Human social interactions and relationships"
}
]
}
]
)
print(message.content)
```
```typescript Vertex AI TypeScript
import { AnthropicVertex } from '@anthropic-ai/vertex-sdk';
// Reads from the `CLOUD_ML_REGION` & `ANTHROPIC_VERTEX_PROJECT_ID` environment variables.
// Additionally goes through the standard `google-auth-library` flow.
const client = new AnthropicVertex();
const msg = await client.messages.create({
model: "claude-sonnet-4@20250514",
max_tokens: 2000,
temperature: 1,
system: "Imagine you are an alien anthropologist studying human culture and customs. Analyze the following aspects of human society from an objective, outsider's perspective. Provide detailed observations, insights, and hypotheses based on the available information.",
messages: [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Human social interactions and relationships"
}
]
}
]
});
console.log(msg);
```
---
# Source: https://platform.claude.com/docs/en/resources/prompt-library/alliteration-alchemist.md
# Alliteration alchemist
Generate alliterative phrases and sentences for any given subject.
---
> Copy this prompt into our developer [Console](/dashboard) to try it for yourself!
| | Content |
| ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| System | Your task is to create alliterative phrases and sentences for the given subject. Ensure that the alliterations not only sound pleasing but also convey relevant information or evoke appropriate emotions related to the subject. |
| User | Ocean |
### Example output
> 1. Whispering waves wash over the shore.
> 2. Salty sea spray splashes on the sand.
> 3. Crashing currents carve coastal cliffs.
> 4. Deep, dark depths disguise hidden dangers.
> 5. Bubbling brooks bring life to the beach.
> 6. Mighty, majestic mammals migrate through the waters.
> 7. Thundering tides toss ships to and fro.
> 8. Shimmering shoals shelter secretive sea creatures.
> 9. Rippling reflections reveal a world beneath the surface.
> 10. Swirling, surging seas shape the shoreline.
> 11. Foaming, frothing floes flow freely.
> 12. Graceful gulls glide above the glistening ocean.
> 13. Playful porpoises plunge through the pristine waters.
> 14. Briny breezes blow across the boundless blue.
> 15. Rhythmic ripples roll towards the rocky coast.
> 16. Coral caves conceal colorful aquatic communities.
> 17. Stormy skies and swelling seas signal nature's might.
> 18. Tumbling tides transform the tranquil bay.
> 19. Whirling, whooshing winds whip up the waves.
> 20. Serene, sapphire waters stretch to the horizon.
---
### API request
```python Python
import anthropic
client = anthropic.Anthropic(
# defaults to os.environ.get("ANTHROPIC_API_KEY")
api_key="my_api_key",
)
message = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1000,
temperature=1,
system="Your task is to create alliterative phrases and sentences for the given subject. Ensure that the alliterations not only sound pleasing but also convey relevant information or evoke appropriate emotions related to the subject.",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "Ocean"
}
]
}
]
)
print(message.content)
```
```typescript TypeScript
import Anthropic from "@anthropic-ai/sdk";
const anthropic = new Anthropic({
apiKey: "my_api_key", // defaults to process.env["ANTHROPIC_API_KEY"]
});
const msg = await anthropic.messages.create({
model: "claude-sonnet-4-5",
max_tokens: 1000,
temperature: 1,
system: "Your task is to create alliterative phrases and sentences for the given subject. Ensure that the alliterations not only sound pleasing but also convey relevant information or evoke appropriate emotions related to the subject.",
messages: [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Ocean"
}
]
}
]
});
console.log(msg);
```
```python AWS Bedrock Python
from anthropic import AnthropicBedrock
# See https://docs.claude.com/claude/reference/claude-on-amazon-bedrock
# for authentication options
client = AnthropicBedrock()
message = client.messages.create(
model="anthropic.claude-sonnet-4-5-20250929-v1:0",
max_tokens=1000,
temperature=1,
system="Your task is to create alliterative phrases and sentences for the given subject. Ensure that the alliterations not only sound pleasing but also convey relevant information or evoke appropriate emotions related to the subject.",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "Ocean"
}
]
}
]
)
print(message.content)
```
```typescript AWS Bedrock TypeScript
import AnthropicBedrock from "@anthropic-ai/bedrock-sdk";
// See https://docs.claude.com/claude/reference/claude-on-amazon-bedrock
// for authentication options
const client = new AnthropicBedrock();
const msg = await client.messages.create({
model: "anthropic.claude-sonnet-4-5-20250929-v1:0",
max_tokens: 1000,
temperature: 1,
system: "Your task is to create alliterative phrases and sentences for the given subject. Ensure that the alliterations not only sound pleasing but also convey relevant information or evoke appropriate emotions related to the subject.",
messages: [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Ocean"
}
]
}
]
});
console.log(msg);
```
```python Vertex AI Python
from anthropic import AnthropicVertex
client = AnthropicVertex()
message = client.messages.create(
model="claude-sonnet-4@20250514",
max_tokens=1000,
temperature=1,
system="Your task is to create alliterative phrases and sentences for the given subject. Ensure that the alliterations not only sound pleasing but also convey relevant information or evoke appropriate emotions related to the subject.",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "Ocean"
}
]
}
]
)
print(message.content)
```
```typescript Vertex AI TypeScript
import { AnthropicVertex } from '@anthropic-ai/vertex-sdk';
// Reads from the `CLOUD_ML_REGION` & `ANTHROPIC_VERTEX_PROJECT_ID` environment variables.
// Additionally goes through the standard `google-auth-library` flow.
const client = new AnthropicVertex();
const msg = await client.messages.create({
model: "claude-sonnet-4@20250514",
max_tokens: 1000,
temperature: 1,
system: "Your task is to create alliterative phrases and sentences for the given subject. Ensure that the alliterations not only sound pleasing but also convey relevant information or evoke appropriate emotions related to the subject.",
messages: [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Ocean"
}
]
}
]
});
console.log(msg);
```
---
# Source: https://platform.claude.com/docs/en/api/admin/api_keys.md
# API Keys
## Retrieve
**get** `/v1/organizations/api_keys/{api_key_id}`
Get Api Key
### Path Parameters
- `api_key_id: string`
ID of the API key.
### Returns
- `APIKey = object { id, created_at, created_by, 5 more }`
- `id: string`
ID of the API key.
- `created_at: string`
RFC 3339 datetime string indicating when the API Key was created.
- `created_by: object { id, type }`
The ID and type of the actor that created the API key.
- `id: string`
ID of the actor that created the object.
- `type: string`
Type of the actor that created the object.
- `name: string`
Name of the API key.
- `partial_key_hint: string`
Partially redacted hint for the API key.
- `status: "active" or "inactive" or "archived"`
Status of the API key.
- `"active"`
- `"inactive"`
- `"archived"`
- `type: "api_key"`
Object type.
For API Keys, this is always `"api_key"`.
- `"api_key"`
- `workspace_id: string`
ID of the Workspace associated with the API key, or null if the API key belongs to the default Workspace.
### Example
```http
curl https://api.anthropic.com/v1/organizations/api_keys/$API_KEY_ID \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY"
```
## List
**get** `/v1/organizations/api_keys`
List Api Keys
### Query Parameters
- `after_id: optional string`
ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately after this object.
- `before_id: optional string`
ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately before this object.
- `created_by_user_id: optional string`
Filter by the ID of the User who created the object.
- `limit: optional number`
Number of items to return per page.
Defaults to `20`. Ranges from `1` to `1000`.
- `status: optional "active" or "inactive" or "archived"`
Filter by API key status.
- `"active"`
- `"inactive"`
- `"archived"`
- `workspace_id: optional string`
Filter by Workspace ID.
### Returns
- `data: array of APIKey`
- `id: string`
ID of the API key.
- `created_at: string`
RFC 3339 datetime string indicating when the API Key was created.
- `created_by: object { id, type }`
The ID and type of the actor that created the API key.
- `id: string`
ID of the actor that created the object.
- `type: string`
Type of the actor that created the object.
- `name: string`
Name of the API key.
- `partial_key_hint: string`
Partially redacted hint for the API key.
- `status: "active" or "inactive" or "archived"`
Status of the API key.
- `"active"`
- `"inactive"`
- `"archived"`
- `type: "api_key"`
Object type.
For API Keys, this is always `"api_key"`.
- `"api_key"`
- `workspace_id: string`
ID of the Workspace associated with the API key, or null if the API key belongs to the default Workspace.
- `first_id: string`
First ID in the `data` list. Can be used as the `before_id` for the previous page.
- `has_more: boolean`
Indicates if there are more results in the requested page direction.
- `last_id: string`
Last ID in the `data` list. Can be used as the `after_id` for the next page.
### Example
```http
curl https://api.anthropic.com/v1/organizations/api_keys \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY"
```
## Update
**post** `/v1/organizations/api_keys/{api_key_id}`
Update Api Key
### Path Parameters
- `api_key_id: string`
ID of the API key.
### Body Parameters
- `name: optional string`
Name of the API key.
- `status: optional "active" or "inactive" or "archived"`
Status of the API key.
- `"active"`
- `"inactive"`
- `"archived"`
### Returns
- `APIKey = object { id, created_at, created_by, 5 more }`
- `id: string`
ID of the API key.
- `created_at: string`
RFC 3339 datetime string indicating when the API Key was created.
- `created_by: object { id, type }`
The ID and type of the actor that created the API key.
- `id: string`
ID of the actor that created the object.
- `type: string`
Type of the actor that created the object.
- `name: string`
Name of the API key.
- `partial_key_hint: string`
Partially redacted hint for the API key.
- `status: "active" or "inactive" or "archived"`
Status of the API key.
- `"active"`
- `"inactive"`
- `"archived"`
- `type: "api_key"`
Object type.
For API Keys, this is always `"api_key"`.
- `"api_key"`
- `workspace_id: string`
ID of the Workspace associated with the API key, or null if the API key belongs to the default Workspace.
### Example
```http
curl https://api.anthropic.com/v1/organizations/api_keys/$API_KEY_ID \
-H 'Content-Type: application/json' \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY" \
-d '{}'
```
---
# Source: https://docs.claude.com/en/api/admin-api/workspaces/archive-workspace.md
## Archive
**post** `/v1/organizations/workspaces/{workspace_id}/archive`
Archive Workspace
### Path Parameters
- `workspace_id: string`
ID of the Workspace.
### Returns
- `Workspace = object { id, archived_at, created_at, 3 more }`
- `id: string`
ID of the Workspace.
- `archived_at: string`
RFC 3339 datetime string indicating when the Workspace was archived, or null if the Workspace is not archived.
- `created_at: string`
RFC 3339 datetime string indicating when the Workspace was created.
- `display_color: string`
Hex color code representing the Workspace in the Anthropic Console.
- `name: string`
Name of the Workspace.
- `type: "workspace"`
Object type.
For Workspaces, this is always `"workspace"`.
- `"workspace"`
### Example
```http
curl https://api.anthropic.com/v1/organizations/workspaces/$WORKSPACE_ID/archive \
-X POST \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY"
```
---
# Source: https://platform.claude.com/docs/en/api/admin/workspaces/archive.md
## Archive
**post** `/v1/organizations/workspaces/{workspace_id}/archive`
Archive Workspace
### Path Parameters
- `workspace_id: string`
ID of the Workspace.
### Returns
- `Workspace = object { id, archived_at, created_at, 3 more }`
- `id: string`
ID of the Workspace.
- `archived_at: string`
RFC 3339 datetime string indicating when the Workspace was archived, or null if the Workspace is not archived.
- `created_at: string`
RFC 3339 datetime string indicating when the Workspace was created.
- `display_color: string`
Hex color code representing the Workspace in the Anthropic Console.
- `name: string`
Name of the Workspace.
- `type: "workspace"`
Object type.
For Workspaces, this is always `"workspace"`.
- `"workspace"`
### Example
```http
curl https://api.anthropic.com/v1/organizations/workspaces/$WORKSPACE_ID/archive \
-X POST \
-H "X-Api-Key: $ANTHROPIC_ADMIN_API_KEY"
```
---
# Source: https://platform.claude.com/docs/en/resources/prompt-library/babels-broadcasts.md
# Babel's broadcasts
Create compelling product announcement tweets in the world's 10 most spoken languages.
---
> Copy this prompt into our developer [Console](/dashboard) to try it for yourself!
| | Content |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| User | Write me a series of product announcement tweets in the 10 most commonly spoken languages. The product is a new state of the art pair of binoculars with built-in AI systems to identify the animals viewed through the binoculars. The tweets should be exciting, cutting edge, and push consumer interest. |
| User | A future where humans can upload their consciousness into a digital realm. |
### Example output
> Here are a series of product announcement tweets in the 10 most commonly spoken languages for a new state-of-the-art pair of binoculars with built-in AI systems to identify animals:
>
> English:
> Introducing the future of bird/wildlife watching! Our new AI binoculars use cutting-edge vision tech to instantly identify any animal you see. Bring the great outdoors to life like never before! #NatureTech #AIBinoculars
>
> Mandarin Chinese:
> 令人兴奋的新品上市!我们的 AI 双筒望远镜融合了尖端视觉技术,可即时识别你所见的任何动物。让大自然的奇迹在你眼前展现,体验前所未有的观赏体验!#智能科技 #AIBinoculars
>
> Hindi:
> बर्ड/वन्यजीव वॉचिंग के लिए भविष्य का अविष्कार! हमारी नई एआई दूरबीनें अत्याधुनिक दृष्टि प्रौद्योगिकी का उपयोग करती हैं, जो आपको दिखाई देने वाले किसी भी जानवर की पहचान करने में सक्षम हैं। पहले कभी न देखी प्रकृति के अद्भुत दृश्यों का अनुभव करें! #NatureWonders #AIBinoculars
>
> Spanish:
> ¡Presentamos el futuro de la observación de aves/vida silvestre! Nuestros nuevos binoculares con IA utilizan técnicas avanzadas de visión para identificar instantáneamente cualquier animal que veas. ¡Experimenta la naturaleza como nunca antes! #TecnologíaNatural #PrismáticosIA
>
> Arabic:
> نقدم لكم مستقبل مراقبة الطيور/الحياة البرية! توفر نظارات المجهر الجديدة لدينا المزودة بالذكاء الاصطناعي تقنيات رؤية متطورة لتحديد هوية أي حيوان تراه على الفور. شاهد عجائب الطبيعة كما لم تفعل من قبل! #تكنولوجيا*الطبيعة #منظار*ذكي
>
> Bengali:
> পাখি/বন্য প্রাণী পর্যবেক্ষণের ভবিষ্যতের উন্মোচন! আমাদের নতুন এআই দুর্বীনগুলি অত্যাধুনিক ভিশন প্রযুক্তি ব্যবহার করে যেকোনো প্রাণীকে দ্রুত চিহ্নিত করতে সক্ষম। প্রকৃতির অপরূপ দৃশ্য আগেকার চেয়ে ভিন্নভাবে উপভোগ করুন! #প্রাকৃতিকপ্রযুক্তি #AIBinoculars
>
> Russian:
> Представляем будущее наблюдения за птицами/дикой природой! Наши новые бинокли с ИИ используют передовые технологии компьютерного зрения для мгновенной идентификации любого животного. Откройте для себя природу по-новому! #ПриродныеТехнологии #БинокльСИИ
>
> Portuguese:
> Apresentamos o futuro da observação de aves/vida selvagem! Os nossos novos binóculos com IA usam técnicas avançadas de visão para identificar instantaneamente qualquer animal que veja. Experiencie a natureza como nunca antes! #TecnologiaNatural #BinóculosIA
>
> Japanese:
> 鳥/野生動物観察の未来をご紹介!新しい AI バイノキュラーは、最先端のビジョン技術を使用して、あなたが見たあらゆる動物をすばやく特定します。自然をこれまでにない方法で体験してください!#ネイチャーテック #AI バイノキュラー
>
> Punjabi:
> ਪੰਛੀਆਂ/ਜੰਗਲੀ ਜੀਵਨ ਦੇਖਣ ਦੇ ਭਵਿੱਖ ਦਾ ਐਲਾਨ! ਸਾਡੀਆਂ ਨਵੀਆਂ ਏਆਈ ਦੂਰਬੀਨਾਂ ਅਤਿ ਆਧੁਨਿਕ ਦ੍ਰਿਸ਼ਟੀ ਤਕਨਾਲੋਜੀ ਦੀ ਵਰਤੋਂ ਕਰਦੀਆਂ ਹਨ ਜੋ ਤੁਸੀਂ ਦੇਖਦੇ ਹੋ ਕਿਸੇ ਵੀ ਜਾਨਵਰ ਦੀ ਸਿੱਧੀ ਪਛਾਣ ਕਰਨ ਦੇ ਸਮਰੱਥ ਹਨ। ਪ੍ਰਕਿਰਤੀ ਦਾ ਅਨੁਭਵ ਪਹਿਲਾਂ ਨਾਲੋਂ ਵੱਖਰੇ ਢੰਗ ਨਾਲ ਕਰੋ! #NeighborhoodTech #AIBinoculars
---
### API request
```python Python
import anthropic
client = anthropic.Anthropic(
# defaults to os.environ.get("ANTHROPIC_API_KEY")
api_key="my_api_key",
)
message = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=2000,
temperature=0,
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "Write me a series of product announcement tweets in the 10 most commonly spoken languages. The product is a new state of the art pair of binoculars with built-in AI systems to identify the animals viewed through the binoculars. The tweets should be exciting, cutting edge, and push consumer interest."
}
]
}
]
)
print(message.content)
```
```typescript TypeScript
import Anthropic from "@anthropic-ai/sdk";
const anthropic = new Anthropic({
apiKey: "my_api_key", // defaults to process.env["ANTHROPIC_API_KEY"]
});
const msg = await anthropic.messages.create({
model: "claude-sonnet-4-5",
max_tokens: 2000,
temperature: 0,
messages: [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Write me a series of product announcement tweets in the 10 most commonly spoken languages. The product is a new state of the art pair of binoculars with built-in AI systems to identify the animals viewed through the binoculars. The tweets should be exciting, cutting edge, and push consumer interest."
}
]
}
]
});
console.log(msg);
```
```python AWS Bedrock Python
from anthropic import AnthropicBedrock
# See https://docs.claude.com/claude/reference/claude-on-amazon-bedrock
# for authentication options
client = AnthropicBedrock()
message = client.messages.create(
model="anthropic.claude-sonnet-4-5-20250929-v1:0",
max_tokens=2000,
temperature=0,
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "Write me a series of product announcement tweets in the 10 most commonly spoken languages. The product is a new state of the art pair of binoculars with built-in AI systems to identify the animals viewed through the binoculars. The tweets should be exciting, cutting edge, and push consumer interest."
}
]
}
]
)
print(message.content)
```
```typescript AWS Bedrock TypeScript
import AnthropicBedrock from "@anthropic-ai/bedrock-sdk";
// See https://docs.claude.com/claude/reference/claude-on-amazon-bedrock
// for authentication options
const client = new AnthropicBedrock();
const msg = await client.messages.create({
model: "anthropic.claude-sonnet-4-5-20250929-v1:0",
max_tokens: 2000,
temperature: 0,
messages: [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Write me a series of product announcement tweets in the 10 most commonly spoken languages. The product is a new state of the art pair of binoculars with built-in AI systems to identify the animals viewed through the binoculars. The tweets should be exciting, cutting edge, and push consumer interest."
}
]
}
]
});
console.log(msg);
```
```python Vertex AI Python
from anthropic import AnthropicVertex
client = AnthropicVertex()
message = client.messages.create(
model="claude-sonnet-4@20250514",
max_tokens=2000,
temperature=0,
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "Write me a series of product announcement tweets in the 10 most commonly spoken languages. The product is a new state of the art pair of binoculars with built-in AI systems to identify the animals viewed through the binoculars. The tweets should be exciting, cutting edge, and push consumer interest."
}
]
}
]
)
print(message.content)
```
```typescript Vertex AI TypeScript
import { AnthropicVertex } from '@anthropic-ai/vertex-sdk';
// Reads from the `CLOUD_ML_REGION` & `ANTHROPIC_VERTEX_PROJECT_ID` environment variables.
// Additionally goes through the standard `google-auth-library` flow.
const client = new AnthropicVertex();
const msg = await client.messages.create({
model: "claude-sonnet-4@20250514",
max_tokens: 2000,
temperature: 0,
messages: [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Write me a series of product announcement tweets in the 10 most commonly spoken languages. The product is a new state of the art pair of binoculars with built-in AI systems to identify the animals viewed through the binoculars. The tweets should be exciting, cutting edge, and push consumer interest."
}
]
}
]
});
console.log(msg);
```
---
# Source: https://platform.claude.com/docs/en/agents-and-tools/tool-use/bash-tool.md
# Bash tool
---
The bash tool enables Claude to execute shell commands in a persistent bash session, allowing system operations, script execution, and command-line automation.
## Overview
The bash tool provides Claude with:
- Persistent bash session that maintains state
- Ability to run any shell command
- Access to environment variables and working directory
- Command chaining and scripting capabilities
## Model compatibility
| Model | Tool Version |
|-------|--------------|
| Claude 4 models and Sonnet 3.7 ([deprecated](/docs/en/about-claude/model-deprecations)) | `bash_20250124` |
Older tool versions are not guaranteed to be backwards-compatible with newer models. Always use the tool version that corresponds to your model version.
## Use cases
- **Development workflows**: Run build commands, tests, and development tools
- **System automation**: Execute scripts, manage files, automate tasks
- **Data processing**: Process files, run analysis scripts, manage datasets
- **Environment setup**: Install packages, configure environments
## Quick start
```python Python
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
tools=[
{
"type": "bash_20250124",
"name": "bash"
}
],
messages=[
{"role": "user", "content": "List all Python files in the current directory."}
]
)
```
```bash Shell
curl https://api.anthropic.com/v1/messages \
-H "content-type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-sonnet-4-5",
"max_tokens": 1024,
"tools": [
{
"type": "bash_20250124",
"name": "bash"
}
],
"messages": [
{
"role": "user",
"content": "List all Python files in the current directory."
}
]
}'
```
## How it works
The bash tool maintains a persistent session:
1. Claude determines what command to run
2. You execute the command in a bash shell
3. Return the output (stdout and stderr) to Claude
4. Session state persists between commands (environment variables, working directory)
## Parameters
| Parameter | Required | Description |
|-----------|----------|-------------|
| `command` | Yes* | The bash command to run |
| `restart` | No | Set to `true` to restart the bash session |
*Required unless using `restart`
```json
// Run a command
{
"command": "ls -la *.py"
}
// Restart the session
{
"restart": true
}
```
## Example: Multi-step automation
Claude can chain commands to complete complex tasks:
```python
# User request
"Install the requests library and create a simple Python script that fetches a joke from an API, then run it."
# Claude's tool uses:
# 1. Install package
{"command": "pip install requests"}
# 2. Create script
{"command": "cat > fetch_joke.py << 'EOF'\nimport requests\nresponse = requests.get('https://official-joke-api.appspot.com/random_joke')\njoke = response.json()\nprint(f\"Setup: {joke['setup']}\")\nprint(f\"Punchline: {joke['punchline']}\")\nEOF"}
# 3. Run script
{"command": "python fetch_joke.py"}
```
The session maintains state between commands, so files created in step 2 are available in step 3.
***
## Implement the bash tool
The bash tool is implemented as a schema-less tool. When using this tool, you don't need to provide an input schema as with other tools; the schema is built into Claude's model and can't be modified.
Create a persistent bash session that Claude can interact with:
```python
import subprocess
import threading
import queue
class BashSession:
def __init__(self):
self.process = subprocess.Popen(
['/bin/bash'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
bufsize=0
)
self.output_queue = queue.Queue()
self.error_queue = queue.Queue()
self._start_readers()
```
Create a function to execute commands and capture output:
```python
def execute_command(self, command):
# Send command to bash
self.process.stdin.write(command + '\n')
self.process.stdin.flush()
# Capture output with timeout
output = self._read_output(timeout=10)
return output
```
Extract and execute commands from Claude's responses:
```python
for content in response.content:
if content.type == "tool_use" and content.name == "bash":
if content.input.get("restart"):
bash_session.restart()
result = "Bash session restarted"
else:
command = content.input.get("command")
result = bash_session.execute_command(command)
# Return result to Claude
tool_result = {
"type": "tool_result",
"tool_use_id": content.id,
"content": result
}
```
Add validation and restrictions:
```python
def validate_command(command):
# Block dangerous commands
dangerous_patterns = ['rm -rf /', 'format', ':(){:|:&};:']
for pattern in dangerous_patterns:
if pattern in command:
return False, f"Command contains dangerous pattern: {pattern}"
# Add more validation as needed
return True, None
```
### Handle errors
When implementing the bash tool, handle various error scenarios:
If a command takes too long to execute:
```json
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_01A09q90qw90lq917835lq9",
"content": "Error: Command timed out after 30 seconds",
"is_error": true
}
]
}
```
If a command doesn't exist:
```json
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_01A09q90qw90lq917835lq9",
"content": "bash: nonexistentcommand: command not found",
"is_error": true
}
]
}
```
If there are permission issues:
```json
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_01A09q90qw90lq917835lq9",
"content": "bash: /root/sensitive-file: Permission denied",
"is_error": true
}
]
}
```
### Follow implementation best practices
Implement timeouts to prevent hanging commands:
```python
def execute_with_timeout(command, timeout=30):
try:
result = subprocess.run(
command,
shell=True,
capture_output=True,
text=True,
timeout=timeout
)
return result.stdout + result.stderr
except subprocess.TimeoutExpired:
return f"Command timed out after {timeout} seconds"
```
Keep the bash session persistent to maintain environment variables and working directory:
```python
# Commands run in the same session maintain state
commands = [
"cd /tmp",
"echo 'Hello' > test.txt",
"cat test.txt" # This works because we're still in /tmp
]
```
Truncate very large outputs to prevent token limit issues:
```python
def truncate_output(output, max_lines=100):
lines = output.split('\n')
if len(lines) > max_lines:
truncated = '\n'.join(lines[:max_lines])
return f"{truncated}\n\n... Output truncated ({len(lines)} total lines) ..."
return output
```
Keep an audit trail of executed commands:
```python
import logging
def log_command(command, output, user_id):
logging.info(f"User {user_id} executed: {command}")
logging.info(f"Output: {output[:200]}...") # Log first 200 chars
```
Remove sensitive information from command outputs:
```python
def sanitize_output(output):
# Remove potential secrets or credentials
import re
# Example: Remove AWS credentials
output = re.sub(r'aws_access_key_id\s*=\s*\S+', 'aws_access_key_id=***', output)
output = re.sub(r'aws_secret_access_key\s*=\s*\S+', 'aws_secret_access_key=***', output)
return output
```
## Security
The bash tool provides direct system access. Implement these essential safety measures:
- Running in isolated environments (Docker/VM)
- Implementing command filtering and allowlists
- Setting resource limits (CPU, memory, disk)
- Logging all executed commands
### Key recommendations
- Use `ulimit` to set resource constraints
- Filter dangerous commands (`sudo`, `rm -rf`, etc.)
- Run with minimal user permissions
- Monitor and log all command execution
## Pricing
The bash tool adds **245 input tokens** to your API calls.
Additional tokens are consumed by:
- Command outputs (stdout/stderr)
- Error messages
- Large file contents
See [tool use pricing](/docs/en/agents-and-tools/tool-use/overview#pricing) for complete pricing details.
## Common patterns
### Development workflows
- Running tests: `pytest && coverage report`
- Building projects: `npm install && npm run build`
- Git operations: `git status && git add . && git commit -m "message"`
### File operations
- Processing data: `wc -l *.csv && ls -lh *.csv`
- Searching files: `find . -name "*.py" | xargs grep "pattern"`
- Creating backups: `tar -czf backup.tar.gz ./data`
### System tasks
- Checking resources: `df -h && free -m`
- Process management: `ps aux | grep python`
- Environment setup: `export PATH=$PATH:/new/path && echo $PATH`
## Limitations
- **No interactive commands**: Cannot handle `vim`, `less`, or password prompts
- **No GUI applications**: Command-line only
- **Session scope**: Persists within conversation, lost between API calls
- **Output limits**: Large outputs may be truncated
- **No streaming**: Results returned after completion
## Combining with other tools
The bash tool is most powerful when combined with the [text editor](/docs/en/agents-and-tools/tool-use/text-editor-tool) and other tools.
## Next steps
Learn about tool use with Claude
View and edit text files with Claude
---
# Source: https://platform.claude.com/docs/en/build-with-claude/batch-processing.md
# Batch processing
---
Batch processing is a powerful approach for handling large volumes of requests efficiently. Instead of processing requests one at a time with immediate responses, batch processing allows you to submit multiple requests together for asynchronous processing. This pattern is particularly useful when:
- You need to process large volumes of data
- Immediate responses are not required
- You want to optimize for cost efficiency
- You're running large-scale evaluations or analyses
The Message Batches API is our first implementation of this pattern.
---
# Message Batches API
The Message Batches API is a powerful, cost-effective way to asynchronously process large volumes of [Messages](/docs/en/api/messages) requests. This approach is well-suited to tasks that do not require immediate responses, with most batches finishing in less than 1 hour while reducing costs by 50% and increasing throughput.
You can [explore the API reference directly](/docs/en/api/creating-message-batches), in addition to this guide.
## How the Message Batches API works
When you send a request to the Message Batches API:
1. The system creates a new Message Batch with the provided Messages requests.
2. The batch is then processed asynchronously, with each request handled independently.
3. You can poll for the status of the batch and retrieve results when processing has ended for all requests.
This is especially useful for bulk operations that don't require immediate results, such as:
- Large-scale evaluations: Process thousands of test cases efficiently.
- Content moderation: Analyze large volumes of user-generated content asynchronously.
- Data analysis: Generate insights or summaries for large datasets.
- Bulk content generation: Create large amounts of text for various purposes (e.g., product descriptions, article summaries).
### Batch limitations
- A Message Batch is limited to either 100,000 Message requests or 256 MB in size, whichever is reached first.
- We process each batch as fast as possible, with most batches completing within 1 hour. You will be able to access batch results when all messages have completed or after 24 hours, whichever comes first. Batches will expire if processing does not complete within 24 hours.
- Batch results are available for 29 days after creation. After that, you may still view the Batch, but its results will no longer be available for download.
- Batches are scoped to a [Workspace](/settings/workspaces). You may view all batches—and their results—that were created within the Workspace that your API key belongs to.
- Rate limits apply to both Batches API HTTP requests and the number of requests within a batch waiting to be processed. See [Message Batches API rate limits](/docs/en/api/rate-limits#message-batches-api). Additionally, we may slow down processing based on current demand and your request volume. In that case, you may see more requests expiring after 24 hours.
- Due to high throughput and concurrent processing, batches may go slightly over your Workspace's configured [spend limit](/settings/limits).
### Supported models
All [active models](/docs/en/about-claude/models/overview) support the Message Batches API.
### What can be batched
Any request that you can make to the Messages API can be included in a batch. This includes:
- Vision
- Tool use
- System messages
- Multi-turn conversations
- Any beta features
Since each request in the batch is processed independently, you can mix different types of requests within a single batch.
Since batches can take longer than 5 minutes to process, consider using the [1-hour cache duration](/docs/en/build-with-claude/prompt-caching#1-hour-cache-duration) with prompt caching for better cache hit rates when processing batches with shared context.
---
## Pricing
The Batches API offers significant cost savings. All usage is charged at 50% of the standard API prices.
| Model | Batch input | Batch output |
|-------------------|------------------|-----------------|
| Claude Opus 4.5 | $2.50 / MTok | $12.50 / MTok |
| Claude Opus 4.1 | $7.50 / MTok | $37.50 / MTok |
| Claude Opus 4 | $7.50 / MTok | $37.50 / MTok |
| Claude Sonnet 4.5 | $1.50 / MTok | $7.50 / MTok |
| Claude Sonnet 4 | $1.50 / MTok | $7.50 / MTok |
| Claude Sonnet 3.7 ([deprecated](/docs/en/about-claude/model-deprecations)) | $1.50 / MTok | $7.50 / MTok |
| Claude Haiku 4.5 | $0.50 / MTok | $2.50 / MTok |
| Claude Haiku 3.5 | $0.40 / MTok | $2 / MTok |
| Claude Opus 3 ([deprecated](/docs/en/about-claude/model-deprecations)) | $7.50 / MTok | $37.50 / MTok |
| Claude Haiku 3 | $0.125 / MTok | $0.625 / MTok |
---
## How to use the Message Batches API
### Prepare and create your batch
A Message Batch is composed of a list of requests to create a Message. The shape of an individual request is comprised of:
- A unique `custom_id` for identifying the Messages request
- A `params` object with the standard [Messages API](/docs/en/api/messages) parameters
You can [create a batch](/docs/en/api/creating-message-batches) by passing this list into the `requests` parameter:
```bash Shell
curl https://api.anthropic.com/v1/messages/batches \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "content-type: application/json" \
--data \
'{
"requests": [
{
"custom_id": "my-first-request",
"params": {
"model": "claude-sonnet-4-5",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "Hello, world"}
]
}
},
{
"custom_id": "my-second-request",
"params": {
"model": "claude-sonnet-4-5",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "Hi again, friend"}
]
}
}
]
}'
```
```python Python
import anthropic
from anthropic.types.message_create_params import MessageCreateParamsNonStreaming
from anthropic.types.messages.batch_create_params import Request
client = anthropic.Anthropic()
message_batch = client.messages.batches.create(
requests=[
Request(
custom_id="my-first-request",
params=MessageCreateParamsNonStreaming(
model="claude-sonnet-4-5",
max_tokens=1024,
messages=[{
"role": "user",
"content": "Hello, world",
}]
)
),
Request(
custom_id="my-second-request",
params=MessageCreateParamsNonStreaming(
model="claude-sonnet-4-5",
max_tokens=1024,
messages=[{
"role": "user",
"content": "Hi again, friend",
}]
)
)
]
)
print(message_batch)
```
```typescript TypeScript
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic();
const messageBatch = await anthropic.messages.batches.create({
requests: [{
custom_id: "my-first-request",
params: {
model: "claude-sonnet-4-5",
max_tokens: 1024,
messages: [
{"role": "user", "content": "Hello, world"}
]
}
}, {
custom_id: "my-second-request",
params: {
model: "claude-sonnet-4-5",
max_tokens: 1024,
messages: [
{"role": "user", "content": "Hi again, friend"}
]
}
}]
});
console.log(messageBatch)
```
```java Java
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.models.messages.Model;
import com.anthropic.models.messages.batches.*;
public class BatchExample {
public static void main(String[] args) {
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
BatchCreateParams params = BatchCreateParams.builder()
.addRequest(BatchCreateParams.Request.builder()
.customId("my-first-request")
.params(BatchCreateParams.Request.Params.builder()
.model(Model.CLAUDE_OPUS_4_0)
.maxTokens(1024)
.addUserMessage("Hello, world")
.build())
.build())
.addRequest(BatchCreateParams.Request.builder()
.customId("my-second-request")
.params(BatchCreateParams.Request.Params.builder()
.model(Model.CLAUDE_OPUS_4_0)
.maxTokens(1024)
.addUserMessage("Hi again, friend")
.build())
.build())
.build();
MessageBatch messageBatch = client.messages().batches().create(params);
System.out.println(messageBatch);
}
}
```
In this example, two separate requests are batched together for asynchronous processing. Each request has a unique `custom_id` and contains the standard parameters you'd use for a Messages API call.
**Test your batch requests with the Messages API**
Validation of the `params` object for each message request is performed asynchronously, and validation errors are returned when processing of the entire batch has ended. You can ensure that you are building your input correctly by verifying your request shape with the [Messages API](/docs/en/api/messages) first.
When a batch is first created, the response will have a processing status of `in_progress`.
```json JSON
{
"id": "msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d",
"type": "message_batch",
"processing_status": "in_progress",
"request_counts": {
"processing": 2,
"succeeded": 0,
"errored": 0,
"canceled": 0,
"expired": 0
},
"ended_at": null,
"created_at": "2024-09-24T18:37:24.100435Z",
"expires_at": "2024-09-25T18:37:24.100435Z",
"cancel_initiated_at": null,
"results_url": null
}
```
### Tracking your batch
The Message Batch's `processing_status` field indicates the stage of processing the batch is in. It starts as `in_progress`, then updates to `ended` once all the requests in the batch have finished processing, and results are ready. You can monitor the state of your batch by visiting the [Console](/settings/workspaces/default/batches), or using the [retrieval endpoint](/docs/en/api/retrieving-message-batches).
#### Polling for Message Batch completion
To poll a Message Batch, you'll need its `id`, which is provided in the response when creating a batch or by listing batches. You can implement a polling loop that checks the batch status periodically until processing has ended:
```python Python
import anthropic
import time
client = anthropic.Anthropic()
message_batch = None
while True:
message_batch = client.messages.batches.retrieve(
MESSAGE_BATCH_ID
)
if message_batch.processing_status == "ended":
break
print(f"Batch {MESSAGE_BATCH_ID} is still processing...")
time.sleep(60)
print(message_batch)
```
```typescript TypeScript
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic();
let messageBatch;
while (true) {
messageBatch = await anthropic.messages.batches.retrieve(
MESSAGE_BATCH_ID
);
if (messageBatch.processing_status === 'ended') {
break;
}
console.log(`Batch ${messageBatch} is still processing... waiting`);
await new Promise(resolve => setTimeout(resolve, 60_000));
}
console.log(messageBatch);
```
```bash Shell
#!/bin/sh
until [[ $(curl -s "https://api.anthropic.com/v1/messages/batches/$MESSAGE_BATCH_ID" \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
| grep -o '"processing_status":[[:space:]]*"[^"]*"' \
| cut -d'"' -f4) == "ended" ]]; do
echo "Batch $MESSAGE_BATCH_ID is still processing..."
sleep 60
done
echo "Batch $MESSAGE_BATCH_ID has finished processing"
```
### Listing all Message Batches
You can list all Message Batches in your Workspace using the [list endpoint](/docs/en/api/listing-message-batches). The API supports pagination, automatically fetching additional pages as needed:
```python Python
import anthropic
client = anthropic.Anthropic()
# Automatically fetches more pages as needed.
for message_batch in client.messages.batches.list(
limit=20
):
print(message_batch)
```
```typescript TypeScript
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic();
// Automatically fetches more pages as needed.
for await (const messageBatch of anthropic.messages.batches.list({
limit: 20
})) {
console.log(messageBatch);
}
```
```bash Shell
#!/bin/sh
if ! command -v jq &> /dev/null; then
echo "Error: This script requires jq. Please install it first."
exit 1
fi
BASE_URL="https://api.anthropic.com/v1/messages/batches"
has_more=true
after_id=""
while [ "$has_more" = true ]; do
# Construct URL with after_id if it exists
if [ -n "$after_id" ]; then
url="${BASE_URL}?limit=20&after_id=${after_id}"
else
url="$BASE_URL?limit=20"
fi
response=$(curl -s "$url" \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01")
# Extract values using jq
has_more=$(echo "$response" | jq -r '.has_more')
after_id=$(echo "$response" | jq -r '.last_id')
# Process and print each entry in the data array
echo "$response" | jq -c '.data[]' | while read -r entry; do
echo "$entry" | jq '.'
done
done
```
```java Java
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.models.messages.batches.*;
public class BatchListExample {
public static void main(String[] args) {
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
// Automatically fetches more pages as needed
for (MessageBatch messageBatch : client.messages().batches().list(
BatchListParams.builder()
.limit(20)
.build()
)) {
System.out.println(messageBatch);
}
}
}
```
### Retrieving batch results
Once batch processing has ended, each Messages request in the batch will have a result. There are 4 result types:
| Result Type | Description |
|-------------|-------------|
| `succeeded` | Request was successful. Includes the message result. |
| `errored` | Request encountered an error and a message was not created. Possible errors include invalid requests and internal server errors. You will not be billed for these requests. |
| `canceled` | User canceled the batch before this request could be sent to the model. You will not be billed for these requests. |
| `expired` | Batch reached its 24 hour expiration before this request could be sent to the model. You will not be billed for these requests. |
You will see an overview of your results with the batch's `request_counts`, which shows how many requests reached each of these four states.
Results of the batch are available for download at the `results_url` property on the Message Batch, and if the organization permission allows, in the Console. Because of the potentially large size of the results, it's recommended to [stream results](/docs/en/api/retrieving-message-batch-results) back rather than download them all at once.
```bash Shell
#!/bin/sh
curl "https://api.anthropic.com/v1/messages/batches/msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_API_KEY" \
| grep -o '"results_url":[[:space:]]*"[^"]*"' \
| cut -d'"' -f4 \
| while read -r url; do
curl -s "$url" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_API_KEY" \
| sed 's/}{/}\n{/g' \
| while IFS= read -r line
do
result_type=$(echo "$line" | sed -n 's/.*"result":[[:space:]]*{[[:space:]]*"type":[[:space:]]*"\([^"]*\)".*/\1/p')
custom_id=$(echo "$line" | sed -n 's/.*"custom_id":[[:space:]]*"\([^"]*\)".*/\1/p')
error_type=$(echo "$line" | sed -n 's/.*"error":[[:space:]]*{[[:space:]]*"type":[[:space:]]*"\([^"]*\)".*/\1/p')
case "$result_type" in
"succeeded")
echo "Success! $custom_id"
;;
"errored")
if [ "$error_type" = "invalid_request" ]; then
# Request body must be fixed before re-sending request
echo "Validation error: $custom_id"
else
# Request can be retried directly
echo "Server error: $custom_id"
fi
;;
"expired")
echo "Expired: $line"
;;
esac
done
done
```
```python Python
import anthropic
client = anthropic.Anthropic()
# Stream results file in memory-efficient chunks, processing one at a time
for result in client.messages.batches.results(
"msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d",
):
match result.result.type:
case "succeeded":
print(f"Success! {result.custom_id}")
case "errored":
if result.result.error.type == "invalid_request":
# Request body must be fixed before re-sending request
print(f"Validation error {result.custom_id}")
else:
# Request can be retried directly
print(f"Server error {result.custom_id}")
case "expired":
print(f"Request expired {result.custom_id}")
```
```typescript TypeScript
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic();
// Stream results file in memory-efficient chunks, processing one at a time
for await (const result of await anthropic.messages.batches.results(
"msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d"
)) {
switch (result.result.type) {
case 'succeeded':
console.log(`Success! ${result.custom_id}`);
break;
case 'errored':
if (result.result.error.type == "invalid_request") {
// Request body must be fixed before re-sending request
console.log(`Validation error: ${result.custom_id}`);
} else {
// Request can be retried directly
console.log(`Server error: ${result.custom_id}`);
}
break;
case 'expired':
console.log(`Request expired: ${result.custom_id}`);
break;
}
}
```
```java Java
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.core.http.StreamResponse;
import com.anthropic.models.messages.batches.MessageBatchIndividualResponse;
import com.anthropic.models.messages.batches.BatchResultsParams;
public class BatchResultsExample {
public static void main(String[] args) {
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
// Stream results file in memory-efficient chunks, processing one at a time
try (StreamResponse streamResponse = client.messages()
.batches()
.resultsStreaming(
BatchResultsParams.builder()
.messageBatchId("msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d")
.build())) {
streamResponse.stream().forEach(result -> {
if (result.result().isSucceeded()) {
System.out.println("Success! " + result.customId());
} else if (result.result().isErrored()) {
if (result.result().asErrored().error().error().isInvalidRequestError()) {
// Request body must be fixed before re-sending request
System.out.println("Validation error: " + result.customId());
} else {
// Request can be retried directly
System.out.println("Server error: " + result.customId());
}
} else if (result.result().isExpired()) {
System.out.println("Request expired: " + result.customId());
}
});
}
}
}
```
The results will be in `.jsonl` format, where each line is a valid JSON object representing the result of a single request in the Message Batch. For each streamed result, you can do something different depending on its `custom_id` and result type. Here is an example set of results:
```json .jsonl file
{"custom_id":"my-second-request","result":{"type":"succeeded","message":{"id":"msg_014VwiXbi91y3JMjcpyGBHX5","type":"message","role":"assistant","model":"claude-sonnet-4-5-20250929","content":[{"type":"text","text":"Hello again! It's nice to see you. How can I assist you today? Is there anything specific you'd like to chat about or any questions you have?"}],"stop_reason":"end_turn","stop_sequence":null,"usage":{"input_tokens":11,"output_tokens":36}}}}
{"custom_id":"my-first-request","result":{"type":"succeeded","message":{"id":"msg_01FqfsLoHwgeFbguDgpz48m7","type":"message","role":"assistant","model":"claude-sonnet-4-5-20250929","content":[{"type":"text","text":"Hello! How can I assist you today? Feel free to ask me any questions or let me know if there's anything you'd like to chat about."}],"stop_reason":"end_turn","stop_sequence":null,"usage":{"input_tokens":10,"output_tokens":34}}}}
```
If your result has an error, its `result.error` will be set to our standard [error shape](/docs/en/api/errors#error-shapes).
**Batch results may not match input order**
Batch results can be returned in any order, and may not match the ordering of requests when the batch was created. In the above example, the result for the second batch request is returned before the first. To correctly match results with their corresponding requests, always use the `custom_id` field.
### Canceling a Message Batch
You can cancel a Message Batch that is currently processing using the [cancel endpoint](/docs/en/api/canceling-message-batches). Immediately after cancellation, a batch's `processing_status` will be `canceling`. You can use the same polling technique described above to wait until cancellation is finalized. Canceled batches end up with a status of `ended` and may contain partial results for requests that were processed before cancellation.
```python Python
import anthropic
client = anthropic.Anthropic()
message_batch = client.messages.batches.cancel(
MESSAGE_BATCH_ID,
)
print(message_batch)
```
```typescript TypeScript
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic();
const messageBatch = await anthropic.messages.batches.cancel(
MESSAGE_BATCH_ID
);
console.log(messageBatch);
```
```bash Shell
#!/bin/sh
curl --request POST https://api.anthropic.com/v1/messages/batches/$MESSAGE_BATCH_ID/cancel \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01"
```
```java Java
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.models.messages.batches.*;
public class BatchCancelExample {
public static void main(String[] args) {
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
MessageBatch messageBatch = client.messages().batches().cancel(
BatchCancelParams.builder()
.messageBatchId(MESSAGE_BATCH_ID)
.build()
);
System.out.println(messageBatch);
}
}
```
The response will show the batch in a `canceling` state:
```json JSON
{
"id": "msgbatch_013Zva2CMHLNnXjNJJKqJ2EF",
"type": "message_batch",
"processing_status": "canceling",
"request_counts": {
"processing": 2,
"succeeded": 0,
"errored": 0,
"canceled": 0,
"expired": 0
},
"ended_at": null,
"created_at": "2024-09-24T18:37:24.100435Z",
"expires_at": "2024-09-25T18:37:24.100435Z",
"cancel_initiated_at": "2024-09-24T18:39:03.114875Z",
"results_url": null
}
```
### Using prompt caching with Message Batches
The Message Batches API supports prompt caching, allowing you to potentially reduce costs and processing time for batch requests. The pricing discounts from prompt caching and Message Batches can stack, providing even greater cost savings when both features are used together. However, since batch requests are processed asynchronously and concurrently, cache hits are provided on a best-effort basis. Users typically experience cache hit rates ranging from 30% to 98%, depending on their traffic patterns.
To maximize the likelihood of cache hits in your batch requests:
1. Include identical `cache_control` blocks in every Message request within your batch
2. Maintain a steady stream of requests to prevent cache entries from expiring after their 5-minute lifetime
3. Structure your requests to share as much cached content as possible
Example of implementing prompt caching in a batch:
```bash Shell
curl https://api.anthropic.com/v1/messages/batches \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "content-type: application/json" \
--data \
'{
"requests": [
{
"custom_id": "my-first-request",
"params": {
"model": "claude-sonnet-4-5",
"max_tokens": 1024,
"system": [
{
"type": "text",
"text": "You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.\n"
},
{
"type": "text",
"text": "",
"cache_control": {"type": "ephemeral"}
}
],
"messages": [
{"role": "user", "content": "Analyze the major themes in Pride and Prejudice."}
]
}
},
{
"custom_id": "my-second-request",
"params": {
"model": "claude-sonnet-4-5",
"max_tokens": 1024,
"system": [
{
"type": "text",
"text": "You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.\n"
},
{
"type": "text",
"text": "",
"cache_control": {"type": "ephemeral"}
}
],
"messages": [
{"role": "user", "content": "Write a summary of Pride and Prejudice."}
]
}
}
]
}'
```
```python Python
import anthropic
from anthropic.types.message_create_params import MessageCreateParamsNonStreaming
from anthropic.types.messages.batch_create_params import Request
client = anthropic.Anthropic()
message_batch = client.messages.batches.create(
requests=[
Request(
custom_id="my-first-request",
params=MessageCreateParamsNonStreaming(
model="claude-sonnet-4-5",
max_tokens=1024,
system=[
{
"type": "text",
"text": "You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.\n"
},
{
"type": "text",
"text": "",
"cache_control": {"type": "ephemeral"}
}
],
messages=[{
"role": "user",
"content": "Analyze the major themes in Pride and Prejudice."
}]
)
),
Request(
custom_id="my-second-request",
params=MessageCreateParamsNonStreaming(
model="claude-sonnet-4-5",
max_tokens=1024,
system=[
{
"type": "text",
"text": "You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.\n"
},
{
"type": "text",
"text": "",
"cache_control": {"type": "ephemeral"}
}
],
messages=[{
"role": "user",
"content": "Write a summary of Pride and Prejudice."
}]
)
)
]
)
```
```typescript TypeScript
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic();
const messageBatch = await anthropic.messages.batches.create({
requests: [{
custom_id: "my-first-request",
params: {
model: "claude-sonnet-4-5",
max_tokens: 1024,
system: [
{
type: "text",
text: "You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.\n"
},
{
type: "text",
text: "",
cache_control: {type: "ephemeral"}
}
],
messages: [
{"role": "user", "content": "Analyze the major themes in Pride and Prejudice."}
]
}
}, {
custom_id: "my-second-request",
params: {
model: "claude-sonnet-4-5",
max_tokens: 1024,
system: [
{
type: "text",
text: "You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.\n"
},
{
type: "text",
text: "",
cache_control: {type: "ephemeral"}
}
],
messages: [
{"role": "user", "content": "Write a summary of Pride and Prejudice."}
]
}
}]
});
```
```java Java
import java.util.List;
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.models.messages.CacheControlEphemeral;
import com.anthropic.models.messages.Model;
import com.anthropic.models.messages.TextBlockParam;
import com.anthropic.models.messages.batches.*;
public class BatchExample {
public static void main(String[] args) {
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
BatchCreateParams createParams = BatchCreateParams.builder()
.addRequest(BatchCreateParams.Request.builder()
.customId("my-first-request")
.params(BatchCreateParams.Request.Params.builder()
.model(Model.CLAUDE_OPUS_4_0)
.maxTokens(1024)
.systemOfTextBlockParams(List.of(
TextBlockParam.builder()
.text("You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.\n")
.build(),
TextBlockParam.builder()
.text("")
.cacheControl(CacheControlEphemeral.builder().build())
.build()
))
.addUserMessage("Analyze the major themes in Pride and Prejudice.")
.build())
.build())
.addRequest(BatchCreateParams.Request.builder()
.customId("my-second-request")
.params(BatchCreateParams.Request.Params.builder()
.model(Model.CLAUDE_OPUS_4_0)
.maxTokens(1024)
.systemOfTextBlockParams(List.of(
TextBlockParam.builder()
.text("You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.\n")
.build(),
TextBlockParam.builder()
.text("")
.cacheControl(CacheControlEphemeral.builder().build())
.build()
))
.addUserMessage("Write a summary of Pride and Prejudice.")
.build())
.build())
.build();
MessageBatch messageBatch = client.messages().batches().create(createParams);
}
}
```
In this example, both requests in the batch include identical system messages and the full text of Pride and Prejudice marked with `cache_control` to increase the likelihood of cache hits.
### Best practices for effective batching
To get the most out of the Batches API:
- Monitor batch processing status regularly and implement appropriate retry logic for failed requests.
- Use meaningful `custom_id` values to easily match results with requests, since order is not guaranteed.
- Consider breaking very large datasets into multiple batches for better manageability.
- Dry run a single request shape with the Messages API to avoid validation errors.
### Troubleshooting common issues
If experiencing unexpected behavior:
- Verify that the total batch request size doesn't exceed 256 MB. If the request size is too large, you may get a 413 `request_too_large` error.
- Check that you're using [supported models](#supported-models) for all requests in the batch.
- Ensure each request in the batch has a unique `custom_id`.
- Ensure that it has been less than 29 days since batch `created_at` (not processing `ended_at`) time. If over 29 days have passed, results will no longer be viewable.
- Confirm that the batch has not been canceled.
Note that the failure of one request in a batch does not affect the processing of other requests.
---
## Batch storage and privacy
- **Workspace isolation**: Batches are isolated within the Workspace they are created in. They can only be accessed by API keys associated with that Workspace, or users with permission to view Workspace batches in the Console.
- **Result availability**: Batch results are available for 29 days after the batch is created, allowing ample time for retrieval and processing.
---
## FAQ
Batches may take up to 24 hours for processing, but many will finish sooner. Actual processing time depends on the size of the batch, current demand, and your request volume. It is possible for a batch to expire and not complete within 24 hours.
See [above](#supported-models) for the list of supported models.
Yes, the Message Batches API supports all features available in the Messages API, including beta features. However, streaming is not supported for batch requests.
The Message Batches API offers a 50% discount on all usage compared to standard API prices. This applies to input tokens, output tokens, and any special tokens. For more on pricing, visit our [pricing page](https://claude.com/pricing#anthropic-api).
No, once a batch has been submitted, it cannot be modified. If you need to make changes, you should cancel the current batch and submit a new one. Note that cancellation may not take immediate effect.
The Message Batches API has HTTP requests-based rate limits in addition to limits on the number of requests in need of processing. See [Message Batches API rate limits](/docs/en/api/rate-limits#message-batches-api). Usage of the Batches API does not affect rate limits in the Messages API.
When you retrieve the results, each request will have a `result` field indicating whether it `succeeded`, `errored`, was `canceled`, or `expired`. For `errored` results, additional error information will be provided. View the error response object in the [API reference](/docs/en/api/creating-message-batches).
The Message Batches API is designed with strong privacy and data separation measures:
1. Batches and their results are isolated within the Workspace in which they were created. This means they can only be accessed by API keys from that same Workspace.
2. Each request within a batch is processed independently, with no data leakage between requests.
3. Results are only available for a limited time (29 days), and follow our [data retention policy](https://support.claude.com/en/articles/7996866-how-long-do-you-store-personal-data).
4. Downloading batch results in the Console can be disabled on the organization-level or on a per-workspace basis.
Yes, it is possible to use prompt caching with Message Batches API. However, because asynchronous batch requests can be processed concurrently and in any order, cache hits are provided on a best-effort basis.
---
# Source: https://platform.claude.com/docs/en/api/typescript/messages/batches.md
# Source: https://platform.claude.com/docs/en/api/ruby/messages/batches.md
# Source: https://platform.claude.com/docs/en/api/python/messages/batches.md
# Source: https://platform.claude.com/docs/en/api/kotlin/messages/batches.md
# Source: https://platform.claude.com/docs/en/api/java/messages/batches.md
# Source: https://platform.claude.com/docs/en/api/go/messages/batches.md
# Source: https://platform.claude.com/docs/en/api/typescript/beta/messages/batches.md
# Source: https://platform.claude.com/docs/en/api/ruby/beta/messages/batches.md
# Source: https://platform.claude.com/docs/en/api/python/beta/messages/batches.md
# Source: https://platform.claude.com/docs/en/api/kotlin/beta/messages/batches.md
# Source: https://platform.claude.com/docs/en/api/java/beta/messages/batches.md
# Source: https://platform.claude.com/docs/en/api/go/beta/messages/batches.md
# Source: https://platform.claude.com/docs/en/api/beta/messages/batches.md
# Source: https://platform.claude.com/docs/en/api/messages/batches.md
# Source: https://platform.claude.com/docs/en/api/typescript/messages/batches.md
# Batches
## Create
`client.messages.batches.create(BatchCreateParamsbody, RequestOptionsoptions?): MessageBatch`
**post** `/v1/messages/batches`
Send a batch of Message creation requests.
The Message Batches API can be used to process multiple Messages API requests at once. Once a Message Batch is created, it begins processing immediately. Batches can take up to 24 hours to complete.
Learn more about the Message Batches API in our [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
### Parameters
- `body: BatchCreateParams`
- `requests: Array`
List of requests for prompt completion. Each is an individual request to create a Message.
- `custom_id: string`
Developer-provided ID created for each request in a Message Batch. Useful for matching results to requests, as results may be given out of request order.
Must be unique for each request within the Message Batch.
- `params: Params`
Messages API creation parameters for the individual request.
See the [Messages API reference](https://docs.claude.com/en/api/messages) for full documentation on available parameters.
- `max_tokens: number`
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.
Different models have different maximum values for this parameter. See [models](https://docs.claude.com/en/docs/models-overview) for details.
- `messages: Array`
Input messages.
Our models are trained to operate on alternating `user` and `assistant` conversational turns. When creating a new `Message`, you specify the prior conversational turns with the `messages` parameter, and the model then generates the next `Message` in the conversation. Consecutive `user` or `assistant` turns in your request will be combined into a single turn.
Each input message must be an object with a `role` and `content`. You can specify a single `user`-role message, or you can include multiple `user` and `assistant` messages.
If the final message uses the `assistant` role, the response content will continue immediately from the content in that message. This can be used to constrain part of the model's response.
Example with a single `user` message:
```json
[{"role": "user", "content": "Hello, Claude"}]
```
Example with multiple conversational turns:
```json
[
{"role": "user", "content": "Hello there."},
{"role": "assistant", "content": "Hi, I'm Claude. How can I help you?"},
{"role": "user", "content": "Can you explain LLMs in plain English?"},
]
```
Example with a partially-filled response from Claude:
```json
[
{"role": "user", "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"},
{"role": "assistant", "content": "The best answer is ("},
]
```
Each input message `content` may be either a single `string` or an array of content blocks, where each block has a specific `type`. Using a `string` for `content` is shorthand for an array of one content block of type `"text"`. The following input messages are equivalent:
```json
{"role": "user", "content": "Hello, Claude"}
```
```json
{"role": "user", "content": [{"type": "text", "text": "Hello, Claude"}]}
```
See [input examples](https://docs.claude.com/en/api/messages-examples).
Note that if you want to include a [system prompt](https://docs.claude.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 100,000 messages in a single request.
- `content: string | Array`
- `string`
- `Array`
- `TextBlockParam`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: CacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `CitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `CitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `CitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `CitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `CitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `ImageBlockParam`
- `source: Base64ImageSource | URLImageSource`
- `Base64ImageSource`
- `data: string`
- `media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"`
- `"image/jpeg"`
- `"image/png"`
- `"image/gif"`
- `"image/webp"`
- `type: "base64"`
- `"base64"`
- `URLImageSource`
- `type: "url"`
- `"url"`
- `url: string`
- `type: "image"`
- `"image"`
- `cache_control?: CacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `DocumentBlockParam`
- `source: Base64PDFSource | PlainTextSource | ContentBlockSource | URLPDFSource`
- `Base64PDFSource`
- `data: string`
- `media_type: "application/pdf"`
- `"application/pdf"`
- `type: "base64"`
- `"base64"`
- `PlainTextSource`
- `data: string`
- `media_type: "text/plain"`
- `"text/plain"`
- `type: "text"`
- `"text"`
- `ContentBlockSource`
- `content: string | Array`
- `string`
- `Array`
- `TextBlockParam`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: CacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `CitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `CitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `CitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `CitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `CitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `ImageBlockParam`
- `source: Base64ImageSource | URLImageSource`
- `Base64ImageSource`
- `data: string`
- `media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"`
- `"image/jpeg"`
- `"image/png"`
- `"image/gif"`
- `"image/webp"`
- `type: "base64"`
- `"base64"`
- `URLImageSource`
- `type: "url"`
- `"url"`
- `url: string`
- `type: "image"`
- `"image"`
- `cache_control?: CacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `type: "content"`
- `"content"`
- `URLPDFSource`
- `type: "url"`
- `"url"`
- `url: string`
- `type: "document"`
- `"document"`
- `cache_control?: CacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: CitationsConfigParam | null`
- `enabled?: boolean`
- `context?: string | null`
- `title?: string | null`
- `SearchResultBlockParam`
- `content: Array`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: CacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `CitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `CitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `CitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `CitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `CitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `source: string`
- `title: string`
- `type: "search_result"`
- `"search_result"`
- `cache_control?: CacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: CitationsConfigParam`
- `enabled?: boolean`
- `ThinkingBlockParam`
- `signature: string`
- `thinking: string`
- `type: "thinking"`
- `"thinking"`
- `RedactedThinkingBlockParam`
- `data: string`
- `type: "redacted_thinking"`
- `"redacted_thinking"`
- `ToolUseBlockParam`
- `id: string`
- `input: Record`
- `name: string`
- `type: "tool_use"`
- `"tool_use"`
- `cache_control?: CacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `ToolResultBlockParam`
- `tool_use_id: string`
- `type: "tool_result"`
- `"tool_result"`
- `cache_control?: CacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `content?: string | Array`
- `string`
- `Array`
- `TextBlockParam`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: CacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `CitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `CitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `CitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `CitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `CitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `ImageBlockParam`
- `source: Base64ImageSource | URLImageSource`
- `Base64ImageSource`
- `data: string`
- `media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"`
- `"image/jpeg"`
- `"image/png"`
- `"image/gif"`
- `"image/webp"`
- `type: "base64"`
- `"base64"`
- `URLImageSource`
- `type: "url"`
- `"url"`
- `url: string`
- `type: "image"`
- `"image"`
- `cache_control?: CacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `SearchResultBlockParam`
- `content: Array`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: CacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `CitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `CitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `CitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `CitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `CitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `source: string`
- `title: string`
- `type: "search_result"`
- `"search_result"`
- `cache_control?: CacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: CitationsConfigParam`
- `enabled?: boolean`
- `DocumentBlockParam`
- `source: Base64PDFSource | PlainTextSource | ContentBlockSource | URLPDFSource`
- `Base64PDFSource`
- `data: string`
- `media_type: "application/pdf"`
- `"application/pdf"`
- `type: "base64"`
- `"base64"`
- `PlainTextSource`
- `data: string`
- `media_type: "text/plain"`
- `"text/plain"`
- `type: "text"`
- `"text"`
- `ContentBlockSource`
- `content: string | Array`
- `string`
- `Array`
- `TextBlockParam`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: CacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `CitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `CitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `CitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `CitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `CitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `ImageBlockParam`
- `source: Base64ImageSource | URLImageSource`
- `Base64ImageSource`
- `data: string`
- `media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"`
- `"image/jpeg"`
- `"image/png"`
- `"image/gif"`
- `"image/webp"`
- `type: "base64"`
- `"base64"`
- `URLImageSource`
- `type: "url"`
- `"url"`
- `url: string`
- `type: "image"`
- `"image"`
- `cache_control?: CacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `type: "content"`
- `"content"`
- `URLPDFSource`
- `type: "url"`
- `"url"`
- `url: string`
- `type: "document"`
- `"document"`
- `cache_control?: CacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: CitationsConfigParam | null`
- `enabled?: boolean`
- `context?: string | null`
- `title?: string | null`
- `is_error?: boolean`
- `ServerToolUseBlockParam`
- `id: string`
- `input: Record`
- `name: "web_search"`
- `"web_search"`
- `type: "server_tool_use"`
- `"server_tool_use"`
- `cache_control?: CacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `WebSearchToolResultBlockParam`
- `content: WebSearchToolResultBlockParamContent`
- `Array`
- `encrypted_content: string`
- `title: string`
- `type: "web_search_result"`
- `"web_search_result"`
- `url: string`
- `page_age?: string | null`
- `WebSearchToolRequestError`
- `error_code: "invalid_tool_input" | "unavailable" | "max_uses_exceeded" | 3 more`
- `"invalid_tool_input"`
- `"unavailable"`
- `"max_uses_exceeded"`
- `"too_many_requests"`
- `"query_too_long"`
- `"request_too_large"`
- `type: "web_search_tool_result_error"`
- `"web_search_tool_result_error"`
- `tool_use_id: string`
- `type: "web_search_tool_result"`
- `"web_search_tool_result"`
- `cache_control?: CacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `role: "user" | "assistant"`
- `"user"`
- `"assistant"`
- `model: Model`
The model that will complete your prompt.
See [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options.
- `"claude-opus-4-5-20251101" | "claude-opus-4-5" | "claude-3-7-sonnet-latest" | 17 more`
- `"claude-opus-4-5-20251101"`
Premium model combining maximum intelligence with practical performance
- `"claude-opus-4-5"`
Premium model combining maximum intelligence with practical performance
- `"claude-3-7-sonnet-latest"`
High-performance model with early extended thinking
- `"claude-3-7-sonnet-20250219"`
High-performance model with early extended thinking
- `"claude-3-5-haiku-latest"`
Fastest and most compact model for near-instant responsiveness
- `"claude-3-5-haiku-20241022"`
Our fastest model
- `"claude-haiku-4-5"`
Hybrid model, capable of near-instant responses and extended thinking
- `"claude-haiku-4-5-20251001"`
Hybrid model, capable of near-instant responses and extended thinking
- `"claude-sonnet-4-20250514"`
High-performance model with extended thinking
- `"claude-sonnet-4-0"`
High-performance model with extended thinking
- `"claude-4-sonnet-20250514"`
High-performance model with extended thinking
- `"claude-sonnet-4-5"`
Our best model for real-world agents and coding
- `"claude-sonnet-4-5-20250929"`
Our best model for real-world agents and coding
- `"claude-opus-4-0"`
Our most capable model
- `"claude-opus-4-20250514"`
Our most capable model
- `"claude-4-opus-20250514"`
Our most capable model
- `"claude-opus-4-1-20250805"`
Our most capable model
- `"claude-3-opus-latest"`
Excels at writing and complex tasks
- `"claude-3-opus-20240229"`
Excels at writing and complex tasks
- `"claude-3-haiku-20240307"`
Our previous most fast and cost-effective
- `(string & {})`
- `metadata?: Metadata`
An object describing metadata about the request.
- `user_id?: string | null`
An external identifier for the user who is associated with the request.
This should be a uuid, hash value, or other opaque identifier. Anthropic may use this id to help detect abuse. Do not include any identifying information such as name, email address, or phone number.
- `output_config?: OutputConfig`
Configuration options for the model's output, such as the output format.
- `format?: Format | null`
A schema to specify Claude's output format in responses. See [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)
- `schema: Record`
The JSON schema of the format
- `type: "json_schema"`
- `"json_schema"`
- `service_tier?: "auto" | "standard_only"`
Determines whether to use priority capacity (if available) or standard capacity for this request.
Anthropic offers different levels of service for your API requests. See [service-tiers](https://docs.claude.com/en/api/service-tiers) for details.
- `"auto"`
- `"standard_only"`
- `stop_sequences?: Array`
Custom text sequences that will cause the model to stop generating.
Our models will normally stop when they have naturally completed their turn, which will result in a response `stop_reason` of `"end_turn"`.
If you want the model to stop generating when it encounters custom strings of text, you can use the `stop_sequences` parameter. If the model encounters one of the custom sequences, the response `stop_reason` value will be `"stop_sequence"` and the response `stop_sequence` value will contain the matched stop sequence.
- `stream?: boolean`
Whether to incrementally stream the response using server-sent events.
See [streaming](https://docs.claude.com/en/api/messages-streaming) for details.
- `system?: string | Array`
System prompt.
A system prompt is a way of providing context and instructions to Claude, such as specifying a particular goal or role. See our [guide to system prompts](https://docs.claude.com/en/docs/system-prompts).
- `string`
- `Array`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: CacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `CitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `CitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `CitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `CitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `CitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `temperature?: number`
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 generative tasks.
Note that even with `temperature` of `0.0`, the results will not be fully deterministic.
- `thinking?: ThinkingConfigParam`
Configuration for enabling Claude's extended thinking.
When enabled, responses include `thinking` content blocks showing Claude's thinking process before the final answer. Requires a minimum budget of 1,024 tokens and counts towards your `max_tokens` limit.
See [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) for details.
- `ThinkingConfigEnabled`
- `budget_tokens: number`
Determines how many tokens Claude can use for its internal reasoning process. Larger budgets can enable more thorough analysis for complex problems, improving response quality.
Must be ≥1024 and less than `max_tokens`.
See [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) for details.
- `type: "enabled"`
- `"enabled"`
- `ThinkingConfigDisabled`
- `type: "disabled"`
- `"disabled"`
- `tool_choice?: ToolChoice`
How the model should use the provided tools. The model can use a specific tool, any available tool, decide by itself, or not use tools at all.
- `ToolChoiceAuto`
The model will automatically decide whether to use tools.
- `type: "auto"`
- `"auto"`
- `disable_parallel_tool_use?: boolean`
Whether to disable parallel tool use.
Defaults to `false`. If set to `true`, the model will output at most one tool use.
- `ToolChoiceAny`
The model will use any available tools.
- `type: "any"`
- `"any"`
- `disable_parallel_tool_use?: boolean`
Whether to disable parallel tool use.
Defaults to `false`. If set to `true`, the model will output exactly one tool use.
- `ToolChoiceTool`
The model will use the specified tool with `tool_choice.name`.
- `name: string`
The name of the tool to use.
- `type: "tool"`
- `"tool"`
- `disable_parallel_tool_use?: boolean`
Whether to disable parallel tool use.
Defaults to `false`. If set to `true`, the model will output exactly one tool use.
- `ToolChoiceNone`
The model will not be allowed to use tools.
- `type: "none"`
- `"none"`
- `tools?: Array`
Definitions of tools that the model may use.
If you include `tools` in your API request, the model may return `tool_use` content blocks that represent the model's use of those tools. You can then run those tools using the tool input generated by the model and then optionally return results back to the model using `tool_result` content blocks.
There are two types of tools: **client tools** and **server tools**. The behavior described below applies to client tools. For [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview#server-tools), see their individual documentation as each has its own behavior (e.g., the [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)).
Each tool definition includes:
* `name`: Name of the tool.
* `description`: Optional, but strongly-recommended description of the tool.
* `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the tool `input` shape that the model will produce in `tool_use` output content blocks.
For example, if you defined `tools` as:
```json
[
{
"name": "get_stock_price",
"description": "Get the current stock price for a given ticker symbol.",
"input_schema": {
"type": "object",
"properties": {
"ticker": {
"type": "string",
"description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
}
},
"required": ["ticker"]
}
}
]
```
And then asked the model "What's the S&P 500 at today?", the model might produce `tool_use` content blocks in the response like this:
```json
[
{
"type": "tool_use",
"id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
"name": "get_stock_price",
"input": { "ticker": "^GSPC" }
}
]
```
You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an input, and return the following back to the model in a subsequent `user` message:
```json
[
{
"type": "tool_result",
"tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
"content": "259.75 USD"
}
]
```
Tools can be used for workflows that include running client-side tools and functions, or more generally whenever you want the model to produce a particular JSON structure of output.
See our [guide](https://docs.claude.com/en/docs/tool-use) for more details.
- `Tool`
- `input_schema: InputSchema`
[JSON schema](https://json-schema.org/draft/2020-12) for this tool's input.
This defines the shape of the `input` that your tool accepts and that the model will produce.
- `type: "object"`
- `"object"`
- `properties?: Record | null`
- `required?: Array | null`
- `name: string`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `cache_control?: CacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `description?: string`
Description of what this tool does.
Tool descriptions should be as detailed as possible. The more information that the model has about what the tool is and how to use it, the better it will perform. You can use natural language descriptions to reinforce important aspects of the tool input JSON schema.
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `type?: "custom" | null`
- `"custom"`
- `ToolBash20250124`
- `name: "bash"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"bash"`
- `type: "bash_20250124"`
- `"bash_20250124"`
- `cache_control?: CacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `ToolTextEditor20250124`
- `name: "str_replace_editor"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"str_replace_editor"`
- `type: "text_editor_20250124"`
- `"text_editor_20250124"`
- `cache_control?: CacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `ToolTextEditor20250429`
- `name: "str_replace_based_edit_tool"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"str_replace_based_edit_tool"`
- `type: "text_editor_20250429"`
- `"text_editor_20250429"`
- `cache_control?: CacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `ToolTextEditor20250728`
- `name: "str_replace_based_edit_tool"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"str_replace_based_edit_tool"`
- `type: "text_editor_20250728"`
- `"text_editor_20250728"`
- `cache_control?: CacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `max_characters?: number | null`
Maximum number of characters to display when viewing a file. If not specified, defaults to displaying the full file.
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `WebSearchTool20250305`
- `name: "web_search"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"web_search"`
- `type: "web_search_20250305"`
- `"web_search_20250305"`
- `allowed_domains?: Array | null`
If provided, only these domains will be included in results. Cannot be used alongside `blocked_domains`.
- `blocked_domains?: Array | null`
If provided, these domains will never appear in results. Cannot be used alongside `allowed_domains`.
- `cache_control?: CacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `max_uses?: number | null`
Maximum number of times the tool can be used in the API request.
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `user_location?: UserLocation | null`
Parameters for the user's location. Used to provide more relevant search results.
- `type: "approximate"`
- `"approximate"`
- `city?: string | null`
The city of the user.
- `country?: string | null`
The two letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the user.
- `region?: string | null`
The region of the user.
- `timezone?: string | null`
The [IANA timezone](https://nodatime.org/TimeZones) of the user.
- `top_k?: number`
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).
Recommended for advanced use cases only. You usually only need to use `temperature`.
- `top_p?: number`
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 reaches a particular probability specified by `top_p`. You should either alter `temperature` or `top_p`, but not both.
Recommended for advanced use cases only. You usually only need to use `temperature`.
### Returns
- `MessageBatch`
- `id: string`
Unique object identifier.
The format and length of IDs may change over time.
- `archived_at: string | null`
RFC 3339 datetime string representing the time at which the Message Batch was archived and its results became unavailable.
- `cancel_initiated_at: string | null`
RFC 3339 datetime string representing the time at which cancellation was initiated for the Message Batch. Specified only if cancellation was initiated.
- `created_at: string`
RFC 3339 datetime string representing the time at which the Message Batch was created.
- `ended_at: string | null`
RFC 3339 datetime string representing the time at which processing for the Message Batch ended. Specified only once processing ends.
Processing ends when every request in a Message Batch has either succeeded, errored, canceled, or expired.
- `expires_at: string`
RFC 3339 datetime string representing the time at which the Message Batch will expire and end processing, which is 24 hours after creation.
- `processing_status: "in_progress" | "canceling" | "ended"`
Processing status of the Message Batch.
- `"in_progress"`
- `"canceling"`
- `"ended"`
- `request_counts: MessageBatchRequestCounts`
Tallies requests within the Message Batch, categorized by their status.
Requests start as `processing` and move to one of the other statuses only once processing of the entire batch ends. The sum of all values always matches the total number of requests in the batch.
- `canceled: number`
Number of requests in the Message Batch that have been canceled.
This is zero until processing of the entire Message Batch has ended.
- `errored: number`
Number of requests in the Message Batch that encountered an error.
This is zero until processing of the entire Message Batch has ended.
- `expired: number`
Number of requests in the Message Batch that have expired.
This is zero until processing of the entire Message Batch has ended.
- `processing: number`
Number of requests in the Message Batch that are processing.
- `succeeded: number`
Number of requests in the Message Batch that have completed successfully.
This is zero until processing of the entire Message Batch has ended.
- `results_url: string | null`
URL to a `.jsonl` file containing the results of the Message Batch requests. Specified only once processing ends.
Results in the file are not guaranteed to be in the same order as requests. Use the `custom_id` field to match results to requests.
- `type: "message_batch"`
Object type.
For Message Batches, this is always `"message_batch"`.
- `"message_batch"`
### Example
```typescript
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic({
apiKey: process.env['ANTHROPIC_API_KEY'], // This is the default and can be omitted
});
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-sonnet-4-5-20250929',
},
},
],
});
console.log(messageBatch.id);
```
## Retrieve
`client.messages.batches.retrieve(stringmessageBatchID, RequestOptionsoptions?): MessageBatch`
**get** `/v1/messages/batches/{message_batch_id}`
This endpoint is idempotent and can be used to poll for Message Batch completion. To access the results of a Message Batch, make a request to the `results_url` field in the response.
Learn more about the Message Batches API in our [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
### Parameters
- `messageBatchID: string`
ID of the Message Batch.
### Returns
- `MessageBatch`
- `id: string`
Unique object identifier.
The format and length of IDs may change over time.
- `archived_at: string | null`
RFC 3339 datetime string representing the time at which the Message Batch was archived and its results became unavailable.
- `cancel_initiated_at: string | null`
RFC 3339 datetime string representing the time at which cancellation was initiated for the Message Batch. Specified only if cancellation was initiated.
- `created_at: string`
RFC 3339 datetime string representing the time at which the Message Batch was created.
- `ended_at: string | null`
RFC 3339 datetime string representing the time at which processing for the Message Batch ended. Specified only once processing ends.
Processing ends when every request in a Message Batch has either succeeded, errored, canceled, or expired.
- `expires_at: string`
RFC 3339 datetime string representing the time at which the Message Batch will expire and end processing, which is 24 hours after creation.
- `processing_status: "in_progress" | "canceling" | "ended"`
Processing status of the Message Batch.
- `"in_progress"`
- `"canceling"`
- `"ended"`
- `request_counts: MessageBatchRequestCounts`
Tallies requests within the Message Batch, categorized by their status.
Requests start as `processing` and move to one of the other statuses only once processing of the entire batch ends. The sum of all values always matches the total number of requests in the batch.
- `canceled: number`
Number of requests in the Message Batch that have been canceled.
This is zero until processing of the entire Message Batch has ended.
- `errored: number`
Number of requests in the Message Batch that encountered an error.
This is zero until processing of the entire Message Batch has ended.
- `expired: number`
Number of requests in the Message Batch that have expired.
This is zero until processing of the entire Message Batch has ended.
- `processing: number`
Number of requests in the Message Batch that are processing.
- `succeeded: number`
Number of requests in the Message Batch that have completed successfully.
This is zero until processing of the entire Message Batch has ended.
- `results_url: string | null`
URL to a `.jsonl` file containing the results of the Message Batch requests. Specified only once processing ends.
Results in the file are not guaranteed to be in the same order as requests. Use the `custom_id` field to match results to requests.
- `type: "message_batch"`
Object type.
For Message Batches, this is always `"message_batch"`.
- `"message_batch"`
### Example
```typescript
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic({
apiKey: process.env['ANTHROPIC_API_KEY'], // This is the default and can be omitted
});
const messageBatch = await client.messages.batches.retrieve('message_batch_id');
console.log(messageBatch.id);
```
## List
`client.messages.batches.list(BatchListParamsquery?, RequestOptionsoptions?): Page`
**get** `/v1/messages/batches`
List all Message Batches within a Workspace. Most recently created batches are returned first.
Learn more about the Message Batches API in our [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
### Parameters
- `query: BatchListParams`
- `after_id?: string`
ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately after this object.
- `before_id?: string`
ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately before this object.
- `limit?: number`
Number of items to return per page.
Defaults to `20`. Ranges from `1` to `1000`.
### Returns
- `MessageBatch`
- `id: string`
Unique object identifier.
The format and length of IDs may change over time.
- `archived_at: string | null`
RFC 3339 datetime string representing the time at which the Message Batch was archived and its results became unavailable.
- `cancel_initiated_at: string | null`
RFC 3339 datetime string representing the time at which cancellation was initiated for the Message Batch. Specified only if cancellation was initiated.
- `created_at: string`
RFC 3339 datetime string representing the time at which the Message Batch was created.
- `ended_at: string | null`
RFC 3339 datetime string representing the time at which processing for the Message Batch ended. Specified only once processing ends.
Processing ends when every request in a Message Batch has either succeeded, errored, canceled, or expired.
- `expires_at: string`
RFC 3339 datetime string representing the time at which the Message Batch will expire and end processing, which is 24 hours after creation.
- `processing_status: "in_progress" | "canceling" | "ended"`
Processing status of the Message Batch.
- `"in_progress"`
- `"canceling"`
- `"ended"`
- `request_counts: MessageBatchRequestCounts`
Tallies requests within the Message Batch, categorized by their status.
Requests start as `processing` and move to one of the other statuses only once processing of the entire batch ends. The sum of all values always matches the total number of requests in the batch.
- `canceled: number`
Number of requests in the Message Batch that have been canceled.
This is zero until processing of the entire Message Batch has ended.
- `errored: number`
Number of requests in the Message Batch that encountered an error.
This is zero until processing of the entire Message Batch has ended.
- `expired: number`
Number of requests in the Message Batch that have expired.
This is zero until processing of the entire Message Batch has ended.
- `processing: number`
Number of requests in the Message Batch that are processing.
- `succeeded: number`
Number of requests in the Message Batch that have completed successfully.
This is zero until processing of the entire Message Batch has ended.
- `results_url: string | null`
URL to a `.jsonl` file containing the results of the Message Batch requests. Specified only once processing ends.
Results in the file are not guaranteed to be in the same order as requests. Use the `custom_id` field to match results to requests.
- `type: "message_batch"`
Object type.
For Message Batches, this is always `"message_batch"`.
- `"message_batch"`
### Example
```typescript
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic({
apiKey: process.env['ANTHROPIC_API_KEY'], // This is the default and can be omitted
});
// Automatically fetches more pages as needed.
for await (const messageBatch of client.messages.batches.list()) {
console.log(messageBatch.id);
}
```
## Cancel
`client.messages.batches.cancel(stringmessageBatchID, RequestOptionsoptions?): MessageBatch`
**post** `/v1/messages/batches/{message_batch_id}/cancel`
Batches may be canceled any time before processing ends. Once cancellation is initiated, the batch enters a `canceling` state, at which time the system may complete any in-progress, non-interruptible requests before finalizing cancellation.
The number of canceled requests is specified in `request_counts`. To determine which requests were canceled, check the individual results within the batch. Note that cancellation may not result in any canceled requests if they were non-interruptible.
Learn more about the Message Batches API in our [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
### Parameters
- `messageBatchID: string`
ID of the Message Batch.
### Returns
- `MessageBatch`
- `id: string`
Unique object identifier.
The format and length of IDs may change over time.
- `archived_at: string | null`
RFC 3339 datetime string representing the time at which the Message Batch was archived and its results became unavailable.
- `cancel_initiated_at: string | null`
RFC 3339 datetime string representing the time at which cancellation was initiated for the Message Batch. Specified only if cancellation was initiated.
- `created_at: string`
RFC 3339 datetime string representing the time at which the Message Batch was created.
- `ended_at: string | null`
RFC 3339 datetime string representing the time at which processing for the Message Batch ended. Specified only once processing ends.
Processing ends when every request in a Message Batch has either succeeded, errored, canceled, or expired.
- `expires_at: string`
RFC 3339 datetime string representing the time at which the Message Batch will expire and end processing, which is 24 hours after creation.
- `processing_status: "in_progress" | "canceling" | "ended"`
Processing status of the Message Batch.
- `"in_progress"`
- `"canceling"`
- `"ended"`
- `request_counts: MessageBatchRequestCounts`
Tallies requests within the Message Batch, categorized by their status.
Requests start as `processing` and move to one of the other statuses only once processing of the entire batch ends. The sum of all values always matches the total number of requests in the batch.
- `canceled: number`
Number of requests in the Message Batch that have been canceled.
This is zero until processing of the entire Message Batch has ended.
- `errored: number`
Number of requests in the Message Batch that encountered an error.
This is zero until processing of the entire Message Batch has ended.
- `expired: number`
Number of requests in the Message Batch that have expired.
This is zero until processing of the entire Message Batch has ended.
- `processing: number`
Number of requests in the Message Batch that are processing.
- `succeeded: number`
Number of requests in the Message Batch that have completed successfully.
This is zero until processing of the entire Message Batch has ended.
- `results_url: string | null`
URL to a `.jsonl` file containing the results of the Message Batch requests. Specified only once processing ends.
Results in the file are not guaranteed to be in the same order as requests. Use the `custom_id` field to match results to requests.
- `type: "message_batch"`
Object type.
For Message Batches, this is always `"message_batch"`.
- `"message_batch"`
### Example
```typescript
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic({
apiKey: process.env['ANTHROPIC_API_KEY'], // This is the default and can be omitted
});
const messageBatch = await client.messages.batches.cancel('message_batch_id');
console.log(messageBatch.id);
```
## Delete
`client.messages.batches.delete(stringmessageBatchID, RequestOptionsoptions?): DeletedMessageBatch`
**delete** `/v1/messages/batches/{message_batch_id}`
Delete a Message Batch.
Message Batches can only be deleted once they've finished processing. If you'd like to delete an in-progress batch, you must first cancel it.
Learn more about the Message Batches API in our [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
### Parameters
- `messageBatchID: string`
ID of the Message Batch.
### Returns
- `DeletedMessageBatch`
- `id: string`
ID of the Message Batch.
- `type: "message_batch_deleted"`
Deleted object type.
For Message Batches, this is always `"message_batch_deleted"`.
- `"message_batch_deleted"`
### Example
```typescript
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic({
apiKey: process.env['ANTHROPIC_API_KEY'], // This is the default and can be omitted
});
const deletedMessageBatch = await client.messages.batches.delete('message_batch_id');
console.log(deletedMessageBatch.id);
```
## Results
`client.messages.batches.results(stringmessageBatchID, RequestOptionsoptions?): MessageBatchIndividualResponse | Stream`
**get** `/v1/messages/batches/{message_batch_id}/results`
Streams the results of a Message Batch as a `.jsonl` file.
Each line in the file is a JSON object containing the result of a single request in the Message Batch. Results are not guaranteed to be in the same order as requests. Use the `custom_id` field to match results to requests.
Learn more about the Message Batches API in our [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
### Parameters
- `messageBatchID: string`
ID of the Message Batch.
### Returns
- `MessageBatchIndividualResponse`
This is a single line in the response `.jsonl` file and does not represent the response as a whole.
- `custom_id: string`
Developer-provided ID created for each request in a Message Batch. Useful for matching results to requests, as results may be given out of request order.
Must be unique for each request within the Message Batch.
- `result: MessageBatchResult`
Processing result for this request.
Contains a Message output if processing was successful, an error response if processing failed, or the reason why processing was not attempted, such as cancellation or expiration.
- `MessageBatchSucceededResult`
- `message: Message`
- `id: string`
Unique object identifier.
The format and length of IDs may change over time.
- `content: Array`
Content generated by the model.
This is an array of content blocks, each of which has a `type` that determines its shape.
Example:
```json
[{"type": "text", "text": "Hi, I'm Claude."}]
```
If the request input `messages` ended with an `assistant` turn, then the response `content` will continue directly from that last turn. You can use this to constrain the model's output.
For example, if the input `messages` were:
```json
[
{"role": "user", "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"},
{"role": "assistant", "content": "The best answer is ("}
]
```
Then the response `content` might be:
```json
[{"type": "text", "text": "B)"}]
```
- `TextBlock`
- `citations: Array | null`
Citations supporting the text block.
The type of citation returned will depend on the type of document being cited. Citing a PDF results in `page_location`, plain text results in `char_location`, and content document results in `content_block_location`.
- `CitationCharLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `file_id: string | null`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `CitationPageLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `file_id: string | null`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `CitationContentBlockLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `file_id: string | null`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `CitationsWebSearchResultLocation`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `CitationsSearchResultLocation`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `text: string`
- `type: "text"`
- `"text"`
- `ThinkingBlock`
- `signature: string`
- `thinking: string`
- `type: "thinking"`
- `"thinking"`
- `RedactedThinkingBlock`
- `data: string`
- `type: "redacted_thinking"`
- `"redacted_thinking"`
- `ToolUseBlock`
- `id: string`
- `input: Record`
- `name: string`
- `type: "tool_use"`
- `"tool_use"`
- `ServerToolUseBlock`
- `id: string`
- `input: Record`
- `name: "web_search"`
- `"web_search"`
- `type: "server_tool_use"`
- `"server_tool_use"`
- `WebSearchToolResultBlock`
- `content: WebSearchToolResultBlockContent`
- `WebSearchToolResultError`
- `error_code: "invalid_tool_input" | "unavailable" | "max_uses_exceeded" | 3 more`
- `"invalid_tool_input"`
- `"unavailable"`
- `"max_uses_exceeded"`
- `"too_many_requests"`
- `"query_too_long"`
- `"request_too_large"`
- `type: "web_search_tool_result_error"`
- `"web_search_tool_result_error"`
- `Array`
- `encrypted_content: string`
- `page_age: string | null`
- `title: string`
- `type: "web_search_result"`
- `"web_search_result"`
- `url: string`
- `tool_use_id: string`
- `type: "web_search_tool_result"`
- `"web_search_tool_result"`
- `model: Model`
The model that will complete your prompt.
See [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options.
- `"claude-opus-4-5-20251101" | "claude-opus-4-5" | "claude-3-7-sonnet-latest" | 17 more`
- `"claude-opus-4-5-20251101"`
Premium model combining maximum intelligence with practical performance
- `"claude-opus-4-5"`
Premium model combining maximum intelligence with practical performance
- `"claude-3-7-sonnet-latest"`
High-performance model with early extended thinking
- `"claude-3-7-sonnet-20250219"`
High-performance model with early extended thinking
- `"claude-3-5-haiku-latest"`
Fastest and most compact model for near-instant responsiveness
- `"claude-3-5-haiku-20241022"`
Our fastest model
- `"claude-haiku-4-5"`
Hybrid model, capable of near-instant responses and extended thinking
- `"claude-haiku-4-5-20251001"`
Hybrid model, capable of near-instant responses and extended thinking
- `"claude-sonnet-4-20250514"`
High-performance model with extended thinking
- `"claude-sonnet-4-0"`
High-performance model with extended thinking
- `"claude-4-sonnet-20250514"`
High-performance model with extended thinking
- `"claude-sonnet-4-5"`
Our best model for real-world agents and coding
- `"claude-sonnet-4-5-20250929"`
Our best model for real-world agents and coding
- `"claude-opus-4-0"`
Our most capable model
- `"claude-opus-4-20250514"`
Our most capable model
- `"claude-4-opus-20250514"`
Our most capable model
- `"claude-opus-4-1-20250805"`
Our most capable model
- `"claude-3-opus-latest"`
Excels at writing and complex tasks
- `"claude-3-opus-20240229"`
Excels at writing and complex tasks
- `"claude-3-haiku-20240307"`
Our previous most fast and cost-effective
- `(string & {})`
- `role: "assistant"`
Conversational role of the generated message.
This will always be `"assistant"`.
- `"assistant"`
- `stop_reason: StopReason | null`
The reason that we stopped.
This may be one the following values:
* `"end_turn"`: the model reached a natural stopping point
* `"max_tokens"`: we exceeded the requested `max_tokens` or the model's maximum
* `"stop_sequence"`: one of your provided custom `stop_sequences` was generated
* `"tool_use"`: the model invoked one or more tools
* `"pause_turn"`: we paused a long-running turn. You may provide the response back as-is in a subsequent request to let the model continue.
* `"refusal"`: when streaming classifiers intervene to handle potential policy violations
In non-streaming mode this value is always non-null. In streaming mode, it is null in the `message_start` event and non-null otherwise.
- `"end_turn"`
- `"max_tokens"`
- `"stop_sequence"`
- `"tool_use"`
- `"pause_turn"`
- `"refusal"`
- `stop_sequence: string | null`
Which custom stop sequence was generated, if any.
This value will be a non-null string if one of your custom stop sequences was generated.
- `type: "message"`
Object type.
For Messages, this is always `"message"`.
- `"message"`
- `usage: Usage`
Billing and rate-limit usage.
Anthropic's API bills and rate-limits by token counts, as tokens represent the underlying cost to our systems.
Under the hood, the API transforms requests into a format suitable for the model. The model's output then goes through a parsing stage before becoming an API response. As a result, the token counts in `usage` will not match one-to-one with the exact visible content of an API request or response.
For example, `output_tokens` will be non-zero, even for an empty string response from Claude.
Total input tokens in a request is the summation of `input_tokens`, `cache_creation_input_tokens`, and `cache_read_input_tokens`.
- `cache_creation: CacheCreation | null`
Breakdown of cached tokens by TTL
- `ephemeral_1h_input_tokens: number`
The number of input tokens used to create the 1 hour cache entry.
- `ephemeral_5m_input_tokens: number`
The number of input tokens used to create the 5 minute cache entry.
- `cache_creation_input_tokens: number | null`
The number of input tokens used to create the cache entry.
- `cache_read_input_tokens: number | null`
The number of input tokens read from the cache.
- `input_tokens: number`
The number of input tokens which were used.
- `output_tokens: number`
The number of output tokens which were used.
- `server_tool_use: ServerToolUsage | null`
The number of server tool requests.
- `web_search_requests: number`
The number of web search tool requests.
- `service_tier: "standard" | "priority" | "batch" | null`
If the request used the priority, standard, or batch tier.
- `"standard"`
- `"priority"`
- `"batch"`
- `type: "succeeded"`
- `"succeeded"`
- `MessageBatchErroredResult`
- `error: ErrorResponse`
- `error: ErrorObject`
- `InvalidRequestError`
- `message: string`
- `type: "invalid_request_error"`
- `"invalid_request_error"`
- `AuthenticationError`
- `message: string`
- `type: "authentication_error"`
- `"authentication_error"`
- `BillingError`
- `message: string`
- `type: "billing_error"`
- `"billing_error"`
- `PermissionError`
- `message: string`
- `type: "permission_error"`
- `"permission_error"`
- `NotFoundError`
- `message: string`
- `type: "not_found_error"`
- `"not_found_error"`
- `RateLimitError`
- `message: string`
- `type: "rate_limit_error"`
- `"rate_limit_error"`
- `GatewayTimeoutError`
- `message: string`
- `type: "timeout_error"`
- `"timeout_error"`
- `APIErrorObject`
- `message: string`
- `type: "api_error"`
- `"api_error"`
- `OverloadedError`
- `message: string`
- `type: "overloaded_error"`
- `"overloaded_error"`
- `request_id: string | null`
- `type: "error"`
- `"error"`
- `type: "errored"`
- `"errored"`
- `MessageBatchCanceledResult`
- `type: "canceled"`
- `"canceled"`
- `MessageBatchExpiredResult`
- `type: "expired"`
- `"expired"`
### Example
```typescript
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic({
apiKey: process.env['ANTHROPIC_API_KEY'], // This is the default and can be omitted
});
const messageBatchIndividualResponse = await client.messages.batches.results('message_batch_id');
console.log(messageBatchIndividualResponse.custom_id);
```
## Domain Types
### Deleted Message Batch
- `DeletedMessageBatch`
- `id: string`
ID of the Message Batch.
- `type: "message_batch_deleted"`
Deleted object type.
For Message Batches, this is always `"message_batch_deleted"`.
- `"message_batch_deleted"`
### Message Batch
- `MessageBatch`
- `id: string`
Unique object identifier.
The format and length of IDs may change over time.
- `archived_at: string | null`
RFC 3339 datetime string representing the time at which the Message Batch was archived and its results became unavailable.
- `cancel_initiated_at: string | null`
RFC 3339 datetime string representing the time at which cancellation was initiated for the Message Batch. Specified only if cancellation was initiated.
- `created_at: string`
RFC 3339 datetime string representing the time at which the Message Batch was created.
- `ended_at: string | null`
RFC 3339 datetime string representing the time at which processing for the Message Batch ended. Specified only once processing ends.
Processing ends when every request in a Message Batch has either succeeded, errored, canceled, or expired.
- `expires_at: string`
RFC 3339 datetime string representing the time at which the Message Batch will expire and end processing, which is 24 hours after creation.
- `processing_status: "in_progress" | "canceling" | "ended"`
Processing status of the Message Batch.
- `"in_progress"`
- `"canceling"`
- `"ended"`
- `request_counts: MessageBatchRequestCounts`
Tallies requests within the Message Batch, categorized by their status.
Requests start as `processing` and move to one of the other statuses only once processing of the entire batch ends. The sum of all values always matches the total number of requests in the batch.
- `canceled: number`
Number of requests in the Message Batch that have been canceled.
This is zero until processing of the entire Message Batch has ended.
- `errored: number`
Number of requests in the Message Batch that encountered an error.
This is zero until processing of the entire Message Batch has ended.
- `expired: number`
Number of requests in the Message Batch that have expired.
This is zero until processing of the entire Message Batch has ended.
- `processing: number`
Number of requests in the Message Batch that are processing.
- `succeeded: number`
Number of requests in the Message Batch that have completed successfully.
This is zero until processing of the entire Message Batch has ended.
- `results_url: string | null`
URL to a `.jsonl` file containing the results of the Message Batch requests. Specified only once processing ends.
Results in the file are not guaranteed to be in the same order as requests. Use the `custom_id` field to match results to requests.
- `type: "message_batch"`
Object type.
For Message Batches, this is always `"message_batch"`.
- `"message_batch"`
### Message Batch Canceled Result
- `MessageBatchCanceledResult`
- `type: "canceled"`
- `"canceled"`
### Message Batch Errored Result
- `MessageBatchErroredResult`
- `error: ErrorResponse`
- `error: ErrorObject`
- `InvalidRequestError`
- `message: string`
- `type: "invalid_request_error"`
- `"invalid_request_error"`
- `AuthenticationError`
- `message: string`
- `type: "authentication_error"`
- `"authentication_error"`
- `BillingError`
- `message: string`
- `type: "billing_error"`
- `"billing_error"`
- `PermissionError`
- `message: string`
- `type: "permission_error"`
- `"permission_error"`
- `NotFoundError`
- `message: string`
- `type: "not_found_error"`
- `"not_found_error"`
- `RateLimitError`
- `message: string`
- `type: "rate_limit_error"`
- `"rate_limit_error"`
- `GatewayTimeoutError`
- `message: string`
- `type: "timeout_error"`
- `"timeout_error"`
- `APIErrorObject`
- `message: string`
- `type: "api_error"`
- `"api_error"`
- `OverloadedError`
- `message: string`
- `type: "overloaded_error"`
- `"overloaded_error"`
- `request_id: string | null`
- `type: "error"`
- `"error"`
- `type: "errored"`
- `"errored"`
### Message Batch Expired Result
- `MessageBatchExpiredResult`
- `type: "expired"`
- `"expired"`
### Message Batch Individual Response
- `MessageBatchIndividualResponse`
This is a single line in the response `.jsonl` file and does not represent the response as a whole.
- `custom_id: string`
Developer-provided ID created for each request in a Message Batch. Useful for matching results to requests, as results may be given out of request order.
Must be unique for each request within the Message Batch.
- `result: MessageBatchResult`
Processing result for this request.
Contains a Message output if processing was successful, an error response if processing failed, or the reason why processing was not attempted, such as cancellation or expiration.
- `MessageBatchSucceededResult`
- `message: Message`
- `id: string`
Unique object identifier.
The format and length of IDs may change over time.
- `content: Array`
Content generated by the model.
This is an array of content blocks, each of which has a `type` that determines its shape.
Example:
```json
[{"type": "text", "text": "Hi, I'm Claude."}]
```
If the request input `messages` ended with an `assistant` turn, then the response `content` will continue directly from that last turn. You can use this to constrain the model's output.
For example, if the input `messages` were:
```json
[
{"role": "user", "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"},
{"role": "assistant", "content": "The best answer is ("}
]
```
Then the response `content` might be:
```json
[{"type": "text", "text": "B)"}]
```
- `TextBlock`
- `citations: Array | null`
Citations supporting the text block.
The type of citation returned will depend on the type of document being cited. Citing a PDF results in `page_location`, plain text results in `char_location`, and content document results in `content_block_location`.
- `CitationCharLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `file_id: string | null`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `CitationPageLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `file_id: string | null`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `CitationContentBlockLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `file_id: string | null`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `CitationsWebSearchResultLocation`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `CitationsSearchResultLocation`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `text: string`
- `type: "text"`
- `"text"`
- `ThinkingBlock`
- `signature: string`
- `thinking: string`
- `type: "thinking"`
- `"thinking"`
- `RedactedThinkingBlock`
- `data: string`
- `type: "redacted_thinking"`
- `"redacted_thinking"`
- `ToolUseBlock`
- `id: string`
- `input: Record`
- `name: string`
- `type: "tool_use"`
- `"tool_use"`
- `ServerToolUseBlock`
- `id: string`
- `input: Record`
- `name: "web_search"`
- `"web_search"`
- `type: "server_tool_use"`
- `"server_tool_use"`
- `WebSearchToolResultBlock`
- `content: WebSearchToolResultBlockContent`
- `WebSearchToolResultError`
- `error_code: "invalid_tool_input" | "unavailable" | "max_uses_exceeded" | 3 more`
- `"invalid_tool_input"`
- `"unavailable"`
- `"max_uses_exceeded"`
- `"too_many_requests"`
- `"query_too_long"`
- `"request_too_large"`
- `type: "web_search_tool_result_error"`
- `"web_search_tool_result_error"`
- `Array`
- `encrypted_content: string`
- `page_age: string | null`
- `title: string`
- `type: "web_search_result"`
- `"web_search_result"`
- `url: string`
- `tool_use_id: string`
- `type: "web_search_tool_result"`
- `"web_search_tool_result"`
- `model: Model`
The model that will complete your prompt.
See [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options.
- `"claude-opus-4-5-20251101" | "claude-opus-4-5" | "claude-3-7-sonnet-latest" | 17 more`
- `"claude-opus-4-5-20251101"`
Premium model combining maximum intelligence with practical performance
- `"claude-opus-4-5"`
Premium model combining maximum intelligence with practical performance
- `"claude-3-7-sonnet-latest"`
High-performance model with early extended thinking
- `"claude-3-7-sonnet-20250219"`
High-performance model with early extended thinking
- `"claude-3-5-haiku-latest"`
Fastest and most compact model for near-instant responsiveness
- `"claude-3-5-haiku-20241022"`
Our fastest model
- `"claude-haiku-4-5"`
Hybrid model, capable of near-instant responses and extended thinking
- `"claude-haiku-4-5-20251001"`
Hybrid model, capable of near-instant responses and extended thinking
- `"claude-sonnet-4-20250514"`
High-performance model with extended thinking
- `"claude-sonnet-4-0"`
High-performance model with extended thinking
- `"claude-4-sonnet-20250514"`
High-performance model with extended thinking
- `"claude-sonnet-4-5"`
Our best model for real-world agents and coding
- `"claude-sonnet-4-5-20250929"`
Our best model for real-world agents and coding
- `"claude-opus-4-0"`
Our most capable model
- `"claude-opus-4-20250514"`
Our most capable model
- `"claude-4-opus-20250514"`
Our most capable model
- `"claude-opus-4-1-20250805"`
Our most capable model
- `"claude-3-opus-latest"`
Excels at writing and complex tasks
- `"claude-3-opus-20240229"`
Excels at writing and complex tasks
- `"claude-3-haiku-20240307"`
Our previous most fast and cost-effective
- `(string & {})`
- `role: "assistant"`
Conversational role of the generated message.
This will always be `"assistant"`.
- `"assistant"`
- `stop_reason: StopReason | null`
The reason that we stopped.
This may be one the following values:
* `"end_turn"`: the model reached a natural stopping point
* `"max_tokens"`: we exceeded the requested `max_tokens` or the model's maximum
* `"stop_sequence"`: one of your provided custom `stop_sequences` was generated
* `"tool_use"`: the model invoked one or more tools
* `"pause_turn"`: we paused a long-running turn. You may provide the response back as-is in a subsequent request to let the model continue.
* `"refusal"`: when streaming classifiers intervene to handle potential policy violations
In non-streaming mode this value is always non-null. In streaming mode, it is null in the `message_start` event and non-null otherwise.
- `"end_turn"`
- `"max_tokens"`
- `"stop_sequence"`
- `"tool_use"`
- `"pause_turn"`
- `"refusal"`
- `stop_sequence: string | null`
Which custom stop sequence was generated, if any.
This value will be a non-null string if one of your custom stop sequences was generated.
- `type: "message"`
Object type.
For Messages, this is always `"message"`.
- `"message"`
- `usage: Usage`
Billing and rate-limit usage.
Anthropic's API bills and rate-limits by token counts, as tokens represent the underlying cost to our systems.
Under the hood, the API transforms requests into a format suitable for the model. The model's output then goes through a parsing stage before becoming an API response. As a result, the token counts in `usage` will not match one-to-one with the exact visible content of an API request or response.
For example, `output_tokens` will be non-zero, even for an empty string response from Claude.
Total input tokens in a request is the summation of `input_tokens`, `cache_creation_input_tokens`, and `cache_read_input_tokens`.
- `cache_creation: CacheCreation | null`
Breakdown of cached tokens by TTL
- `ephemeral_1h_input_tokens: number`
The number of input tokens used to create the 1 hour cache entry.
- `ephemeral_5m_input_tokens: number`
The number of input tokens used to create the 5 minute cache entry.
- `cache_creation_input_tokens: number | null`
The number of input tokens used to create the cache entry.
- `cache_read_input_tokens: number | null`
The number of input tokens read from the cache.
- `input_tokens: number`
The number of input tokens which were used.
- `output_tokens: number`
The number of output tokens which were used.
- `server_tool_use: ServerToolUsage | null`
The number of server tool requests.
- `web_search_requests: number`
The number of web search tool requests.
- `service_tier: "standard" | "priority" | "batch" | null`
If the request used the priority, standard, or batch tier.
- `"standard"`
- `"priority"`
- `"batch"`
- `type: "succeeded"`
- `"succeeded"`
- `MessageBatchErroredResult`
- `error: ErrorResponse`
- `error: ErrorObject`
- `InvalidRequestError`
- `message: string`
- `type: "invalid_request_error"`
- `"invalid_request_error"`
- `AuthenticationError`
- `message: string`
- `type: "authentication_error"`
- `"authentication_error"`
- `BillingError`
- `message: string`
- `type: "billing_error"`
- `"billing_error"`
- `PermissionError`
- `message: string`
- `type: "permission_error"`
- `"permission_error"`
- `NotFoundError`
- `message: string`
- `type: "not_found_error"`
- `"not_found_error"`
- `RateLimitError`
- `message: string`
- `type: "rate_limit_error"`
- `"rate_limit_error"`
- `GatewayTimeoutError`
- `message: string`
- `type: "timeout_error"`
- `"timeout_error"`
- `APIErrorObject`
- `message: string`
- `type: "api_error"`
- `"api_error"`
- `OverloadedError`
- `message: string`
- `type: "overloaded_error"`
- `"overloaded_error"`
- `request_id: string | null`
- `type: "error"`
- `"error"`
- `type: "errored"`
- `"errored"`
- `MessageBatchCanceledResult`
- `type: "canceled"`
- `"canceled"`
- `MessageBatchExpiredResult`
- `type: "expired"`
- `"expired"`
### Message Batch Request Counts
- `MessageBatchRequestCounts`
- `canceled: number`
Number of requests in the Message Batch that have been canceled.
This is zero until processing of the entire Message Batch has ended.
- `errored: number`
Number of requests in the Message Batch that encountered an error.
This is zero until processing of the entire Message Batch has ended.
- `expired: number`
Number of requests in the Message Batch that have expired.
This is zero until processing of the entire Message Batch has ended.
- `processing: number`
Number of requests in the Message Batch that are processing.
- `succeeded: number`
Number of requests in the Message Batch that have completed successfully.
This is zero until processing of the entire Message Batch has ended.
### Message Batch Result
- `MessageBatchResult = MessageBatchSucceededResult | MessageBatchErroredResult | MessageBatchCanceledResult | MessageBatchExpiredResult`
Processing result for this request.
Contains a Message output if processing was successful, an error response if processing failed, or the reason why processing was not attempted, such as cancellation or expiration.
- `MessageBatchSucceededResult`
- `message: Message`
- `id: string`
Unique object identifier.
The format and length of IDs may change over time.
- `content: Array`
Content generated by the model.
This is an array of content blocks, each of which has a `type` that determines its shape.
Example:
```json
[{"type": "text", "text": "Hi, I'm Claude."}]
```
If the request input `messages` ended with an `assistant` turn, then the response `content` will continue directly from that last turn. You can use this to constrain the model's output.
For example, if the input `messages` were:
```json
[
{"role": "user", "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"},
{"role": "assistant", "content": "The best answer is ("}
]
```
Then the response `content` might be:
```json
[{"type": "text", "text": "B)"}]
```
- `TextBlock`
- `citations: Array | null`
Citations supporting the text block.
The type of citation returned will depend on the type of document being cited. Citing a PDF results in `page_location`, plain text results in `char_location`, and content document results in `content_block_location`.
- `CitationCharLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `file_id: string | null`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `CitationPageLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `file_id: string | null`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `CitationContentBlockLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `file_id: string | null`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `CitationsWebSearchResultLocation`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `CitationsSearchResultLocation`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `text: string`
- `type: "text"`
- `"text"`
- `ThinkingBlock`
- `signature: string`
- `thinking: string`
- `type: "thinking"`
- `"thinking"`
- `RedactedThinkingBlock`
- `data: string`
- `type: "redacted_thinking"`
- `"redacted_thinking"`
- `ToolUseBlock`
- `id: string`
- `input: Record`
- `name: string`
- `type: "tool_use"`
- `"tool_use"`
- `ServerToolUseBlock`
- `id: string`
- `input: Record`
- `name: "web_search"`
- `"web_search"`
- `type: "server_tool_use"`
- `"server_tool_use"`
- `WebSearchToolResultBlock`
- `content: WebSearchToolResultBlockContent`
- `WebSearchToolResultError`
- `error_code: "invalid_tool_input" | "unavailable" | "max_uses_exceeded" | 3 more`
- `"invalid_tool_input"`
- `"unavailable"`
- `"max_uses_exceeded"`
- `"too_many_requests"`
- `"query_too_long"`
- `"request_too_large"`
- `type: "web_search_tool_result_error"`
- `"web_search_tool_result_error"`
- `Array`
- `encrypted_content: string`
- `page_age: string | null`
- `title: string`
- `type: "web_search_result"`
- `"web_search_result"`
- `url: string`
- `tool_use_id: string`
- `type: "web_search_tool_result"`
- `"web_search_tool_result"`
- `model: Model`
The model that will complete your prompt.
See [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options.
- `"claude-opus-4-5-20251101" | "claude-opus-4-5" | "claude-3-7-sonnet-latest" | 17 more`
- `"claude-opus-4-5-20251101"`
Premium model combining maximum intelligence with practical performance
- `"claude-opus-4-5"`
Premium model combining maximum intelligence with practical performance
- `"claude-3-7-sonnet-latest"`
High-performance model with early extended thinking
- `"claude-3-7-sonnet-20250219"`
High-performance model with early extended thinking
- `"claude-3-5-haiku-latest"`
Fastest and most compact model for near-instant responsiveness
- `"claude-3-5-haiku-20241022"`
Our fastest model
- `"claude-haiku-4-5"`
Hybrid model, capable of near-instant responses and extended thinking
- `"claude-haiku-4-5-20251001"`
Hybrid model, capable of near-instant responses and extended thinking
- `"claude-sonnet-4-20250514"`
High-performance model with extended thinking
- `"claude-sonnet-4-0"`
High-performance model with extended thinking
- `"claude-4-sonnet-20250514"`
High-performance model with extended thinking
- `"claude-sonnet-4-5"`
Our best model for real-world agents and coding
- `"claude-sonnet-4-5-20250929"`
Our best model for real-world agents and coding
- `"claude-opus-4-0"`
Our most capable model
- `"claude-opus-4-20250514"`
Our most capable model
- `"claude-4-opus-20250514"`
Our most capable model
- `"claude-opus-4-1-20250805"`
Our most capable model
- `"claude-3-opus-latest"`
Excels at writing and complex tasks
- `"claude-3-opus-20240229"`
Excels at writing and complex tasks
- `"claude-3-haiku-20240307"`
Our previous most fast and cost-effective
- `(string & {})`
- `role: "assistant"`
Conversational role of the generated message.
This will always be `"assistant"`.
- `"assistant"`
- `stop_reason: StopReason | null`
The reason that we stopped.
This may be one the following values:
* `"end_turn"`: the model reached a natural stopping point
* `"max_tokens"`: we exceeded the requested `max_tokens` or the model's maximum
* `"stop_sequence"`: one of your provided custom `stop_sequences` was generated
* `"tool_use"`: the model invoked one or more tools
* `"pause_turn"`: we paused a long-running turn. You may provide the response back as-is in a subsequent request to let the model continue.
* `"refusal"`: when streaming classifiers intervene to handle potential policy violations
In non-streaming mode this value is always non-null. In streaming mode, it is null in the `message_start` event and non-null otherwise.
- `"end_turn"`
- `"max_tokens"`
- `"stop_sequence"`
- `"tool_use"`
- `"pause_turn"`
- `"refusal"`
- `stop_sequence: string | null`
Which custom stop sequence was generated, if any.
This value will be a non-null string if one of your custom stop sequences was generated.
- `type: "message"`
Object type.
For Messages, this is always `"message"`.
- `"message"`
- `usage: Usage`
Billing and rate-limit usage.
Anthropic's API bills and rate-limits by token counts, as tokens represent the underlying cost to our systems.
Under the hood, the API transforms requests into a format suitable for the model. The model's output then goes through a parsing stage before becoming an API response. As a result, the token counts in `usage` will not match one-to-one with the exact visible content of an API request or response.
For example, `output_tokens` will be non-zero, even for an empty string response from Claude.
Total input tokens in a request is the summation of `input_tokens`, `cache_creation_input_tokens`, and `cache_read_input_tokens`.
- `cache_creation: CacheCreation | null`
Breakdown of cached tokens by TTL
- `ephemeral_1h_input_tokens: number`
The number of input tokens used to create the 1 hour cache entry.
- `ephemeral_5m_input_tokens: number`
The number of input tokens used to create the 5 minute cache entry.
- `cache_creation_input_tokens: number | null`
The number of input tokens used to create the cache entry.
- `cache_read_input_tokens: number | null`
The number of input tokens read from the cache.
- `input_tokens: number`
The number of input tokens which were used.
- `output_tokens: number`
The number of output tokens which were used.
- `server_tool_use: ServerToolUsage | null`
The number of server tool requests.
- `web_search_requests: number`
The number of web search tool requests.
- `service_tier: "standard" | "priority" | "batch" | null`
If the request used the priority, standard, or batch tier.
- `"standard"`
- `"priority"`
- `"batch"`
- `type: "succeeded"`
- `"succeeded"`
- `MessageBatchErroredResult`
- `error: ErrorResponse`
- `error: ErrorObject`
- `InvalidRequestError`
- `message: string`
- `type: "invalid_request_error"`
- `"invalid_request_error"`
- `AuthenticationError`
- `message: string`
- `type: "authentication_error"`
- `"authentication_error"`
- `BillingError`
- `message: string`
- `type: "billing_error"`
- `"billing_error"`
- `PermissionError`
- `message: string`
- `type: "permission_error"`
- `"permission_error"`
- `NotFoundError`
- `message: string`
- `type: "not_found_error"`
- `"not_found_error"`
- `RateLimitError`
- `message: string`
- `type: "rate_limit_error"`
- `"rate_limit_error"`
- `GatewayTimeoutError`
- `message: string`
- `type: "timeout_error"`
- `"timeout_error"`
- `APIErrorObject`
- `message: string`
- `type: "api_error"`
- `"api_error"`
- `OverloadedError`
- `message: string`
- `type: "overloaded_error"`
- `"overloaded_error"`
- `request_id: string | null`
- `type: "error"`
- `"error"`
- `type: "errored"`
- `"errored"`
- `MessageBatchCanceledResult`
- `type: "canceled"`
- `"canceled"`
- `MessageBatchExpiredResult`
- `type: "expired"`
- `"expired"`
### Message Batch Succeeded Result
- `MessageBatchSucceededResult`
- `message: Message`
- `id: string`
Unique object identifier.
The format and length of IDs may change over time.
- `content: Array`
Content generated by the model.
This is an array of content blocks, each of which has a `type` that determines its shape.
Example:
```json
[{"type": "text", "text": "Hi, I'm Claude."}]
```
If the request input `messages` ended with an `assistant` turn, then the response `content` will continue directly from that last turn. You can use this to constrain the model's output.
For example, if the input `messages` were:
```json
[
{"role": "user", "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"},
{"role": "assistant", "content": "The best answer is ("}
]
```
Then the response `content` might be:
```json
[{"type": "text", "text": "B)"}]
```
- `TextBlock`
- `citations: Array | null`
Citations supporting the text block.
The type of citation returned will depend on the type of document being cited. Citing a PDF results in `page_location`, plain text results in `char_location`, and content document results in `content_block_location`.
- `CitationCharLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `file_id: string | null`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `CitationPageLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `file_id: string | null`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `CitationContentBlockLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `file_id: string | null`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `CitationsWebSearchResultLocation`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `CitationsSearchResultLocation`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `text: string`
- `type: "text"`
- `"text"`
- `ThinkingBlock`
- `signature: string`
- `thinking: string`
- `type: "thinking"`
- `"thinking"`
- `RedactedThinkingBlock`
- `data: string`
- `type: "redacted_thinking"`
- `"redacted_thinking"`
- `ToolUseBlock`
- `id: string`
- `input: Record`
- `name: string`
- `type: "tool_use"`
- `"tool_use"`
- `ServerToolUseBlock`
- `id: string`
- `input: Record`
- `name: "web_search"`
- `"web_search"`
- `type: "server_tool_use"`
- `"server_tool_use"`
- `WebSearchToolResultBlock`
- `content: WebSearchToolResultBlockContent`
- `WebSearchToolResultError`
- `error_code: "invalid_tool_input" | "unavailable" | "max_uses_exceeded" | 3 more`
- `"invalid_tool_input"`
- `"unavailable"`
- `"max_uses_exceeded"`
- `"too_many_requests"`
- `"query_too_long"`
- `"request_too_large"`
- `type: "web_search_tool_result_error"`
- `"web_search_tool_result_error"`
- `Array`
- `encrypted_content: string`
- `page_age: string | null`
- `title: string`
- `type: "web_search_result"`
- `"web_search_result"`
- `url: string`
- `tool_use_id: string`
- `type: "web_search_tool_result"`
- `"web_search_tool_result"`
- `model: Model`
The model that will complete your prompt.
See [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options.
- `"claude-opus-4-5-20251101" | "claude-opus-4-5" | "claude-3-7-sonnet-latest" | 17 more`
- `"claude-opus-4-5-20251101"`
Premium model combining maximum intelligence with practical performance
- `"claude-opus-4-5"`
Premium model combining maximum intelligence with practical performance
- `"claude-3-7-sonnet-latest"`
High-performance model with early extended thinking
- `"claude-3-7-sonnet-20250219"`
High-performance model with early extended thinking
- `"claude-3-5-haiku-latest"`
Fastest and most compact model for near-instant responsiveness
- `"claude-3-5-haiku-20241022"`
Our fastest model
- `"claude-haiku-4-5"`
Hybrid model, capable of near-instant responses and extended thinking
- `"claude-haiku-4-5-20251001"`
Hybrid model, capable of near-instant responses and extended thinking
- `"claude-sonnet-4-20250514"`
High-performance model with extended thinking
- `"claude-sonnet-4-0"`
High-performance model with extended thinking
- `"claude-4-sonnet-20250514"`
High-performance model with extended thinking
- `"claude-sonnet-4-5"`
Our best model for real-world agents and coding
- `"claude-sonnet-4-5-20250929"`
Our best model for real-world agents and coding
- `"claude-opus-4-0"`
Our most capable model
- `"claude-opus-4-20250514"`
Our most capable model
- `"claude-4-opus-20250514"`
Our most capable model
- `"claude-opus-4-1-20250805"`
Our most capable model
- `"claude-3-opus-latest"`
Excels at writing and complex tasks
- `"claude-3-opus-20240229"`
Excels at writing and complex tasks
- `"claude-3-haiku-20240307"`
Our previous most fast and cost-effective
- `(string & {})`
- `role: "assistant"`
Conversational role of the generated message.
This will always be `"assistant"`.
- `"assistant"`
- `stop_reason: StopReason | null`
The reason that we stopped.
This may be one the following values:
* `"end_turn"`: the model reached a natural stopping point
* `"max_tokens"`: we exceeded the requested `max_tokens` or the model's maximum
* `"stop_sequence"`: one of your provided custom `stop_sequences` was generated
* `"tool_use"`: the model invoked one or more tools
* `"pause_turn"`: we paused a long-running turn. You may provide the response back as-is in a subsequent request to let the model continue.
* `"refusal"`: when streaming classifiers intervene to handle potential policy violations
In non-streaming mode this value is always non-null. In streaming mode, it is null in the `message_start` event and non-null otherwise.
- `"end_turn"`
- `"max_tokens"`
- `"stop_sequence"`
- `"tool_use"`
- `"pause_turn"`
- `"refusal"`
- `stop_sequence: string | null`
Which custom stop sequence was generated, if any.
This value will be a non-null string if one of your custom stop sequences was generated.
- `type: "message"`
Object type.
For Messages, this is always `"message"`.
- `"message"`
- `usage: Usage`
Billing and rate-limit usage.
Anthropic's API bills and rate-limits by token counts, as tokens represent the underlying cost to our systems.
Under the hood, the API transforms requests into a format suitable for the model. The model's output then goes through a parsing stage before becoming an API response. As a result, the token counts in `usage` will not match one-to-one with the exact visible content of an API request or response.
For example, `output_tokens` will be non-zero, even for an empty string response from Claude.
Total input tokens in a request is the summation of `input_tokens`, `cache_creation_input_tokens`, and `cache_read_input_tokens`.
- `cache_creation: CacheCreation | null`
Breakdown of cached tokens by TTL
- `ephemeral_1h_input_tokens: number`
The number of input tokens used to create the 1 hour cache entry.
- `ephemeral_5m_input_tokens: number`
The number of input tokens used to create the 5 minute cache entry.
- `cache_creation_input_tokens: number | null`
The number of input tokens used to create the cache entry.
- `cache_read_input_tokens: number | null`
The number of input tokens read from the cache.
- `input_tokens: number`
The number of input tokens which were used.
- `output_tokens: number`
The number of output tokens which were used.
- `server_tool_use: ServerToolUsage | null`
The number of server tool requests.
- `web_search_requests: number`
The number of web search tool requests.
- `service_tier: "standard" | "priority" | "batch" | null`
If the request used the priority, standard, or batch tier.
- `"standard"`
- `"priority"`
- `"batch"`
- `type: "succeeded"`
- `"succeeded"`
---
# Source: https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/be-clear-and-direct.md
# Be clear, direct, and detailed
---
While these tips apply broadly to all Claude models, you can find prompting tips specific to extended thinking models [here](/docs/en/build-with-claude/prompt-engineering/extended-thinking-tips).
When interacting with Claude, think of it as a brilliant but very new employee (with amnesia) who needs explicit instructions. Like any new employee, Claude does not have context on your norms, styles, guidelines, or preferred ways of working.
The more precisely you explain what you want, the better Claude's response will be.
**The golden rule of clear prompting**
Show your prompt to a colleague, ideally someone who has minimal context on the task, and ask them to follow the instructions. If they're confused, Claude will likely be too.
## How to be clear, contextual, and specific
- **Give Claude contextual information:** Just like you might be able to better perform on a task if you knew more context, Claude will perform better if it has more contextual information. Some examples of contextual information:
- What the task results will be used for
- What audience the output is meant for
- What workflow the task is a part of, and where this task belongs in that workflow
- The end goal of the task, or what a successful task completion looks like
- **Be specific about what you want Claude to do:** For example, if you want Claude to output only code and nothing else, say so.
- **Provide instructions as sequential steps:** Use numbered lists or bullet points to better ensure that Claude carries out the task the exact way you want it to.
### Examples
Notice that Claude still makes mistakes in the unclear prompting example, such as leaving in a customer's name.
| Role | Unclear Prompt | Clear Prompt |
| --- | --- | --- |
| User | Please remove all personally identifiable information from these customer feedback messages: \{\{FEEDBACK_DATA\}\} | Your task is to anonymize customer feedback for our quarterly review.
Instructions:
1. Replace all customer names with "CUSTOMER_[ID]" (e.g., "Jane Doe" → "CUSTOMER_001").
2. Replace email addresses with "EMAIL_[ID]@example.com".
3. Redact phone numbers as "PHONE_[ID]".
4. If a message mentions a specific product (e.g., "AcmeCloud"), leave it intact.
5. If no PII is found, copy the message verbatim.
6. Output only the processed messages, separated by "---".
Data to process: \{\{FEEDBACK_DATA\}\} |
| Assistant (Claude's response) | Here are the anonymized customer feedback messages:
1. I've been using your software for years, and it's been great. But lately, AcmeCloud has been crashing a lot. Fix it!
2. XXX, your customer support rep, was incredibly helpful. He guided me through the whole process. My email is XXX if you want to send a survey.
3. I'm John Smith, and I'm not happy. I've been on hold for 2 hours trying to reach someone at XXX. This is unacceptable! | CUSTOMER_001: I've been using your software for years, and it's been great. But lately, AcmeCloud has been crashing a lot. Fix it!
---
CUSTOMER_002: CUSTOMER_SERVICE_001, your customer support rep, was incredibly helpful. He guided me through the whole process. My email is EMAIL_002@example.com if you want to send a survey.
---
CUSTOMER_003: I'm CUSTOMER_003, and I'm not happy. I've been on hold for 2 hours trying to reach someone at PHONE_001. This is unacceptable! |
Notice that Claude makes up details to fill in the gaps where it lacks context with the vague prompt.
| Role | Vague Prompt | Specific Prompt |
| --- | --- | --- |
| User | Write a marketing email for our new AcmeCloud features. | Your task is to craft a targeted marketing email for our Q3 AcmeCloud feature release.
Instructions:
1. Write for this target audience: Mid-size tech companies (100-500 employees) upgrading from on-prem to cloud.
2. Highlight 3 key new features: advanced data encryption, cross-platform sync, and real-time collaboration.
3. Tone: Professional yet approachable. Emphasize security, efficiency, and teamwork.
4. Include a clear CTA: Free 30-day trial with priority onboarding.
5. Subject line: Under 50 chars, mention "security" and "collaboration".
6. Personalization: Use \{\{COMPANY_NAME\}\} and \{\{CONTACT_NAME\}\} variables.
Structure:
1. Subject line
2. Email body (150-200 words)
3. CTA button text |
| Assistant (Claude's response) | Here's a draft marketing email for our new features:
Subject: Boost Your Business with AcmeCloud's Latest Features
Dear Valued Customer,
We're excited to introduce three powerful features to AcmeCloud that will revolutionize your workflow:
1. Real-Time Collaboration: Work on documents simultaneously with your team. No more version control issues!
2. AI-Powered Insights: Make data-driven decisions with AI that analyzes trends and automates tasks.
3. Advanced Security Suite: End-to-end encryption, multi-factor auth, and threat detection keep your data safe.
Limited Offer: Upgrade now for a 20% first-year discount. Plus, refer a friend for an extra 10% off!
Best,
The AcmeCloud Team | Subject line: AcmeCloud: Enterprise security meets real-time teamwork
Email body:
Dear \{\{CONTACT_NAME\}\},
At \{\{COMPANY_NAME\}\}, you're scaling fast and eyeing the cloud. But with growth comes the challenge of keeping data secure while fostering collaboration. That's where AcmeCloud's Q3 release comes in, tailor-made for tech innovators like you.
1. Fort Knox for Your Files: Military-grade encryption now safeguards your data, both in motion and at rest. Your intellectual property stays yours, period.
2. Sync Without Borders: Windows, Mac, or Linux—AcmeCloud speaks all languages. Unified version control means no more "final_v2_REALLY_FINAL.doc".
3. Collaborate at Light Speed: Ditch the attachment ping-pong. Now your devs, designers, and data scientists co-create in real-time, slashing time-to-market.
Don't just take our word for it. Experience the AcmeCloud difference with our 30-day trial. And because we know time is your most precious asset, we're throwing in priority onboarding.
Elevate Your Team Now - Free 30-Day Trial |
Notice that Claude outputs superfluous text and different formating with the vague prompt.
| Role | Vague Prompt | Detailed Prompt |
| --- | --- | --- |
| User | Analyze this AcmeCloud outage report and summarize the key points.
\{\{REPORT\}\} | Analyze this AcmeCloud outage report. Skip the preamble. Keep your response terse and write only the bare bones necessary information. List only:
1) Cause
2) Duration
3) Impacted services
4) Number of affected users
5) Estimated revenue loss.
Here's the report: \{\{REPORT\}\}|
| Assistant (Claude's response) | Here's a summary of the key points from the AcmeCloud outage report:
On May 15th, a misconfigured load balancer update caused significant traffic routing issues, resulting in a service outage from 09:15 to 13:52 UTC. The 4-hour 37-minute disruption impacted our core file syncing service and admin dashboard, rendering them inaccessible. Additionally, the mobile app experienced partial functionality loss. Approximately 68% of our user base, totaling 1.3 million users, were affected. Based on our Service Level Agreements (SLAs) and average revenue per user, we estimate a financial impact of $420,000 in service credits and potential customer churn. | 1) Cause: Misconfigured load balancer update
2) Duration: 4h 37m (09:15-13:52 UTC, May 15)
3) Impacted: Core sync, admin dashboard (down); mobile app (partial)
4) Affected users: 1.3M (68% of base)
5) Est. revenue loss: $420,000 |
***
Get inspired by a curated selection of prompts for various tasks and use cases.
An example-filled tutorial that covers the prompt engineering concepts found in our docs.
A lighter weight version of our prompt engineering tutorial via an interactive spreadsheet.
---
# Source: https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices.md
# Skill authoring best practices
Learn how to write effective Skills that Claude can discover and use successfully.
---
Good Skills are concise, well-structured, and tested with real usage. This guide provides practical authoring decisions to help you write Skills that Claude can discover and use effectively.
For conceptual background on how Skills work, see the [Skills overview](/docs/en/agents-and-tools/agent-skills/overview).
## Core principles
### Concise is key
The [context window](/docs/en/build-with-claude/context-windows) is a public good. Your Skill shares the context window with everything else Claude needs to know, including:
- The system prompt
- Conversation history
- Other Skills' metadata
- Your actual request
Not every token in your Skill has an immediate cost. At startup, only the metadata (name and description) from all Skills is pre-loaded. Claude reads SKILL.md only when the Skill becomes relevant, and reads additional files only as needed. However, being concise in SKILL.md still matters: once Claude loads it, every token competes with conversation history and other context.
**Default assumption**: Claude is already very smart
Only add context Claude doesn't already have. Challenge each piece of information:
- "Does Claude really need this explanation?"
- "Can I assume Claude knows this?"
- "Does this paragraph justify its token cost?"
**Good example: Concise** (approximately 50 tokens):
````markdown
## Extract PDF text
Use pdfplumber for text extraction:
```python
import pdfplumber
with pdfplumber.open("file.pdf") as pdf:
text = pdf.pages[0].extract_text()
```
````
**Bad example: Too verbose** (approximately 150 tokens):
```markdown
## Extract PDF text
PDF (Portable Document Format) files are a common file format that contains
text, images, and other content. To extract text from a PDF, you'll need to
use a library. There are many libraries available for PDF processing, but we
recommend pdfplumber because it's easy to use and handles most cases well.
First, you'll need to install it using pip. Then you can use the code below...
```
The concise version assumes Claude knows what PDFs are and how libraries work.
### Set appropriate degrees of freedom
Match the level of specificity to the task's fragility and variability.
**High freedom** (text-based instructions):
Use when:
- Multiple approaches are valid
- Decisions depend on context
- Heuristics guide the approach
Example:
```markdown
## Code review process
1. Analyze the code structure and organization
2. Check for potential bugs or edge cases
3. Suggest improvements for readability and maintainability
4. Verify adherence to project conventions
```
**Medium freedom** (pseudocode or scripts with parameters):
Use when:
- A preferred pattern exists
- Some variation is acceptable
- Configuration affects behavior
Example:
````markdown
## Generate report
Use this template and customize as needed:
```python
def generate_report(data, format="markdown", include_charts=True):
# Process data
# Generate output in specified format
# Optionally include visualizations
```
````
**Low freedom** (specific scripts, few or no parameters):
Use when:
- Operations are fragile and error-prone
- Consistency is critical
- A specific sequence must be followed
Example:
````markdown
## Database migration
Run exactly this script:
```bash
python scripts/migrate.py --verify --backup
```
Do not modify the command or add additional flags.
````
**Analogy**: Think of Claude as a robot exploring a path:
- **Narrow bridge with cliffs on both sides**: There's only one safe way forward. Provide specific guardrails and exact instructions (low freedom). Example: database migrations that must run in exact sequence.
- **Open field with no hazards**: Many paths lead to success. Give general direction and trust Claude to find the best route (high freedom). Example: code reviews where context determines the best approach.
### Test with all models you plan to use
Skills act as additions to models, so effectiveness depends on the underlying model. Test your Skill with all the models you plan to use it with.
**Testing considerations by model**:
- **Claude Haiku** (fast, economical): Does the Skill provide enough guidance?
- **Claude Sonnet** (balanced): Is the Skill clear and efficient?
- **Claude Opus** (powerful reasoning): Does the Skill avoid over-explaining?
What works perfectly for Opus might need more detail for Haiku. If you plan to use your Skill across multiple models, aim for instructions that work well with all of them.
## Skill structure
**YAML Frontmatter**: The SKILL.md frontmatter requires two fields:
`name`:
- Maximum 64 characters
- Must contain only lowercase letters, numbers, and hyphens
- Cannot contain XML tags
- Cannot contain reserved words: "anthropic", "claude"
`description`:
- Must be non-empty
- Maximum 1024 characters
- Cannot contain XML tags
- Should describe what the Skill does and when to use it
For complete Skill structure details, see the [Skills overview](/docs/en/agents-and-tools/agent-skills/overview#skill-structure).
### Naming conventions
Use consistent naming patterns to make Skills easier to reference and discuss. We recommend using **gerund form** (verb + -ing) for Skill names, as this clearly describes the activity or capability the Skill provides.
Remember that the `name` field must use lowercase letters, numbers, and hyphens only.
**Good naming examples (gerund form)**:
- `processing-pdfs`
- `analyzing-spreadsheets`
- `managing-databases`
- `testing-code`
- `writing-documentation`
**Acceptable alternatives**:
- Noun phrases: `pdf-processing`, `spreadsheet-analysis`
- Action-oriented: `process-pdfs`, `analyze-spreadsheets`
**Avoid**:
- Vague names: `helper`, `utils`, `tools`
- Overly generic: `documents`, `data`, `files`
- Reserved words: `anthropic-helper`, `claude-tools`
- Inconsistent patterns within your skill collection
Consistent naming makes it easier to:
- Reference Skills in documentation and conversations
- Understand what a Skill does at a glance
- Organize and search through multiple Skills
- Maintain a professional, cohesive skill library
### Writing effective descriptions
The `description` field enables Skill discovery and should include both what the Skill does and when to use it.
**Always write in third person**. The description is injected into the system prompt, and inconsistent point-of-view can cause discovery problems.
- **Good:** "Processes Excel files and generates reports"
- **Avoid:** "I can help you process Excel files"
- **Avoid:** "You can use this to process Excel files"
**Be specific and include key terms**. Include both what the Skill does and specific triggers/contexts for when to use it.
Each Skill has exactly one description field. The description is critical for skill selection: Claude uses it to choose the right Skill from potentially 100+ available Skills. Your description must provide enough detail for Claude to know when to select this Skill, while the rest of SKILL.md provides the implementation details.
Effective examples:
**PDF Processing skill:**
```yaml
description: Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction.
```
**Excel Analysis skill:**
```yaml
description: Analyze Excel spreadsheets, create pivot tables, generate charts. Use when analyzing Excel files, spreadsheets, tabular data, or .xlsx files.
```
**Git Commit Helper skill:**
```yaml
description: Generate descriptive commit messages by analyzing git diffs. Use when the user asks for help writing commit messages or reviewing staged changes.
```
Avoid vague descriptions like these:
```yaml
description: Helps with documents
```
```yaml
description: Processes data
```
```yaml
description: Does stuff with files
```
### Progressive disclosure patterns
SKILL.md serves as an overview that points Claude to detailed materials as needed, like a table of contents in an onboarding guide. For an explanation of how progressive disclosure works, see [How Skills work](/docs/en/agents-and-tools/agent-skills/overview#how-skills-work) in the overview.
**Practical guidance:**
- Keep SKILL.md body under 500 lines for optimal performance
- Split content into separate files when approaching this limit
- Use the patterns below to organize instructions, code, and resources effectively
#### Visual overview: From simple to complex
A basic Skill starts with just a SKILL.md file containing metadata and instructions:

As your Skill grows, you can bundle additional content that Claude loads only when needed:

The complete Skill directory structure might look like this:
```
pdf/
├── SKILL.md # Main instructions (loaded when triggered)
├── FORMS.md # Form-filling guide (loaded as needed)
├── reference.md # API reference (loaded as needed)
├── examples.md # Usage examples (loaded as needed)
└── scripts/
├── analyze_form.py # Utility script (executed, not loaded)
├── fill_form.py # Form filling script
└── validate.py # Validation script
```
#### Pattern 1: High-level guide with references
````markdown
---
name: pdf-processing
description: Extracts text and tables from PDF files, fills forms, and merges documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction.
---
# PDF Processing
## Quick start
Extract text with pdfplumber:
```python
import pdfplumber
with pdfplumber.open("file.pdf") as pdf:
text = pdf.pages[0].extract_text()
```
## Advanced features
**Form filling**: See [FORMS.md](FORMS.md) for complete guide
**API reference**: See [REFERENCE.md](REFERENCE.md) for all methods
**Examples**: See [EXAMPLES.md](EXAMPLES.md) for common patterns
````
Claude loads FORMS.md, REFERENCE.md, or EXAMPLES.md only when needed.
#### Pattern 2: Domain-specific organization
For Skills with multiple domains, organize content by domain to avoid loading irrelevant context. When a user asks about sales metrics, Claude only needs to read sales-related schemas, not finance or marketing data. This keeps token usage low and context focused.
```
bigquery-skill/
├── SKILL.md (overview and navigation)
└── reference/
├── finance.md (revenue, billing metrics)
├── sales.md (opportunities, pipeline)
├── product.md (API usage, features)
└── marketing.md (campaigns, attribution)
```
````markdown SKILL.md
# BigQuery Data Analysis
## Available datasets
**Finance**: Revenue, ARR, billing → See [reference/finance.md](reference/finance.md)
**Sales**: Opportunities, pipeline, accounts → See [reference/sales.md](reference/sales.md)
**Product**: API usage, features, adoption → See [reference/product.md](reference/product.md)
**Marketing**: Campaigns, attribution, email → See [reference/marketing.md](reference/marketing.md)
## Quick search
Find specific metrics using grep:
```bash
grep -i "revenue" reference/finance.md
grep -i "pipeline" reference/sales.md
grep -i "api usage" reference/product.md
```
````
#### Pattern 3: Conditional details
Show basic content, link to advanced content:
```markdown
# DOCX Processing
## Creating documents
Use docx-js for new documents. See [DOCX-JS.md](DOCX-JS.md).
## Editing documents
For simple edits, modify the XML directly.
**For tracked changes**: See [REDLINING.md](REDLINING.md)
**For OOXML details**: See [OOXML.md](OOXML.md)
```
Claude reads REDLINING.md or OOXML.md only when the user needs those features.
### Avoid deeply nested references
Claude may partially read files when they're referenced from other referenced files. When encountering nested references, Claude might use commands like `head -100` to preview content rather than reading entire files, resulting in incomplete information.
**Keep references one level deep from SKILL.md**. All reference files should link directly from SKILL.md to ensure Claude reads complete files when needed.
**Bad example: Too deep**:
```markdown
# SKILL.md
See [advanced.md](advanced.md)...
# advanced.md
See [details.md](details.md)...
# details.md
Here's the actual information...
```
**Good example: One level deep**:
```markdown
# SKILL.md
**Basic usage**: [instructions in SKILL.md]
**Advanced features**: See [advanced.md](advanced.md)
**API reference**: See [reference.md](reference.md)
**Examples**: See [examples.md](examples.md)
```
### Structure longer reference files with table of contents
For reference files longer than 100 lines, include a table of contents at the top. This ensures Claude can see the full scope of available information even when previewing with partial reads.
**Example**:
```markdown
# API Reference
## Contents
- Authentication and setup
- Core methods (create, read, update, delete)
- Advanced features (batch operations, webhooks)
- Error handling patterns
- Code examples
## Authentication and setup
...
## Core methods
...
```
Claude can then read the complete file or jump to specific sections as needed.
For details on how this filesystem-based architecture enables progressive disclosure, see the [Runtime environment](#runtime-environment) section in the Advanced section below.
## Workflows and feedback loops
### Use workflows for complex tasks
Break complex operations into clear, sequential steps. For particularly complex workflows, provide a checklist that Claude can copy into its response and check off as it progresses.
**Example 1: Research synthesis workflow** (for Skills without code):
````markdown
## Research synthesis workflow
Copy this checklist and track your progress:
```
Research Progress:
- [ ] Step 1: Read all source documents
- [ ] Step 2: Identify key themes
- [ ] Step 3: Cross-reference claims
- [ ] Step 4: Create structured summary
- [ ] Step 5: Verify citations
```
**Step 1: Read all source documents**
Review each document in the `sources/` directory. Note the main arguments and supporting evidence.
**Step 2: Identify key themes**
Look for patterns across sources. What themes appear repeatedly? Where do sources agree or disagree?
**Step 3: Cross-reference claims**
For each major claim, verify it appears in the source material. Note which source supports each point.
**Step 4: Create structured summary**
Organize findings by theme. Include:
- Main claim
- Supporting evidence from sources
- Conflicting viewpoints (if any)
**Step 5: Verify citations**
Check that every claim references the correct source document. If citations are incomplete, return to Step 3.
````
This example shows how workflows apply to analysis tasks that don't require code. The checklist pattern works for any complex, multi-step process.
**Example 2: PDF form filling workflow** (for Skills with code):
````markdown
## PDF form filling workflow
Copy this checklist and check off items as you complete them:
```
Task Progress:
- [ ] Step 1: Analyze the form (run analyze_form.py)
- [ ] Step 2: Create field mapping (edit fields.json)
- [ ] Step 3: Validate mapping (run validate_fields.py)
- [ ] Step 4: Fill the form (run fill_form.py)
- [ ] Step 5: Verify output (run verify_output.py)
```
**Step 1: Analyze the form**
Run: `python scripts/analyze_form.py input.pdf`
This extracts form fields and their locations, saving to `fields.json`.
**Step 2: Create field mapping**
Edit `fields.json` to add values for each field.
**Step 3: Validate mapping**
Run: `python scripts/validate_fields.py fields.json`
Fix any validation errors before continuing.
**Step 4: Fill the form**
Run: `python scripts/fill_form.py input.pdf fields.json output.pdf`
**Step 5: Verify output**
Run: `python scripts/verify_output.py output.pdf`
If verification fails, return to Step 2.
````
Clear steps prevent Claude from skipping critical validation. The checklist helps both Claude and you track progress through multi-step workflows.
### Implement feedback loops
**Common pattern**: Run validator → fix errors → repeat
This pattern greatly improves output quality.
**Example 1: Style guide compliance** (for Skills without code):
```markdown
## Content review process
1. Draft your content following the guidelines in STYLE_GUIDE.md
2. Review against the checklist:
- Check terminology consistency
- Verify examples follow the standard format
- Confirm all required sections are present
3. If issues found:
- Note each issue with specific section reference
- Revise the content
- Review the checklist again
4. Only proceed when all requirements are met
5. Finalize and save the document
```
This shows the validation loop pattern using reference documents instead of scripts. The "validator" is STYLE_GUIDE.md, and Claude performs the check by reading and comparing.
**Example 2: Document editing process** (for Skills with code):
```markdown
## Document editing process
1. Make your edits to `word/document.xml`
2. **Validate immediately**: `python ooxml/scripts/validate.py unpacked_dir/`
3. If validation fails:
- Review the error message carefully
- Fix the issues in the XML
- Run validation again
4. **Only proceed when validation passes**
5. Rebuild: `python ooxml/scripts/pack.py unpacked_dir/ output.docx`
6. Test the output document
```
The validation loop catches errors early.
## Content guidelines
### Avoid time-sensitive information
Don't include information that will become outdated:
**Bad example: Time-sensitive** (will become wrong):
```markdown
If you're doing this before August 2025, use the old API.
After August 2025, use the new API.
```
**Good example** (use "old patterns" section):
```markdown
## Current method
Use the v2 API endpoint: `api.example.com/v2/messages`
## Old patterns
Legacy v1 API (deprecated 2025-08)
The v1 API used: `api.example.com/v1/messages`
This endpoint is no longer supported.
```
The old patterns section provides historical context without cluttering the main content.
### Use consistent terminology
Choose one term and use it throughout the Skill:
**Good - Consistent**:
- Always "API endpoint"
- Always "field"
- Always "extract"
**Bad - Inconsistent**:
- Mix "API endpoint", "URL", "API route", "path"
- Mix "field", "box", "element", "control"
- Mix "extract", "pull", "get", "retrieve"
Consistency helps Claude understand and follow instructions.
## Common patterns
### Template pattern
Provide templates for output format. Match the level of strictness to your needs.
**For strict requirements** (like API responses or data formats):
````markdown
## Report structure
ALWAYS use this exact template structure:
```markdown
# [Analysis Title]
## Executive summary
[One-paragraph overview of key findings]
## Key findings
- Finding 1 with supporting data
- Finding 2 with supporting data
- Finding 3 with supporting data
## Recommendations
1. Specific actionable recommendation
2. Specific actionable recommendation
```
````
**For flexible guidance** (when adaptation is useful):
````markdown
## Report structure
Here is a sensible default format, but use your best judgment based on the analysis:
```markdown
# [Analysis Title]
## Executive summary
[Overview]
## Key findings
[Adapt sections based on what you discover]
## Recommendations
[Tailor to the specific context]
```
Adjust sections as needed for the specific analysis type.
````
### Examples pattern
For Skills where output quality depends on seeing examples, provide input/output pairs just like in regular prompting:
````markdown
## Commit message format
Generate commit messages following these examples:
**Example 1:**
Input: Added user authentication with JWT tokens
Output:
```
feat(auth): implement JWT-based authentication
Add login endpoint and token validation middleware
```
**Example 2:**
Input: Fixed bug where dates displayed incorrectly in reports
Output:
```
fix(reports): correct date formatting in timezone conversion
Use UTC timestamps consistently across report generation
```
**Example 3:**
Input: Updated dependencies and refactored error handling
Output:
```
chore: update dependencies and refactor error handling
- Upgrade lodash to 4.17.21
- Standardize error response format across endpoints
```
Follow this style: type(scope): brief description, then detailed explanation.
````
Examples help Claude understand the desired style and level of detail more clearly than descriptions alone.
### Conditional workflow pattern
Guide Claude through decision points:
```markdown
## Document modification workflow
1. Determine the modification type:
**Creating new content?** → Follow "Creation workflow" below
**Editing existing content?** → Follow "Editing workflow" below
2. Creation workflow:
- Use docx-js library
- Build document from scratch
- Export to .docx format
3. Editing workflow:
- Unpack existing document
- Modify XML directly
- Validate after each change
- Repack when complete
```
If workflows become large or complicated with many steps, consider pushing them into separate files and tell Claude to read the appropriate file based on the task at hand.
## Evaluation and iteration
### Build evaluations first
**Create evaluations BEFORE writing extensive documentation.** This ensures your Skill solves real problems rather than documenting imagined ones.
**Evaluation-driven development:**
1. **Identify gaps**: Run Claude on representative tasks without a Skill. Document specific failures or missing context
2. **Create evaluations**: Build three scenarios that test these gaps
3. **Establish baseline**: Measure Claude's performance without the Skill
4. **Write minimal instructions**: Create just enough content to address the gaps and pass evaluations
5. **Iterate**: Execute evaluations, compare against baseline, and refine
This approach ensures you're solving actual problems rather than anticipating requirements that may never materialize.
**Evaluation structure**:
```json
{
"skills": ["pdf-processing"],
"query": "Extract all text from this PDF file and save it to output.txt",
"files": ["test-files/document.pdf"],
"expected_behavior": [
"Successfully reads the PDF file using an appropriate PDF processing library or command-line tool",
"Extracts text content from all pages in the document without missing any pages",
"Saves the extracted text to a file named output.txt in a clear, readable format"
]
}
```
This example demonstrates a data-driven evaluation with a simple testing rubric. We do not currently provide a built-in way to run these evaluations. Users can create their own evaluation system. Evaluations are your source of truth for measuring Skill effectiveness.
### Develop Skills iteratively with Claude
The most effective Skill development process involves Claude itself. Work with one instance of Claude ("Claude A") to create a Skill that will be used by other instances ("Claude B"). Claude A helps you design and refine instructions, while Claude B tests them in real tasks. This works because Claude models understand both how to write effective agent instructions and what information agents need.
**Creating a new Skill:**
1. **Complete a task without a Skill**: Work through a problem with Claude A using normal prompting. As you work, you'll naturally provide context, explain preferences, and share procedural knowledge. Notice what information you repeatedly provide.
2. **Identify the reusable pattern**: After completing the task, identify what context you provided that would be useful for similar future tasks.
**Example**: If you worked through a BigQuery analysis, you might have provided table names, field definitions, filtering rules (like "always exclude test accounts"), and common query patterns.
3. **Ask Claude A to create a Skill**: "Create a Skill that captures this BigQuery analysis pattern we just used. Include the table schemas, naming conventions, and the rule about filtering test accounts."
Claude models understand the Skill format and structure natively. You don't need special system prompts or a "writing skills" skill to get Claude to help create Skills. Simply ask Claude to create a Skill and it will generate properly structured SKILL.md content with appropriate frontmatter and body content.
4. **Review for conciseness**: Check that Claude A hasn't added unnecessary explanations. Ask: "Remove the explanation about what win rate means - Claude already knows that."
5. **Improve information architecture**: Ask Claude A to organize the content more effectively. For example: "Organize this so the table schema is in a separate reference file. We might add more tables later."
6. **Test on similar tasks**: Use the Skill with Claude B (a fresh instance with the Skill loaded) on related use cases. Observe whether Claude B finds the right information, applies rules correctly, and handles the task successfully.
7. **Iterate based on observation**: If Claude B struggles or misses something, return to Claude A with specifics: "When Claude used this Skill, it forgot to filter by date for Q4. Should we add a section about date filtering patterns?"
**Iterating on existing Skills:**
The same hierarchical pattern continues when improving Skills. You alternate between:
- **Working with Claude A** (the expert who helps refine the Skill)
- **Testing with Claude B** (the agent using the Skill to perform real work)
- **Observing Claude B's behavior** and bringing insights back to Claude A
1. **Use the Skill in real workflows**: Give Claude B (with the Skill loaded) actual tasks, not test scenarios
2. **Observe Claude B's behavior**: Note where it struggles, succeeds, or makes unexpected choices
**Example observation**: "When I asked Claude B for a regional sales report, it wrote the query but forgot to filter out test accounts, even though the Skill mentions this rule."
3. **Return to Claude A for improvements**: Share the current SKILL.md and describe what you observed. Ask: "I noticed Claude B forgot to filter test accounts when I asked for a regional report. The Skill mentions filtering, but maybe it's not prominent enough?"
4. **Review Claude A's suggestions**: Claude A might suggest reorganizing to make rules more prominent, using stronger language like "MUST filter" instead of "always filter", or restructuring the workflow section.
5. **Apply and test changes**: Update the Skill with Claude A's refinements, then test again with Claude B on similar requests
6. **Repeat based on usage**: Continue this observe-refine-test cycle as you encounter new scenarios. Each iteration improves the Skill based on real agent behavior, not assumptions.
**Gathering team feedback:**
1. Share Skills with teammates and observe their usage
2. Ask: Does the Skill activate when expected? Are instructions clear? What's missing?
3. Incorporate feedback to address blind spots in your own usage patterns
**Why this approach works**: Claude A understands agent needs, you provide domain expertise, Claude B reveals gaps through real usage, and iterative refinement improves Skills based on observed behavior rather than assumptions.
### Observe how Claude navigates Skills
As you iterate on Skills, pay attention to how Claude actually uses them in practice. Watch for:
- **Unexpected exploration paths**: Does Claude read files in an order you didn't anticipate? This might indicate your structure isn't as intuitive as you thought
- **Missed connections**: Does Claude fail to follow references to important files? Your links might need to be more explicit or prominent
- **Overreliance on certain sections**: If Claude repeatedly reads the same file, consider whether that content should be in the main SKILL.md instead
- **Ignored content**: If Claude never accesses a bundled file, it might be unnecessary or poorly signaled in the main instructions
Iterate based on these observations rather than assumptions. The 'name' and 'description' in your Skill's metadata are particularly critical. Claude uses these when deciding whether to trigger the Skill in response to the current task. Make sure they clearly describe what the Skill does and when it should be used.
## Anti-patterns to avoid
### Avoid Windows-style paths
Always use forward slashes in file paths, even on Windows:
- ✓ **Good**: `scripts/helper.py`, `reference/guide.md`
- ✗ **Avoid**: `scripts\helper.py`, `reference\guide.md`
Unix-style paths work across all platforms, while Windows-style paths cause errors on Unix systems.
### Avoid offering too many options
Don't present multiple approaches unless necessary:
````markdown
**Bad example: Too many choices** (confusing):
"You can use pypdf, or pdfplumber, or PyMuPDF, or pdf2image, or..."
**Good example: Provide a default** (with escape hatch):
"Use pdfplumber for text extraction:
```python
import pdfplumber
```
For scanned PDFs requiring OCR, use pdf2image with pytesseract instead."
````
## Advanced: Skills with executable code
The sections below focus on Skills that include executable scripts. If your Skill uses only markdown instructions, skip to [Checklist for effective Skills](#checklist-for-effective-skills).
### Solve, don't punt
When writing scripts for Skills, handle error conditions rather than punting to Claude.
**Good example: Handle errors explicitly**:
```python
def process_file(path):
"""Process a file, creating it if it doesn't exist."""
try:
with open(path) as f:
return f.read()
except FileNotFoundError:
# Create file with default content instead of failing
print(f"File {path} not found, creating default")
with open(path, 'w') as f:
f.write('')
return ''
except PermissionError:
# Provide alternative instead of failing
print(f"Cannot access {path}, using default")
return ''
```
**Bad example: Punt to Claude**:
```python
def process_file(path):
# Just fail and let Claude figure it out
return open(path).read()
```
Configuration parameters should also be justified and documented to avoid "voodoo constants" (Ousterhout's law). If you don't know the right value, how will Claude determine it?
**Good example: Self-documenting**:
```python
# HTTP requests typically complete within 30 seconds
# Longer timeout accounts for slow connections
REQUEST_TIMEOUT = 30
# Three retries balances reliability vs speed
# Most intermittent failures resolve by the second retry
MAX_RETRIES = 3
```
**Bad example: Magic numbers**:
```python
TIMEOUT = 47 # Why 47?
RETRIES = 5 # Why 5?
```
### Provide utility scripts
Even if Claude could write a script, pre-made scripts offer advantages:
**Benefits of utility scripts**:
- More reliable than generated code
- Save tokens (no need to include code in context)
- Save time (no code generation required)
- Ensure consistency across uses

The diagram above shows how executable scripts work alongside instruction files. The instruction file (forms.md) references the script, and Claude can execute it without loading its contents into context.
**Important distinction**: Make clear in your instructions whether Claude should:
- **Execute the script** (most common): "Run `analyze_form.py` to extract fields"
- **Read it as reference** (for complex logic): "See `analyze_form.py` for the field extraction algorithm"
For most utility scripts, execution is preferred because it's more reliable and efficient. See the [Runtime environment](#runtime-environment) section below for details on how script execution works.
**Example**:
````markdown
## Utility scripts
**analyze_form.py**: Extract all form fields from PDF
```bash
python scripts/analyze_form.py input.pdf > fields.json
```
Output format:
```json
{
"field_name": {"type": "text", "x": 100, "y": 200},
"signature": {"type": "sig", "x": 150, "y": 500}
}
```
**validate_boxes.py**: Check for overlapping bounding boxes
```bash
python scripts/validate_boxes.py fields.json
# Returns: "OK" or lists conflicts
```
**fill_form.py**: Apply field values to PDF
```bash
python scripts/fill_form.py input.pdf fields.json output.pdf
```
````
### Use visual analysis
When inputs can be rendered as images, have Claude analyze them:
````markdown
## Form layout analysis
1. Convert PDF to images:
```bash
python scripts/pdf_to_images.py form.pdf
```
2. Analyze each page image to identify form fields
3. Claude can see field locations and types visually
````
In this example, you'd need to write the `pdf_to_images.py` script.
Claude's vision capabilities help understand layouts and structures.
### Create verifiable intermediate outputs
When Claude performs complex, open-ended tasks, it can make mistakes. The "plan-validate-execute" pattern catches errors early by having Claude first create a plan in a structured format, then validate that plan with a script before executing it.
**Example**: Imagine asking Claude to update 50 form fields in a PDF based on a spreadsheet. Without validation, Claude might reference non-existent fields, create conflicting values, miss required fields, or apply updates incorrectly.
**Solution**: Use the workflow pattern shown above (PDF form filling), but add an intermediate `changes.json` file that gets validated before applying changes. The workflow becomes: analyze → **create plan file** → **validate plan** → execute → verify.
**Why this pattern works:**
- **Catches errors early**: Validation finds problems before changes are applied
- **Machine-verifiable**: Scripts provide objective verification
- **Reversible planning**: Claude can iterate on the plan without touching originals
- **Clear debugging**: Error messages point to specific problems
**When to use**: Batch operations, destructive changes, complex validation rules, high-stakes operations.
**Implementation tip**: Make validation scripts verbose with specific error messages like "Field 'signature_date' not found. Available fields: customer_name, order_total, signature_date_signed" to help Claude fix issues.
### Package dependencies
Skills run in the code execution environment with platform-specific limitations:
- **claude.ai**: Can install packages from npm and PyPI and pull from GitHub repositories
- **Anthropic API**: Has no network access and no runtime package installation
List required packages in your SKILL.md and verify they're available in the [code execution tool documentation](/docs/en/agents-and-tools/tool-use/code-execution-tool).
### Runtime environment
Skills run in a code execution environment with filesystem access, bash commands, and code execution capabilities. For the conceptual explanation of this architecture, see [The Skills architecture](/docs/en/agents-and-tools/agent-skills/overview#the-skills-architecture) in the overview.
**How this affects your authoring:**
**How Claude accesses Skills:**
1. **Metadata pre-loaded**: At startup, the name and description from all Skills' YAML frontmatter are loaded into the system prompt
2. **Files read on-demand**: Claude uses bash Read tools to access SKILL.md and other files from the filesystem when needed
3. **Scripts executed efficiently**: Utility scripts can be executed via bash without loading their full contents into context. Only the script's output consumes tokens
4. **No context penalty for large files**: Reference files, data, or documentation don't consume context tokens until actually read
- **File paths matter**: Claude navigates your skill directory like a filesystem. Use forward slashes (`reference/guide.md`), not backslashes
- **Name files descriptively**: Use names that indicate content: `form_validation_rules.md`, not `doc2.md`
- **Organize for discovery**: Structure directories by domain or feature
- Good: `reference/finance.md`, `reference/sales.md`
- Bad: `docs/file1.md`, `docs/file2.md`
- **Bundle comprehensive resources**: Include complete API docs, extensive examples, large datasets; no context penalty until accessed
- **Prefer scripts for deterministic operations**: Write `validate_form.py` rather than asking Claude to generate validation code
- **Make execution intent clear**:
- "Run `analyze_form.py` to extract fields" (execute)
- "See `analyze_form.py` for the extraction algorithm" (read as reference)
- **Test file access patterns**: Verify Claude can navigate your directory structure by testing with real requests
**Example:**
```
bigquery-skill/
├── SKILL.md (overview, points to reference files)
└── reference/
├── finance.md (revenue metrics)
├── sales.md (pipeline data)
└── product.md (usage analytics)
```
When the user asks about revenue, Claude reads SKILL.md, sees the reference to `reference/finance.md`, and invokes bash to read just that file. The sales.md and product.md files remain on the filesystem, consuming zero context tokens until needed. This filesystem-based model is what enables progressive disclosure. Claude can navigate and selectively load exactly what each task requires.
For complete details on the technical architecture, see [How Skills work](/docs/en/agents-and-tools/agent-skills/overview#how-skills-work) in the Skills overview.
### MCP tool references
If your Skill uses MCP (Model Context Protocol) tools, always use fully qualified tool names to avoid "tool not found" errors.
**Format**: `ServerName:tool_name`
**Example**:
```markdown
Use the BigQuery:bigquery_schema tool to retrieve table schemas.
Use the GitHub:create_issue tool to create issues.
```
Where:
- `BigQuery` and `GitHub` are MCP server names
- `bigquery_schema` and `create_issue` are the tool names within those servers
Without the server prefix, Claude may fail to locate the tool, especially when multiple MCP servers are available.
### Avoid assuming tools are installed
Don't assume packages are available:
````markdown
**Bad example: Assumes installation**:
"Use the pdf library to process the file."
**Good example: Explicit about dependencies**:
"Install required package: `pip install pypdf`
Then use it:
```python
from pypdf import PdfReader
reader = PdfReader("file.pdf")
```"
````
## Technical notes
### YAML frontmatter requirements
The SKILL.md frontmatter requires `name` and `description` fields with specific validation rules:
- `name`: Maximum 64 characters, lowercase letters/numbers/hyphens only, no XML tags, no reserved words
- `description`: Maximum 1024 characters, non-empty, no XML tags
See the [Skills overview](/docs/en/agents-and-tools/agent-skills/overview#skill-structure) for complete structure details.
### Token budgets
Keep SKILL.md body under 500 lines for optimal performance. If your content exceeds this, split it into separate files using the progressive disclosure patterns described earlier. For architectural details, see the [Skills overview](/docs/en/agents-and-tools/agent-skills/overview#how-skills-work).
## Checklist for effective Skills
Before sharing a Skill, verify:
### Core quality
- [ ] Description is specific and includes key terms
- [ ] Description includes both what the Skill does and when to use it
- [ ] SKILL.md body is under 500 lines
- [ ] Additional details are in separate files (if needed)
- [ ] No time-sensitive information (or in "old patterns" section)
- [ ] Consistent terminology throughout
- [ ] Examples are concrete, not abstract
- [ ] File references are one level deep
- [ ] Progressive disclosure used appropriately
- [ ] Workflows have clear steps
### Code and scripts
- [ ] Scripts solve problems rather than punt to Claude
- [ ] Error handling is explicit and helpful
- [ ] No "voodoo constants" (all values justified)
- [ ] Required packages listed in instructions and verified as available
- [ ] Scripts have clear documentation
- [ ] No Windows-style paths (all forward slashes)
- [ ] Validation/verification steps for critical operations
- [ ] Feedback loops included for quality-critical tasks
### Testing
- [ ] At least three evaluations created
- [ ] Tested with Haiku, Sonnet, and Opus
- [ ] Tested with real usage scenarios
- [ ] Team feedback incorporated (if applicable)
## Next steps
Create your first Skill
Create and manage Skills in Claude Code
Use Skills programmatically in TypeScript and Python
Upload and use Skills programmatically
---
# Source: https://platform.claude.com/docs/en/api/beta-headers.md
# Beta headers
Documentation for using beta headers with the Claude API
---
Beta headers allow you to access experimental features and new model capabilities before they become part of the standard API.
These features are subject to change and may be modified or removed in future releases.
Beta headers are often used in conjunction with the [beta namespace in the client SDKs](/docs/en/api/client-sdks#beta-namespace-in-client-sdks)
## How to use beta headers
To access beta features, include the `anthropic-beta` header in your API requests:
```http
POST /v1/messages
Content-Type: application/json
X-API-Key: YOUR_API_KEY
anthropic-beta: BETA_FEATURE_NAME
```
When using the SDK, you can specify beta headers in the request options:
```python Python
from anthropic import Anthropic
client = Anthropic()
response = client.beta.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
messages=[
{"role": "user", "content": "Hello, Claude"}
],
betas=["beta-feature-name"]
)
```
```typescript TypeScript
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic();
const msg = await anthropic.beta.messages.create({
model: 'claude-sonnet-4-5',
max_tokens: 1024,
messages: [
{ role: 'user', content: 'Hello, Claude' }
],
betas: ['beta-feature-name']
});
```
```bash cURL
curl https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "anthropic-beta: beta-feature-name" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-4-5",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "Hello, Claude"}
]
}'
```
Beta features are experimental and may:
- Have breaking changes without notice
- Be deprecated or removed
- Have different rate limits or pricing
- Not be available in all regions
### Multiple beta features
To use multiple beta features in a single request, include all feature names in the header separated by commas:
```http
anthropic-beta: feature1,feature2,feature3
```
### Version naming conventions
Beta feature names typically follow the pattern: `feature-name-YYYY-MM-DD`, where the date indicates when the beta version was released. Always use the exact beta feature name as documented.
## Error handling
If you use an invalid or unavailable beta header, you'll receive an error response:
```json
{
"type": "error",
"error": {
"type": "invalid_request_error",
"message": "Unsupported beta header: invalid-beta-name"
}
}
```
## Getting help
For questions about beta features:
1. Check the documentation for the specific feature
2. Review the [API changelog](/docs/en/api/versioning) for updates
3. Contact support for assistance with production usage
Remember that beta features are provided "as-is" and may not have the same SLA guarantees as stable API features.
---
# Source: https://platform.claude.com/docs/en/api/typescript/beta.md
# Source: https://platform.claude.com/docs/en/api/ruby/beta.md
# Source: https://platform.claude.com/docs/en/api/python/beta.md
# Source: https://platform.claude.com/docs/en/api/kotlin/beta.md
# Source: https://platform.claude.com/docs/en/api/java/beta.md
# Source: https://platform.claude.com/docs/en/api/go/beta.md
# Source: https://platform.claude.com/docs/en/api/beta.md
# Source: https://platform.claude.com/docs/en/api/typescript/beta.md
# Beta
## Domain Types
### Anthropic Beta
- `AnthropicBeta = (string & {}) | "message-batches-2024-09-24" | "prompt-caching-2024-07-31" | "computer-use-2024-10-22" | 16 more`
- `(string & {})`
- `"message-batches-2024-09-24" | "prompt-caching-2024-07-31" | "computer-use-2024-10-22" | 16 more`
- `"message-batches-2024-09-24"`
- `"prompt-caching-2024-07-31"`
- `"computer-use-2024-10-22"`
- `"computer-use-2025-01-24"`
- `"pdfs-2024-09-25"`
- `"token-counting-2024-11-01"`
- `"token-efficient-tools-2025-02-19"`
- `"output-128k-2025-02-19"`
- `"files-api-2025-04-14"`
- `"mcp-client-2025-04-04"`
- `"mcp-client-2025-11-20"`
- `"dev-full-thinking-2025-05-14"`
- `"interleaved-thinking-2025-05-14"`
- `"code-execution-2025-05-22"`
- `"extended-cache-ttl-2025-04-11"`
- `"context-1m-2025-08-07"`
- `"context-management-2025-06-27"`
- `"model-context-window-exceeded-2025-08-26"`
- `"skills-2025-10-02"`
### Beta API Error
- `BetaAPIError`
- `message: string`
- `type: "api_error"`
- `"api_error"`
### Beta Authentication Error
- `BetaAuthenticationError`
- `message: string`
- `type: "authentication_error"`
- `"authentication_error"`
### Beta Billing Error
- `BetaBillingError`
- `message: string`
- `type: "billing_error"`
- `"billing_error"`
### Beta Error
- `BetaError = BetaInvalidRequestError | BetaAuthenticationError | BetaBillingError | 6 more`
- `BetaInvalidRequestError`
- `message: string`
- `type: "invalid_request_error"`
- `"invalid_request_error"`
- `BetaAuthenticationError`
- `message: string`
- `type: "authentication_error"`
- `"authentication_error"`
- `BetaBillingError`
- `message: string`
- `type: "billing_error"`
- `"billing_error"`
- `BetaPermissionError`
- `message: string`
- `type: "permission_error"`
- `"permission_error"`
- `BetaNotFoundError`
- `message: string`
- `type: "not_found_error"`
- `"not_found_error"`
- `BetaRateLimitError`
- `message: string`
- `type: "rate_limit_error"`
- `"rate_limit_error"`
- `BetaGatewayTimeoutError`
- `message: string`
- `type: "timeout_error"`
- `"timeout_error"`
- `BetaAPIError`
- `message: string`
- `type: "api_error"`
- `"api_error"`
- `BetaOverloadedError`
- `message: string`
- `type: "overloaded_error"`
- `"overloaded_error"`
### Beta Error Response
- `BetaErrorResponse`
- `error: BetaError`
- `BetaInvalidRequestError`
- `message: string`
- `type: "invalid_request_error"`
- `"invalid_request_error"`
- `BetaAuthenticationError`
- `message: string`
- `type: "authentication_error"`
- `"authentication_error"`
- `BetaBillingError`
- `message: string`
- `type: "billing_error"`
- `"billing_error"`
- `BetaPermissionError`
- `message: string`
- `type: "permission_error"`
- `"permission_error"`
- `BetaNotFoundError`
- `message: string`
- `type: "not_found_error"`
- `"not_found_error"`
- `BetaRateLimitError`
- `message: string`
- `type: "rate_limit_error"`
- `"rate_limit_error"`
- `BetaGatewayTimeoutError`
- `message: string`
- `type: "timeout_error"`
- `"timeout_error"`
- `BetaAPIError`
- `message: string`
- `type: "api_error"`
- `"api_error"`
- `BetaOverloadedError`
- `message: string`
- `type: "overloaded_error"`
- `"overloaded_error"`
- `request_id: string | null`
- `type: "error"`
- `"error"`
### Beta Gateway Timeout Error
- `BetaGatewayTimeoutError`
- `message: string`
- `type: "timeout_error"`
- `"timeout_error"`
### Beta Invalid Request Error
- `BetaInvalidRequestError`
- `message: string`
- `type: "invalid_request_error"`
- `"invalid_request_error"`
### Beta Not Found Error
- `BetaNotFoundError`
- `message: string`
- `type: "not_found_error"`
- `"not_found_error"`
### Beta Overloaded Error
- `BetaOverloadedError`
- `message: string`
- `type: "overloaded_error"`
- `"overloaded_error"`
### Beta Permission Error
- `BetaPermissionError`
- `message: string`
- `type: "permission_error"`
- `"permission_error"`
### Beta Rate Limit Error
- `BetaRateLimitError`
- `message: string`
- `type: "rate_limit_error"`
- `"rate_limit_error"`
# Models
## List
`client.beta.models.list(ModelListParamsparams?, RequestOptionsoptions?): Page`
**get** `/v1/models`
List available models.
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.
### Parameters
- `params: ModelListParams`
- `after_id?: string`
Query param: ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately after this object.
- `before_id?: string`
Query param: ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately before this object.
- `limit?: number`
Query param: Number of items to return per page.
Defaults to `20`. Ranges from `1` to `1000`.
- `betas?: Array`
Header param: Optional header to specify the beta version(s) you want to use.
- `(string & {})`
- `"message-batches-2024-09-24" | "prompt-caching-2024-07-31" | "computer-use-2024-10-22" | 16 more`
- `"message-batches-2024-09-24"`
- `"prompt-caching-2024-07-31"`
- `"computer-use-2024-10-22"`
- `"computer-use-2025-01-24"`
- `"pdfs-2024-09-25"`
- `"token-counting-2024-11-01"`
- `"token-efficient-tools-2025-02-19"`
- `"output-128k-2025-02-19"`
- `"files-api-2025-04-14"`
- `"mcp-client-2025-04-04"`
- `"mcp-client-2025-11-20"`
- `"dev-full-thinking-2025-05-14"`
- `"interleaved-thinking-2025-05-14"`
- `"code-execution-2025-05-22"`
- `"extended-cache-ttl-2025-04-11"`
- `"context-1m-2025-08-07"`
- `"context-management-2025-06-27"`
- `"model-context-window-exceeded-2025-08-26"`
- `"skills-2025-10-02"`
### Returns
- `BetaModelInfo`
- `id: string`
Unique model identifier.
- `created_at: string`
RFC 3339 datetime string representing the time at which the model was released. May be set to an epoch value if the release date is unknown.
- `display_name: string`
A human-readable name for the model.
- `type: "model"`
Object type.
For Models, this is always `"model"`.
- `"model"`
### Example
```typescript
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic({
apiKey: process.env['ANTHROPIC_API_KEY'], // This is the default and can be omitted
});
// Automatically fetches more pages as needed.
for await (const betaModelInfo of client.beta.models.list()) {
console.log(betaModelInfo.id);
}
```
## Retrieve
`client.beta.models.retrieve(stringmodelID, ModelRetrieveParamsparams?, RequestOptionsoptions?): BetaModelInfo`
**get** `/v1/models/{model_id}`
Get a specific model.
The Models API response can be used to determine information about a specific model or resolve a model alias to a model ID.
### Parameters
- `modelID: string`
Model identifier or alias.
- `params: ModelRetrieveParams`
- `betas?: Array`
Optional header to specify the beta version(s) you want to use.
- `(string & {})`
- `"message-batches-2024-09-24" | "prompt-caching-2024-07-31" | "computer-use-2024-10-22" | 16 more`
- `"message-batches-2024-09-24"`
- `"prompt-caching-2024-07-31"`
- `"computer-use-2024-10-22"`
- `"computer-use-2025-01-24"`
- `"pdfs-2024-09-25"`
- `"token-counting-2024-11-01"`
- `"token-efficient-tools-2025-02-19"`
- `"output-128k-2025-02-19"`
- `"files-api-2025-04-14"`
- `"mcp-client-2025-04-04"`
- `"mcp-client-2025-11-20"`
- `"dev-full-thinking-2025-05-14"`
- `"interleaved-thinking-2025-05-14"`
- `"code-execution-2025-05-22"`
- `"extended-cache-ttl-2025-04-11"`
- `"context-1m-2025-08-07"`
- `"context-management-2025-06-27"`
- `"model-context-window-exceeded-2025-08-26"`
- `"skills-2025-10-02"`
### Returns
- `BetaModelInfo`
- `id: string`
Unique model identifier.
- `created_at: string`
RFC 3339 datetime string representing the time at which the model was released. May be set to an epoch value if the release date is unknown.
- `display_name: string`
A human-readable name for the model.
- `type: "model"`
Object type.
For Models, this is always `"model"`.
- `"model"`
### Example
```typescript
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic({
apiKey: process.env['ANTHROPIC_API_KEY'], // This is the default and can be omitted
});
const betaModelInfo = await client.beta.models.retrieve('model_id');
console.log(betaModelInfo.id);
```
## Domain Types
### Beta Model Info
- `BetaModelInfo`
- `id: string`
Unique model identifier.
- `created_at: string`
RFC 3339 datetime string representing the time at which the model was released. May be set to an epoch value if the release date is unknown.
- `display_name: string`
A human-readable name for the model.
- `type: "model"`
Object type.
For Models, this is always `"model"`.
- `"model"`
# Messages
## Create
`client.beta.messages.create(MessageCreateParamsparams, RequestOptionsoptions?): BetaMessage | Stream`
**post** `/v1/messages`
Send a structured list of input messages with text and/or image content, and the model will generate the next message in the conversation.
The Messages API can be used for either single queries or stateless multi-turn conversations.
Learn more about the Messages API in our [user guide](https://docs.claude.com/en/docs/initial-setup)
### Parameters
- `MessageCreateParams = MessageCreateParamsNonStreaming | MessageCreateParamsStreaming`
- `MessageCreateParamsBase`
- `max_tokens: number`
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.
Different models have different maximum values for this parameter. See [models](https://docs.claude.com/en/docs/models-overview) for details.
- `messages: Array`
Body param: Input messages.
Our models are trained to operate on alternating `user` and `assistant` conversational turns. When creating a new `Message`, you specify the prior conversational turns with the `messages` parameter, and the model then generates the next `Message` in the conversation. Consecutive `user` or `assistant` turns in your request will be combined into a single turn.
Each input message must be an object with a `role` and `content`. You can specify a single `user`-role message, or you can include multiple `user` and `assistant` messages.
If the final message uses the `assistant` role, the response content will continue immediately from the content in that message. This can be used to constrain part of the model's response.
Example with a single `user` message:
```json
[{"role": "user", "content": "Hello, Claude"}]
```
Example with multiple conversational turns:
```json
[
{"role": "user", "content": "Hello there."},
{"role": "assistant", "content": "Hi, I'm Claude. How can I help you?"},
{"role": "user", "content": "Can you explain LLMs in plain English?"},
]
```
Example with a partially-filled response from Claude:
```json
[
{"role": "user", "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"},
{"role": "assistant", "content": "The best answer is ("},
]
```
Each input message `content` may be either a single `string` or an array of content blocks, where each block has a specific `type`. Using a `string` for `content` is shorthand for an array of one content block of type `"text"`. The following input messages are equivalent:
```json
{"role": "user", "content": "Hello, Claude"}
```
```json
{"role": "user", "content": [{"type": "text", "text": "Hello, Claude"}]}
```
See [input examples](https://docs.claude.com/en/api/messages-examples).
Note that if you want to include a [system prompt](https://docs.claude.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 100,000 messages in a single request.
- `content: string | Array`
- `string`
- `Array`
- `BetaTextBlockParam`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `BetaCitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `BetaImageBlockParam`
- `source: BetaBase64ImageSource | BetaURLImageSource | BetaFileImageSource`
- `BetaBase64ImageSource`
- `data: string`
- `media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"`
- `"image/jpeg"`
- `"image/png"`
- `"image/gif"`
- `"image/webp"`
- `type: "base64"`
- `"base64"`
- `BetaURLImageSource`
- `type: "url"`
- `"url"`
- `url: string`
- `BetaFileImageSource`
- `file_id: string`
- `type: "file"`
- `"file"`
- `type: "image"`
- `"image"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `BetaRequestDocumentBlock`
- `source: BetaBase64PDFSource | BetaPlainTextSource | BetaContentBlockSource | 2 more`
- `BetaBase64PDFSource`
- `data: string`
- `media_type: "application/pdf"`
- `"application/pdf"`
- `type: "base64"`
- `"base64"`
- `BetaPlainTextSource`
- `data: string`
- `media_type: "text/plain"`
- `"text/plain"`
- `type: "text"`
- `"text"`
- `BetaContentBlockSource`
- `content: string | Array`
- `string`
- `Array`
- `BetaTextBlockParam`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `BetaCitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `BetaImageBlockParam`
- `source: BetaBase64ImageSource | BetaURLImageSource | BetaFileImageSource`
- `BetaBase64ImageSource`
- `data: string`
- `media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"`
- `"image/jpeg"`
- `"image/png"`
- `"image/gif"`
- `"image/webp"`
- `type: "base64"`
- `"base64"`
- `BetaURLImageSource`
- `type: "url"`
- `"url"`
- `url: string`
- `BetaFileImageSource`
- `file_id: string`
- `type: "file"`
- `"file"`
- `type: "image"`
- `"image"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `type: "content"`
- `"content"`
- `BetaURLPDFSource`
- `type: "url"`
- `"url"`
- `url: string`
- `BetaFileDocumentSource`
- `file_id: string`
- `type: "file"`
- `"file"`
- `type: "document"`
- `"document"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: BetaCitationsConfigParam | null`
- `enabled?: boolean`
- `context?: string | null`
- `title?: string | null`
- `BetaSearchResultBlockParam`
- `content: Array`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `BetaCitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `source: string`
- `title: string`
- `type: "search_result"`
- `"search_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: BetaCitationsConfigParam`
- `enabled?: boolean`
- `BetaThinkingBlockParam`
- `signature: string`
- `thinking: string`
- `type: "thinking"`
- `"thinking"`
- `BetaRedactedThinkingBlockParam`
- `data: string`
- `type: "redacted_thinking"`
- `"redacted_thinking"`
- `BetaToolUseBlockParam`
- `id: string`
- `input: Record`
- `name: string`
- `type: "tool_use"`
- `"tool_use"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `caller?: BetaDirectCaller | BetaServerToolCaller`
Tool invocation directly from the model.
- `BetaDirectCaller`
Tool invocation directly from the model.
- `type: "direct"`
- `"direct"`
- `BetaServerToolCaller`
Tool invocation generated by a server-side tool.
- `tool_id: string`
- `type: "code_execution_20250825"`
- `"code_execution_20250825"`
- `BetaToolResultBlockParam`
- `tool_use_id: string`
- `type: "tool_result"`
- `"tool_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `content?: string | Array`
- `string`
- `Array`
- `BetaTextBlockParam`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `BetaCitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `BetaImageBlockParam`
- `source: BetaBase64ImageSource | BetaURLImageSource | BetaFileImageSource`
- `BetaBase64ImageSource`
- `data: string`
- `media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"`
- `"image/jpeg"`
- `"image/png"`
- `"image/gif"`
- `"image/webp"`
- `type: "base64"`
- `"base64"`
- `BetaURLImageSource`
- `type: "url"`
- `"url"`
- `url: string`
- `BetaFileImageSource`
- `file_id: string`
- `type: "file"`
- `"file"`
- `type: "image"`
- `"image"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `BetaSearchResultBlockParam`
- `content: Array`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `BetaCitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `source: string`
- `title: string`
- `type: "search_result"`
- `"search_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: BetaCitationsConfigParam`
- `enabled?: boolean`
- `BetaRequestDocumentBlock`
- `source: BetaBase64PDFSource | BetaPlainTextSource | BetaContentBlockSource | 2 more`
- `BetaBase64PDFSource`
- `data: string`
- `media_type: "application/pdf"`
- `"application/pdf"`
- `type: "base64"`
- `"base64"`
- `BetaPlainTextSource`
- `data: string`
- `media_type: "text/plain"`
- `"text/plain"`
- `type: "text"`
- `"text"`
- `BetaContentBlockSource`
- `content: string | Array`
- `string`
- `Array`
- `BetaTextBlockParam`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `BetaCitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `BetaImageBlockParam`
- `source: BetaBase64ImageSource | BetaURLImageSource | BetaFileImageSource`
- `BetaBase64ImageSource`
- `data: string`
- `media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"`
- `"image/jpeg"`
- `"image/png"`
- `"image/gif"`
- `"image/webp"`
- `type: "base64"`
- `"base64"`
- `BetaURLImageSource`
- `type: "url"`
- `"url"`
- `url: string`
- `BetaFileImageSource`
- `file_id: string`
- `type: "file"`
- `"file"`
- `type: "image"`
- `"image"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `type: "content"`
- `"content"`
- `BetaURLPDFSource`
- `type: "url"`
- `"url"`
- `url: string`
- `BetaFileDocumentSource`
- `file_id: string`
- `type: "file"`
- `"file"`
- `type: "document"`
- `"document"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: BetaCitationsConfigParam | null`
- `enabled?: boolean`
- `context?: string | null`
- `title?: string | null`
- `BetaToolReferenceBlockParam`
Tool reference block that can be included in tool_result content.
- `tool_name: string`
- `type: "tool_reference"`
- `"tool_reference"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `is_error?: boolean`
- `BetaServerToolUseBlockParam`
- `id: string`
- `input: Record`
- `name: "web_search" | "web_fetch" | "code_execution" | 4 more`
- `"web_search"`
- `"web_fetch"`
- `"code_execution"`
- `"bash_code_execution"`
- `"text_editor_code_execution"`
- `"tool_search_tool_regex"`
- `"tool_search_tool_bm25"`
- `type: "server_tool_use"`
- `"server_tool_use"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `caller?: BetaDirectCaller | BetaServerToolCaller`
Tool invocation directly from the model.
- `BetaDirectCaller`
Tool invocation directly from the model.
- `type: "direct"`
- `"direct"`
- `BetaServerToolCaller`
Tool invocation generated by a server-side tool.
- `tool_id: string`
- `type: "code_execution_20250825"`
- `"code_execution_20250825"`
- `BetaWebSearchToolResultBlockParam`
- `content: BetaWebSearchToolResultBlockParamContent`
- `Array`
- `encrypted_content: string`
- `title: string`
- `type: "web_search_result"`
- `"web_search_result"`
- `url: string`
- `page_age?: string | null`
- `BetaWebSearchToolRequestError`
- `error_code: BetaWebSearchToolResultErrorCode`
- `"invalid_tool_input"`
- `"unavailable"`
- `"max_uses_exceeded"`
- `"too_many_requests"`
- `"query_too_long"`
- `"request_too_large"`
- `type: "web_search_tool_result_error"`
- `"web_search_tool_result_error"`
- `tool_use_id: string`
- `type: "web_search_tool_result"`
- `"web_search_tool_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `BetaWebFetchToolResultBlockParam`
- `content: BetaWebFetchToolResultErrorBlockParam | BetaWebFetchBlockParam`
- `BetaWebFetchToolResultErrorBlockParam`
- `error_code: BetaWebFetchToolResultErrorCode`
- `"invalid_tool_input"`
- `"url_too_long"`
- `"url_not_allowed"`
- `"url_not_accessible"`
- `"unsupported_content_type"`
- `"too_many_requests"`
- `"max_uses_exceeded"`
- `"unavailable"`
- `type: "web_fetch_tool_result_error"`
- `"web_fetch_tool_result_error"`
- `BetaWebFetchBlockParam`
- `content: BetaRequestDocumentBlock`
- `source: BetaBase64PDFSource | BetaPlainTextSource | BetaContentBlockSource | 2 more`
- `BetaBase64PDFSource`
- `data: string`
- `media_type: "application/pdf"`
- `"application/pdf"`
- `type: "base64"`
- `"base64"`
- `BetaPlainTextSource`
- `data: string`
- `media_type: "text/plain"`
- `"text/plain"`
- `type: "text"`
- `"text"`
- `BetaContentBlockSource`
- `content: string | Array`
- `string`
- `Array`
- `BetaTextBlockParam`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `BetaCitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `BetaImageBlockParam`
- `source: BetaBase64ImageSource | BetaURLImageSource | BetaFileImageSource`
- `BetaBase64ImageSource`
- `data: string`
- `media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"`
- `"image/jpeg"`
- `"image/png"`
- `"image/gif"`
- `"image/webp"`
- `type: "base64"`
- `"base64"`
- `BetaURLImageSource`
- `type: "url"`
- `"url"`
- `url: string`
- `BetaFileImageSource`
- `file_id: string`
- `type: "file"`
- `"file"`
- `type: "image"`
- `"image"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `type: "content"`
- `"content"`
- `BetaURLPDFSource`
- `type: "url"`
- `"url"`
- `url: string`
- `BetaFileDocumentSource`
- `file_id: string`
- `type: "file"`
- `"file"`
- `type: "document"`
- `"document"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: BetaCitationsConfigParam | null`
- `enabled?: boolean`
- `context?: string | null`
- `title?: string | null`
- `type: "web_fetch_result"`
- `"web_fetch_result"`
- `url: string`
Fetched content URL
- `retrieved_at?: string | null`
ISO 8601 timestamp when the content was retrieved
- `tool_use_id: string`
- `type: "web_fetch_tool_result"`
- `"web_fetch_tool_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `BetaCodeExecutionToolResultBlockParam`
- `content: BetaCodeExecutionToolResultBlockParamContent`
- `BetaCodeExecutionToolResultErrorParam`
- `error_code: BetaCodeExecutionToolResultErrorCode`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `type: "code_execution_tool_result_error"`
- `"code_execution_tool_result_error"`
- `BetaCodeExecutionResultBlockParam`
- `content: Array`
- `file_id: string`
- `type: "code_execution_output"`
- `"code_execution_output"`
- `return_code: number`
- `stderr: string`
- `stdout: string`
- `type: "code_execution_result"`
- `"code_execution_result"`
- `tool_use_id: string`
- `type: "code_execution_tool_result"`
- `"code_execution_tool_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `BetaBashCodeExecutionToolResultBlockParam`
- `content: BetaBashCodeExecutionToolResultErrorParam | BetaBashCodeExecutionResultBlockParam`
- `BetaBashCodeExecutionToolResultErrorParam`
- `error_code: "invalid_tool_input" | "unavailable" | "too_many_requests" | 2 more`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `"output_file_too_large"`
- `type: "bash_code_execution_tool_result_error"`
- `"bash_code_execution_tool_result_error"`
- `BetaBashCodeExecutionResultBlockParam`
- `content: Array`
- `file_id: string`
- `type: "bash_code_execution_output"`
- `"bash_code_execution_output"`
- `return_code: number`
- `stderr: string`
- `stdout: string`
- `type: "bash_code_execution_result"`
- `"bash_code_execution_result"`
- `tool_use_id: string`
- `type: "bash_code_execution_tool_result"`
- `"bash_code_execution_tool_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `BetaTextEditorCodeExecutionToolResultBlockParam`
- `content: BetaTextEditorCodeExecutionToolResultErrorParam | BetaTextEditorCodeExecutionViewResultBlockParam | BetaTextEditorCodeExecutionCreateResultBlockParam | BetaTextEditorCodeExecutionStrReplaceResultBlockParam`
- `BetaTextEditorCodeExecutionToolResultErrorParam`
- `error_code: "invalid_tool_input" | "unavailable" | "too_many_requests" | 2 more`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `"file_not_found"`
- `type: "text_editor_code_execution_tool_result_error"`
- `"text_editor_code_execution_tool_result_error"`
- `error_message?: string | null`
- `BetaTextEditorCodeExecutionViewResultBlockParam`
- `content: string`
- `file_type: "text" | "image" | "pdf"`
- `"text"`
- `"image"`
- `"pdf"`
- `type: "text_editor_code_execution_view_result"`
- `"text_editor_code_execution_view_result"`
- `num_lines?: number | null`
- `start_line?: number | null`
- `total_lines?: number | null`
- `BetaTextEditorCodeExecutionCreateResultBlockParam`
- `is_file_update: boolean`
- `type: "text_editor_code_execution_create_result"`
- `"text_editor_code_execution_create_result"`
- `BetaTextEditorCodeExecutionStrReplaceResultBlockParam`
- `type: "text_editor_code_execution_str_replace_result"`
- `"text_editor_code_execution_str_replace_result"`
- `lines?: Array | null`
- `new_lines?: number | null`
- `new_start?: number | null`
- `old_lines?: number | null`
- `old_start?: number | null`
- `tool_use_id: string`
- `type: "text_editor_code_execution_tool_result"`
- `"text_editor_code_execution_tool_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `BetaToolSearchToolResultBlockParam`
- `content: BetaToolSearchToolResultErrorParam | BetaToolSearchToolSearchResultBlockParam`
- `BetaToolSearchToolResultErrorParam`
- `error_code: "invalid_tool_input" | "unavailable" | "too_many_requests" | "execution_time_exceeded"`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `type: "tool_search_tool_result_error"`
- `"tool_search_tool_result_error"`
- `BetaToolSearchToolSearchResultBlockParam`
- `tool_references: Array`
- `tool_name: string`
- `type: "tool_reference"`
- `"tool_reference"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `type: "tool_search_tool_search_result"`
- `"tool_search_tool_search_result"`
- `tool_use_id: string`
- `type: "tool_search_tool_result"`
- `"tool_search_tool_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `BetaMCPToolUseBlockParam`
- `id: string`
- `input: Record`
- `name: string`
- `server_name: string`
The name of the MCP server
- `type: "mcp_tool_use"`
- `"mcp_tool_use"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `BetaRequestMCPToolResultBlockParam`
- `tool_use_id: string`
- `type: "mcp_tool_result"`
- `"mcp_tool_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `content?: string | Array`
- `string`
- `Array`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `BetaCitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `is_error?: boolean`
- `BetaContainerUploadBlockParam`
A content block that represents a file to be uploaded to the container
Files uploaded via this block will be available in the container's input directory.
- `file_id: string`
- `type: "container_upload"`
- `"container_upload"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `role: "user" | "assistant"`
- `"user"`
- `"assistant"`
- `model: Model`
Body param: The model that will complete your prompt.
See [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options.
- `"claude-opus-4-5-20251101" | "claude-opus-4-5" | "claude-3-7-sonnet-latest" | 17 more`
- `"claude-opus-4-5-20251101"`
Premium model combining maximum intelligence with practical performance
- `"claude-opus-4-5"`
Premium model combining maximum intelligence with practical performance
- `"claude-3-7-sonnet-latest"`
High-performance model with early extended thinking
- `"claude-3-7-sonnet-20250219"`
High-performance model with early extended thinking
- `"claude-3-5-haiku-latest"`
Fastest and most compact model for near-instant responsiveness
- `"claude-3-5-haiku-20241022"`
Our fastest model
- `"claude-haiku-4-5"`
Hybrid model, capable of near-instant responses and extended thinking
- `"claude-haiku-4-5-20251001"`
Hybrid model, capable of near-instant responses and extended thinking
- `"claude-sonnet-4-20250514"`
High-performance model with extended thinking
- `"claude-sonnet-4-0"`
High-performance model with extended thinking
- `"claude-4-sonnet-20250514"`
High-performance model with extended thinking
- `"claude-sonnet-4-5"`
Our best model for real-world agents and coding
- `"claude-sonnet-4-5-20250929"`
Our best model for real-world agents and coding
- `"claude-opus-4-0"`
Our most capable model
- `"claude-opus-4-20250514"`
Our most capable model
- `"claude-4-opus-20250514"`
Our most capable model
- `"claude-opus-4-1-20250805"`
Our most capable model
- `"claude-3-opus-latest"`
Excels at writing and complex tasks
- `"claude-3-opus-20240229"`
Excels at writing and complex tasks
- `"claude-3-haiku-20240307"`
Our previous most fast and cost-effective
- `(string & {})`
- `container?: BetaContainerParams | string | null`
Body param: Container identifier for reuse across requests.
- `BetaContainerParams`
Container parameters with skills to be loaded.
- `id?: string | null`
Container id
- `skills?: Array | null`
List of skills to load in the container
- `skill_id: string`
Skill ID
- `type: "anthropic" | "custom"`
Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined)
- `"anthropic"`
- `"custom"`
- `version?: string`
Skill version or 'latest' for most recent version
- `string`
- `context_management?: BetaContextManagementConfig | null`
Body param: Context management configuration.
This allows you to control how Claude manages context across multiple requests, such as whether to clear function results or not.
- `edits?: Array`
List of context management edits to apply
- `BetaClearToolUses20250919Edit`
- `type: "clear_tool_uses_20250919"`
- `"clear_tool_uses_20250919"`
- `clear_at_least?: BetaInputTokensClearAtLeast | null`
Minimum number of tokens that must be cleared when triggered. Context will only be modified if at least this many tokens can be removed.
- `type: "input_tokens"`
- `"input_tokens"`
- `value: number`
- `clear_tool_inputs?: boolean | Array | null`
Whether to clear all tool inputs (bool) or specific tool inputs to clear (list)
- `boolean`
- `Array`
- `exclude_tools?: Array | null`
Tool names whose uses are preserved from clearing
- `keep?: BetaToolUsesKeep`
Number of tool uses to retain in the conversation
- `type: "tool_uses"`
- `"tool_uses"`
- `value: number`
- `trigger?: BetaInputTokensTrigger | BetaToolUsesTrigger`
Condition that triggers the context management strategy
- `BetaInputTokensTrigger`
- `type: "input_tokens"`
- `"input_tokens"`
- `value: number`
- `BetaToolUsesTrigger`
- `type: "tool_uses"`
- `"tool_uses"`
- `value: number`
- `BetaClearThinking20251015Edit`
- `type: "clear_thinking_20251015"`
- `"clear_thinking_20251015"`
- `keep?: BetaThinkingTurns | BetaAllThinkingTurns | "all"`
Number of most recent assistant turns to keep thinking blocks for. Older turns will have their thinking blocks removed.
- `BetaThinkingTurns`
- `type: "thinking_turns"`
- `"thinking_turns"`
- `value: number`
- `BetaAllThinkingTurns`
- `type: "all"`
- `"all"`
- `"all"`
- `"all"`
- `mcp_servers?: Array`
Body param: MCP servers to be utilized in this request
- `name: string`
- `type: "url"`
- `"url"`
- `url: string`
- `authorization_token?: string | null`
- `tool_configuration?: BetaRequestMCPServerToolConfiguration | null`
- `allowed_tools?: Array | null`
- `enabled?: boolean | null`
- `metadata?: BetaMetadata`
Body param: An object describing metadata about the request.
- `user_id?: string | null`
An external identifier for the user who is associated with the request.
This should be a uuid, hash value, or other opaque identifier. Anthropic may use this id to help detect abuse. Do not include any identifying information such as name, email address, or phone number.
- `output_config?: BetaOutputConfig`
Body param: Configuration options for the model's output, such as the output format.
- `effort?: "low" | "medium" | "high" | null`
How much effort the model should put into its response. Higher effort levels may result in more thorough analysis but take longer.
Valid values are `low`, `medium`, or `high`.
- `"low"`
- `"medium"`
- `"high"`
- `format?: BetaJSONOutputFormat | null`
A schema to specify Claude's output format in responses. See [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)
- `schema: Record`
The JSON schema of the format
- `type: "json_schema"`
- `"json_schema"`
- `output_format?: BetaJSONOutputFormat | null`
Body param: Deprecated: Use `output_config.format` instead. See [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)
A schema to specify Claude's output format in responses. This parameter will be removed in a future release.
- `schema: Record`
The JSON schema of the format
- `type: "json_schema"`
- `"json_schema"`
- `service_tier?: "auto" | "standard_only"`
Body param: Determines whether to use priority capacity (if available) or standard capacity for this request.
Anthropic offers different levels of service for your API requests. See [service-tiers](https://docs.claude.com/en/api/service-tiers) for details.
- `"auto"`
- `"standard_only"`
- `stop_sequences?: Array`
Body param: Custom text sequences that will cause the model to stop generating.
Our models will normally stop when they have naturally completed their turn, which will result in a response `stop_reason` of `"end_turn"`.
If you want the model to stop generating when it encounters custom strings of text, you can use the `stop_sequences` parameter. If the model encounters one of the custom sequences, the response `stop_reason` value will be `"stop_sequence"` and the response `stop_sequence` value will contain the matched stop sequence.
- `stream?: false`
Body param: Whether to incrementally stream the response using server-sent events.
See [streaming](https://docs.claude.com/en/api/messages-streaming) for details.
- `false`
- `system?: string | Array`
Body param: System prompt.
A system prompt is a way of providing context and instructions to Claude, such as specifying a particular goal or role. See our [guide to system prompts](https://docs.claude.com/en/docs/system-prompts).
- `string`
- `Array`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `BetaCitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `temperature?: number`
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 generative tasks.
Note that even with `temperature` of `0.0`, the results will not be fully deterministic.
- `thinking?: BetaThinkingConfigParam`
Body param: Configuration for enabling Claude's extended thinking.
When enabled, responses include `thinking` content blocks showing Claude's thinking process before the final answer. Requires a minimum budget of 1,024 tokens and counts towards your `max_tokens` limit.
See [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) for details.
- `BetaThinkingConfigEnabled`
- `budget_tokens: number`
Determines how many tokens Claude can use for its internal reasoning process. Larger budgets can enable more thorough analysis for complex problems, improving response quality.
Must be ≥1024 and less than `max_tokens`.
See [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) for details.
- `type: "enabled"`
- `"enabled"`
- `BetaThinkingConfigDisabled`
- `type: "disabled"`
- `"disabled"`
- `tool_choice?: BetaToolChoice`
Body param: How the model should use the provided tools. The model can use a specific tool, any available tool, decide by itself, or not use tools at all.
- `BetaToolChoiceAuto`
The model will automatically decide whether to use tools.
- `type: "auto"`
- `"auto"`
- `disable_parallel_tool_use?: boolean`
Whether to disable parallel tool use.
Defaults to `false`. If set to `true`, the model will output at most one tool use.
- `BetaToolChoiceAny`
The model will use any available tools.
- `type: "any"`
- `"any"`
- `disable_parallel_tool_use?: boolean`
Whether to disable parallel tool use.
Defaults to `false`. If set to `true`, the model will output exactly one tool use.
- `BetaToolChoiceTool`
The model will use the specified tool with `tool_choice.name`.
- `name: string`
The name of the tool to use.
- `type: "tool"`
- `"tool"`
- `disable_parallel_tool_use?: boolean`
Whether to disable parallel tool use.
Defaults to `false`. If set to `true`, the model will output exactly one tool use.
- `BetaToolChoiceNone`
The model will not be allowed to use tools.
- `type: "none"`
- `"none"`
- `tools?: Array`
Body param: Definitions of tools that the model may use.
If you include `tools` in your API request, the model may return `tool_use` content blocks that represent the model's use of those tools. You can then run those tools using the tool input generated by the model and then optionally return results back to the model using `tool_result` content blocks.
There are two types of tools: **client tools** and **server tools**. The behavior described below applies to client tools. For [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview#server-tools), see their individual documentation as each has its own behavior (e.g., the [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)).
Each tool definition includes:
* `name`: Name of the tool.
* `description`: Optional, but strongly-recommended description of the tool.
* `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the tool `input` shape that the model will produce in `tool_use` output content blocks.
For example, if you defined `tools` as:
```json
[
{
"name": "get_stock_price",
"description": "Get the current stock price for a given ticker symbol.",
"input_schema": {
"type": "object",
"properties": {
"ticker": {
"type": "string",
"description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
}
},
"required": ["ticker"]
}
}
]
```
And then asked the model "What's the S&P 500 at today?", the model might produce `tool_use` content blocks in the response like this:
```json
[
{
"type": "tool_use",
"id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
"name": "get_stock_price",
"input": { "ticker": "^GSPC" }
}
]
```
You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an input, and return the following back to the model in a subsequent `user` message:
```json
[
{
"type": "tool_result",
"tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
"content": "259.75 USD"
}
]
```
Tools can be used for workflows that include running client-side tools and functions, or more generally whenever you want the model to produce a particular JSON structure of output.
See our [guide](https://docs.claude.com/en/docs/tool-use) for more details.
- `BetaTool`
- `input_schema: InputSchema`
[JSON schema](https://json-schema.org/draft/2020-12) for this tool's input.
This defines the shape of the `input` that your tool accepts and that the model will produce.
- `type: "object"`
- `"object"`
- `properties?: Record | null`
- `required?: Array | null`
- `name: string`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `description?: string`
Description of what this tool does.
Tool descriptions should be as detailed as possible. The more information that the model has about what the tool is and how to use it, the better it will perform. You can use natural language descriptions to reinforce important aspects of the tool input JSON schema.
- `input_examples?: Array>`
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `type?: "custom" | null`
- `"custom"`
- `BetaToolBash20241022`
- `name: "bash"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"bash"`
- `type: "bash_20241022"`
- `"bash_20241022"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `input_examples?: Array>`
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaToolBash20250124`
- `name: "bash"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"bash"`
- `type: "bash_20250124"`
- `"bash_20250124"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `input_examples?: Array>`
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaCodeExecutionTool20250522`
- `name: "code_execution"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"code_execution"`
- `type: "code_execution_20250522"`
- `"code_execution_20250522"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaCodeExecutionTool20250825`
- `name: "code_execution"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"code_execution"`
- `type: "code_execution_20250825"`
- `"code_execution_20250825"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaToolComputerUse20241022`
- `display_height_px: number`
The height of the display in pixels.
- `display_width_px: number`
The width of the display in pixels.
- `name: "computer"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"computer"`
- `type: "computer_20241022"`
- `"computer_20241022"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `display_number?: number | null`
The X11 display number (e.g. 0, 1) for the display.
- `input_examples?: Array>`
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaMemoryTool20250818`
- `name: "memory"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"memory"`
- `type: "memory_20250818"`
- `"memory_20250818"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `input_examples?: Array>`
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaToolComputerUse20250124`
- `display_height_px: number`
The height of the display in pixels.
- `display_width_px: number`
The width of the display in pixels.
- `name: "computer"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"computer"`
- `type: "computer_20250124"`
- `"computer_20250124"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `display_number?: number | null`
The X11 display number (e.g. 0, 1) for the display.
- `input_examples?: Array>`
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaToolTextEditor20241022`
- `name: "str_replace_editor"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"str_replace_editor"`
- `type: "text_editor_20241022"`
- `"text_editor_20241022"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `input_examples?: Array>`
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaToolComputerUse20251124`
- `display_height_px: number`
The height of the display in pixels.
- `display_width_px: number`
The width of the display in pixels.
- `name: "computer"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"computer"`
- `type: "computer_20251124"`
- `"computer_20251124"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `display_number?: number | null`
The X11 display number (e.g. 0, 1) for the display.
- `enable_zoom?: boolean`
Whether to enable an action to take a zoomed-in screenshot of the screen.
- `input_examples?: Array>`
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaToolTextEditor20250124`
- `name: "str_replace_editor"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"str_replace_editor"`
- `type: "text_editor_20250124"`
- `"text_editor_20250124"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `input_examples?: Array>`
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaToolTextEditor20250429`
- `name: "str_replace_based_edit_tool"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"str_replace_based_edit_tool"`
- `type: "text_editor_20250429"`
- `"text_editor_20250429"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `input_examples?: Array>`
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaToolTextEditor20250728`
- `name: "str_replace_based_edit_tool"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"str_replace_based_edit_tool"`
- `type: "text_editor_20250728"`
- `"text_editor_20250728"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `input_examples?: Array>`
- `max_characters?: number | null`
Maximum number of characters to display when viewing a file. If not specified, defaults to displaying the full file.
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaWebSearchTool20250305`
- `name: "web_search"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"web_search"`
- `type: "web_search_20250305"`
- `"web_search_20250305"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `allowed_domains?: Array | null`
If provided, only these domains will be included in results. Cannot be used alongside `blocked_domains`.
- `blocked_domains?: Array | null`
If provided, these domains will never appear in results. Cannot be used alongside `allowed_domains`.
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `max_uses?: number | null`
Maximum number of times the tool can be used in the API request.
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `user_location?: UserLocation | null`
Parameters for the user's location. Used to provide more relevant search results.
- `type: "approximate"`
- `"approximate"`
- `city?: string | null`
The city of the user.
- `country?: string | null`
The two letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the user.
- `region?: string | null`
The region of the user.
- `timezone?: string | null`
The [IANA timezone](https://nodatime.org/TimeZones) of the user.
- `BetaWebFetchTool20250910`
- `name: "web_fetch"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"web_fetch"`
- `type: "web_fetch_20250910"`
- `"web_fetch_20250910"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `allowed_domains?: Array | null`
List of domains to allow fetching from
- `blocked_domains?: Array | null`
List of domains to block fetching from
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: BetaCitationsConfigParam | null`
Citations configuration for fetched documents. Citations are disabled by default.
- `enabled?: boolean`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `max_content_tokens?: number | null`
Maximum number of tokens used by including web page text content in the context. The limit is approximate and does not apply to binary content such as PDFs.
- `max_uses?: number | null`
Maximum number of times the tool can be used in the API request.
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaToolSearchToolBm25_20251119`
- `name: "tool_search_tool_bm25"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"tool_search_tool_bm25"`
- `type: "tool_search_tool_bm25_20251119" | "tool_search_tool_bm25"`
- `"tool_search_tool_bm25_20251119"`
- `"tool_search_tool_bm25"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaToolSearchToolRegex20251119`
- `name: "tool_search_tool_regex"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"tool_search_tool_regex"`
- `type: "tool_search_tool_regex_20251119" | "tool_search_tool_regex"`
- `"tool_search_tool_regex_20251119"`
- `"tool_search_tool_regex"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaMCPToolset`
Configuration for a group of tools from an MCP server.
Allows configuring enabled status and defer_loading for all tools
from an MCP server, with optional per-tool overrides.
- `mcp_server_name: string`
Name of the MCP server to configure tools for
- `type: "mcp_toolset"`
- `"mcp_toolset"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `configs?: Record | null`
Configuration overrides for specific tools, keyed by tool name
- `defer_loading?: boolean`
- `enabled?: boolean`
- `default_config?: BetaMCPToolDefaultConfig`
Default configuration applied to all tools from this server
- `defer_loading?: boolean`
- `enabled?: boolean`
- `top_k?: number`
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).
Recommended for advanced use cases only. You usually only need to use `temperature`.
- `top_p?: number`
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 reaches a particular probability specified by `top_p`. You should either alter `temperature` or `top_p`, but not both.
Recommended for advanced use cases only. You usually only need to use `temperature`.
- `betas?: Array`
Header param: Optional header to specify the beta version(s) you want to use.
- `(string & {})`
- `"message-batches-2024-09-24" | "prompt-caching-2024-07-31" | "computer-use-2024-10-22" | 16 more`
- `"message-batches-2024-09-24"`
- `"prompt-caching-2024-07-31"`
- `"computer-use-2024-10-22"`
- `"computer-use-2025-01-24"`
- `"pdfs-2024-09-25"`
- `"token-counting-2024-11-01"`
- `"token-efficient-tools-2025-02-19"`
- `"output-128k-2025-02-19"`
- `"files-api-2025-04-14"`
- `"mcp-client-2025-04-04"`
- `"mcp-client-2025-11-20"`
- `"dev-full-thinking-2025-05-14"`
- `"interleaved-thinking-2025-05-14"`
- `"code-execution-2025-05-22"`
- `"extended-cache-ttl-2025-04-11"`
- `"context-1m-2025-08-07"`
- `"context-management-2025-06-27"`
- `"model-context-window-exceeded-2025-08-26"`
- `"skills-2025-10-02"`
- `MessageCreateParamsNonStreaming extends MessageCreateParamsBase`
- `stream?: false`
Body param: Whether to incrementally stream the response using server-sent events.
See [streaming](https://docs.claude.com/en/api/messages-streaming) for details.
- `false`
- `MessageCreateParamsNonStreaming extends MessageCreateParamsBase`
- `stream?: false`
Body param: Whether to incrementally stream the response using server-sent events.
See [streaming](https://docs.claude.com/en/api/messages-streaming) for details.
- `false`
### Returns
- `BetaMessage`
- `id: string`
Unique object identifier.
The format and length of IDs may change over time.
- `container: BetaContainer | null`
Information about the container used in the request (for the code execution tool)
- `id: string`
Identifier for the container used in this request
- `expires_at: string`
The time at which the container will expire.
- `skills: Array | null`
Skills loaded in the container
- `skill_id: string`
Skill ID
- `type: "anthropic" | "custom"`
Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined)
- `"anthropic"`
- `"custom"`
- `version: string`
Skill version or 'latest' for most recent version
- `content: Array`
Content generated by the model.
This is an array of content blocks, each of which has a `type` that determines its shape.
Example:
```json
[{"type": "text", "text": "Hi, I'm Claude."}]
```
If the request input `messages` ended with an `assistant` turn, then the response `content` will continue directly from that last turn. You can use this to constrain the model's output.
For example, if the input `messages` were:
```json
[
{"role": "user", "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"},
{"role": "assistant", "content": "The best answer is ("}
]
```
Then the response `content` might be:
```json
[{"type": "text", "text": "B)"}]
```
- `BetaTextBlock`
- `citations: Array | null`
Citations supporting the text block.
The type of citation returned will depend on the type of document being cited. Citing a PDF results in `page_location`, plain text results in `char_location`, and content document results in `content_block_location`.
- `BetaCitationCharLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `file_id: string | null`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `file_id: string | null`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `file_id: string | null`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationsWebSearchResultLocation`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocation`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `text: string`
- `type: "text"`
- `"text"`
- `BetaThinkingBlock`
- `signature: string`
- `thinking: string`
- `type: "thinking"`
- `"thinking"`
- `BetaRedactedThinkingBlock`
- `data: string`
- `type: "redacted_thinking"`
- `"redacted_thinking"`
- `BetaToolUseBlock`
- `id: string`
- `input: Record`
- `name: string`
- `type: "tool_use"`
- `"tool_use"`
- `caller?: BetaDirectCaller | BetaServerToolCaller`
Tool invocation directly from the model.
- `BetaDirectCaller`
Tool invocation directly from the model.
- `type: "direct"`
- `"direct"`
- `BetaServerToolCaller`
Tool invocation generated by a server-side tool.
- `tool_id: string`
- `type: "code_execution_20250825"`
- `"code_execution_20250825"`
- `BetaServerToolUseBlock`
- `id: string`
- `input: Record`
- `name: "web_search" | "web_fetch" | "code_execution" | 4 more`
- `"web_search"`
- `"web_fetch"`
- `"code_execution"`
- `"bash_code_execution"`
- `"text_editor_code_execution"`
- `"tool_search_tool_regex"`
- `"tool_search_tool_bm25"`
- `type: "server_tool_use"`
- `"server_tool_use"`
- `caller?: BetaDirectCaller | BetaServerToolCaller`
Tool invocation directly from the model.
- `BetaDirectCaller`
Tool invocation directly from the model.
- `type: "direct"`
- `"direct"`
- `BetaServerToolCaller`
Tool invocation generated by a server-side tool.
- `tool_id: string`
- `type: "code_execution_20250825"`
- `"code_execution_20250825"`
- `BetaWebSearchToolResultBlock`
- `content: BetaWebSearchToolResultBlockContent`
- `BetaWebSearchToolResultError`
- `error_code: BetaWebSearchToolResultErrorCode`
- `"invalid_tool_input"`
- `"unavailable"`
- `"max_uses_exceeded"`
- `"too_many_requests"`
- `"query_too_long"`
- `"request_too_large"`
- `type: "web_search_tool_result_error"`
- `"web_search_tool_result_error"`
- `Array`
- `encrypted_content: string`
- `page_age: string | null`
- `title: string`
- `type: "web_search_result"`
- `"web_search_result"`
- `url: string`
- `tool_use_id: string`
- `type: "web_search_tool_result"`
- `"web_search_tool_result"`
- `BetaWebFetchToolResultBlock`
- `content: BetaWebFetchToolResultErrorBlock | BetaWebFetchBlock`
- `BetaWebFetchToolResultErrorBlock`
- `error_code: BetaWebFetchToolResultErrorCode`
- `"invalid_tool_input"`
- `"url_too_long"`
- `"url_not_allowed"`
- `"url_not_accessible"`
- `"unsupported_content_type"`
- `"too_many_requests"`
- `"max_uses_exceeded"`
- `"unavailable"`
- `type: "web_fetch_tool_result_error"`
- `"web_fetch_tool_result_error"`
- `BetaWebFetchBlock`
- `content: BetaDocumentBlock`
- `citations: BetaCitationConfig | null`
Citation configuration for the document
- `enabled: boolean`
- `source: BetaBase64PDFSource | BetaPlainTextSource`
- `BetaBase64PDFSource`
- `data: string`
- `media_type: "application/pdf"`
- `"application/pdf"`
- `type: "base64"`
- `"base64"`
- `BetaPlainTextSource`
- `data: string`
- `media_type: "text/plain"`
- `"text/plain"`
- `type: "text"`
- `"text"`
- `title: string | null`
The title of the document
- `type: "document"`
- `"document"`
- `retrieved_at: string | null`
ISO 8601 timestamp when the content was retrieved
- `type: "web_fetch_result"`
- `"web_fetch_result"`
- `url: string`
Fetched content URL
- `tool_use_id: string`
- `type: "web_fetch_tool_result"`
- `"web_fetch_tool_result"`
- `BetaCodeExecutionToolResultBlock`
- `content: BetaCodeExecutionToolResultBlockContent`
- `BetaCodeExecutionToolResultError`
- `error_code: BetaCodeExecutionToolResultErrorCode`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `type: "code_execution_tool_result_error"`
- `"code_execution_tool_result_error"`
- `BetaCodeExecutionResultBlock`
- `content: Array`
- `file_id: string`
- `type: "code_execution_output"`
- `"code_execution_output"`
- `return_code: number`
- `stderr: string`
- `stdout: string`
- `type: "code_execution_result"`
- `"code_execution_result"`
- `tool_use_id: string`
- `type: "code_execution_tool_result"`
- `"code_execution_tool_result"`
- `BetaBashCodeExecutionToolResultBlock`
- `content: BetaBashCodeExecutionToolResultError | BetaBashCodeExecutionResultBlock`
- `BetaBashCodeExecutionToolResultError`
- `error_code: "invalid_tool_input" | "unavailable" | "too_many_requests" | 2 more`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `"output_file_too_large"`
- `type: "bash_code_execution_tool_result_error"`
- `"bash_code_execution_tool_result_error"`
- `BetaBashCodeExecutionResultBlock`
- `content: Array`
- `file_id: string`
- `type: "bash_code_execution_output"`
- `"bash_code_execution_output"`
- `return_code: number`
- `stderr: string`
- `stdout: string`
- `type: "bash_code_execution_result"`
- `"bash_code_execution_result"`
- `tool_use_id: string`
- `type: "bash_code_execution_tool_result"`
- `"bash_code_execution_tool_result"`
- `BetaTextEditorCodeExecutionToolResultBlock`
- `content: BetaTextEditorCodeExecutionToolResultError | BetaTextEditorCodeExecutionViewResultBlock | BetaTextEditorCodeExecutionCreateResultBlock | BetaTextEditorCodeExecutionStrReplaceResultBlock`
- `BetaTextEditorCodeExecutionToolResultError`
- `error_code: "invalid_tool_input" | "unavailable" | "too_many_requests" | 2 more`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `"file_not_found"`
- `error_message: string | null`
- `type: "text_editor_code_execution_tool_result_error"`
- `"text_editor_code_execution_tool_result_error"`
- `BetaTextEditorCodeExecutionViewResultBlock`
- `content: string`
- `file_type: "text" | "image" | "pdf"`
- `"text"`
- `"image"`
- `"pdf"`
- `num_lines: number | null`
- `start_line: number | null`
- `total_lines: number | null`
- `type: "text_editor_code_execution_view_result"`
- `"text_editor_code_execution_view_result"`
- `BetaTextEditorCodeExecutionCreateResultBlock`
- `is_file_update: boolean`
- `type: "text_editor_code_execution_create_result"`
- `"text_editor_code_execution_create_result"`
- `BetaTextEditorCodeExecutionStrReplaceResultBlock`
- `lines: Array | null`
- `new_lines: number | null`
- `new_start: number | null`
- `old_lines: number | null`
- `old_start: number | null`
- `type: "text_editor_code_execution_str_replace_result"`
- `"text_editor_code_execution_str_replace_result"`
- `tool_use_id: string`
- `type: "text_editor_code_execution_tool_result"`
- `"text_editor_code_execution_tool_result"`
- `BetaToolSearchToolResultBlock`
- `content: BetaToolSearchToolResultError | BetaToolSearchToolSearchResultBlock`
- `BetaToolSearchToolResultError`
- `error_code: "invalid_tool_input" | "unavailable" | "too_many_requests" | "execution_time_exceeded"`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `error_message: string | null`
- `type: "tool_search_tool_result_error"`
- `"tool_search_tool_result_error"`
- `BetaToolSearchToolSearchResultBlock`
- `tool_references: Array`
- `tool_name: string`
- `type: "tool_reference"`
- `"tool_reference"`
- `type: "tool_search_tool_search_result"`
- `"tool_search_tool_search_result"`
- `tool_use_id: string`
- `type: "tool_search_tool_result"`
- `"tool_search_tool_result"`
- `BetaMCPToolUseBlock`
- `id: string`
- `input: Record`
- `name: string`
The name of the MCP tool
- `server_name: string`
The name of the MCP server
- `type: "mcp_tool_use"`
- `"mcp_tool_use"`
- `BetaMCPToolResultBlock`
- `content: string | Array`
- `string`
- `Array`
- `citations: Array | null`
Citations supporting the text block.
The type of citation returned will depend on the type of document being cited. Citing a PDF results in `page_location`, plain text results in `char_location`, and content document results in `content_block_location`.
- `BetaCitationCharLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `file_id: string | null`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `file_id: string | null`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `file_id: string | null`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationsWebSearchResultLocation`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocation`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `text: string`
- `type: "text"`
- `"text"`
- `is_error: boolean`
- `tool_use_id: string`
- `type: "mcp_tool_result"`
- `"mcp_tool_result"`
- `BetaContainerUploadBlock`
Response model for a file uploaded to the container.
- `file_id: string`
- `type: "container_upload"`
- `"container_upload"`
- `context_management: BetaContextManagementResponse | null`
Context management response.
Information about context management strategies applied during the request.
- `applied_edits: Array`
List of context management edits that were applied.
- `BetaClearToolUses20250919EditResponse`
- `cleared_input_tokens: number`
Number of input tokens cleared by this edit.
- `cleared_tool_uses: number`
Number of tool uses that were cleared.
- `type: "clear_tool_uses_20250919"`
The type of context management edit applied.
- `"clear_tool_uses_20250919"`
- `BetaClearThinking20251015EditResponse`
- `cleared_input_tokens: number`
Number of input tokens cleared by this edit.
- `cleared_thinking_turns: number`
Number of thinking turns that were cleared.
- `type: "clear_thinking_20251015"`
The type of context management edit applied.
- `"clear_thinking_20251015"`
- `model: Model`
The model that will complete your prompt.
See [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options.
- `"claude-opus-4-5-20251101" | "claude-opus-4-5" | "claude-3-7-sonnet-latest" | 17 more`
- `"claude-opus-4-5-20251101"`
Premium model combining maximum intelligence with practical performance
- `"claude-opus-4-5"`
Premium model combining maximum intelligence with practical performance
- `"claude-3-7-sonnet-latest"`
High-performance model with early extended thinking
- `"claude-3-7-sonnet-20250219"`
High-performance model with early extended thinking
- `"claude-3-5-haiku-latest"`
Fastest and most compact model for near-instant responsiveness
- `"claude-3-5-haiku-20241022"`
Our fastest model
- `"claude-haiku-4-5"`
Hybrid model, capable of near-instant responses and extended thinking
- `"claude-haiku-4-5-20251001"`
Hybrid model, capable of near-instant responses and extended thinking
- `"claude-sonnet-4-20250514"`
High-performance model with extended thinking
- `"claude-sonnet-4-0"`
High-performance model with extended thinking
- `"claude-4-sonnet-20250514"`
High-performance model with extended thinking
- `"claude-sonnet-4-5"`
Our best model for real-world agents and coding
- `"claude-sonnet-4-5-20250929"`
Our best model for real-world agents and coding
- `"claude-opus-4-0"`
Our most capable model
- `"claude-opus-4-20250514"`
Our most capable model
- `"claude-4-opus-20250514"`
Our most capable model
- `"claude-opus-4-1-20250805"`
Our most capable model
- `"claude-3-opus-latest"`
Excels at writing and complex tasks
- `"claude-3-opus-20240229"`
Excels at writing and complex tasks
- `"claude-3-haiku-20240307"`
Our previous most fast and cost-effective
- `(string & {})`
- `role: "assistant"`
Conversational role of the generated message.
This will always be `"assistant"`.
- `"assistant"`
- `stop_reason: BetaStopReason | null`
The reason that we stopped.
This may be one the following values:
* `"end_turn"`: the model reached a natural stopping point
* `"max_tokens"`: we exceeded the requested `max_tokens` or the model's maximum
* `"stop_sequence"`: one of your provided custom `stop_sequences` was generated
* `"tool_use"`: the model invoked one or more tools
* `"pause_turn"`: we paused a long-running turn. You may provide the response back as-is in a subsequent request to let the model continue.
* `"refusal"`: when streaming classifiers intervene to handle potential policy violations
In non-streaming mode this value is always non-null. In streaming mode, it is null in the `message_start` event and non-null otherwise.
- `"end_turn"`
- `"max_tokens"`
- `"stop_sequence"`
- `"tool_use"`
- `"pause_turn"`
- `"refusal"`
- `"model_context_window_exceeded"`
- `stop_sequence: string | null`
Which custom stop sequence was generated, if any.
This value will be a non-null string if one of your custom stop sequences was generated.
- `type: "message"`
Object type.
For Messages, this is always `"message"`.
- `"message"`
- `usage: BetaUsage`
Billing and rate-limit usage.
Anthropic's API bills and rate-limits by token counts, as tokens represent the underlying cost to our systems.
Under the hood, the API transforms requests into a format suitable for the model. The model's output then goes through a parsing stage before becoming an API response. As a result, the token counts in `usage` will not match one-to-one with the exact visible content of an API request or response.
For example, `output_tokens` will be non-zero, even for an empty string response from Claude.
Total input tokens in a request is the summation of `input_tokens`, `cache_creation_input_tokens`, and `cache_read_input_tokens`.
- `cache_creation: BetaCacheCreation | null`
Breakdown of cached tokens by TTL
- `ephemeral_1h_input_tokens: number`
The number of input tokens used to create the 1 hour cache entry.
- `ephemeral_5m_input_tokens: number`
The number of input tokens used to create the 5 minute cache entry.
- `cache_creation_input_tokens: number | null`
The number of input tokens used to create the cache entry.
- `cache_read_input_tokens: number | null`
The number of input tokens read from the cache.
- `input_tokens: number`
The number of input tokens which were used.
- `output_tokens: number`
The number of output tokens which were used.
- `server_tool_use: BetaServerToolUsage | null`
The number of server tool requests.
- `web_fetch_requests: number`
The number of web fetch tool requests.
- `web_search_requests: number`
The number of web search tool requests.
- `service_tier: "standard" | "priority" | "batch" | null`
If the request used the priority, standard, or batch tier.
- `"standard"`
- `"priority"`
- `"batch"`
### Example
```typescript
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic({
apiKey: process.env['ANTHROPIC_API_KEY'], // This is the default and can be omitted
});
const betaMessage = await client.beta.messages.create({
max_tokens: 1024,
messages: [{ content: 'Hello, world', role: 'user' }],
model: 'claude-sonnet-4-5-20250929',
});
console.log(betaMessage.id);
```
## Count Tokens
`client.beta.messages.countTokens(MessageCountTokensParamsparams, RequestOptionsoptions?): BetaMessageTokensCount`
**post** `/v1/messages/count_tokens`
Count the number of tokens in a Message.
The Token Count API can be used to count the number of tokens in a Message, including tools, images, and documents, without creating it.
Learn more about token counting in our [user guide](https://docs.claude.com/en/docs/build-with-claude/token-counting)
### Parameters
- `params: MessageCountTokensParams`
- `messages: Array`
Body param: Input messages.
Our models are trained to operate on alternating `user` and `assistant` conversational turns. When creating a new `Message`, you specify the prior conversational turns with the `messages` parameter, and the model then generates the next `Message` in the conversation. Consecutive `user` or `assistant` turns in your request will be combined into a single turn.
Each input message must be an object with a `role` and `content`. You can specify a single `user`-role message, or you can include multiple `user` and `assistant` messages.
If the final message uses the `assistant` role, the response content will continue immediately from the content in that message. This can be used to constrain part of the model's response.
Example with a single `user` message:
```json
[{"role": "user", "content": "Hello, Claude"}]
```
Example with multiple conversational turns:
```json
[
{"role": "user", "content": "Hello there."},
{"role": "assistant", "content": "Hi, I'm Claude. How can I help you?"},
{"role": "user", "content": "Can you explain LLMs in plain English?"},
]
```
Example with a partially-filled response from Claude:
```json
[
{"role": "user", "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"},
{"role": "assistant", "content": "The best answer is ("},
]
```
Each input message `content` may be either a single `string` or an array of content blocks, where each block has a specific `type`. Using a `string` for `content` is shorthand for an array of one content block of type `"text"`. The following input messages are equivalent:
```json
{"role": "user", "content": "Hello, Claude"}
```
```json
{"role": "user", "content": [{"type": "text", "text": "Hello, Claude"}]}
```
See [input examples](https://docs.claude.com/en/api/messages-examples).
Note that if you want to include a [system prompt](https://docs.claude.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 100,000 messages in a single request.
- `content: string | Array`
- `string`
- `Array`
- `BetaTextBlockParam`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `BetaCitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `BetaImageBlockParam`
- `source: BetaBase64ImageSource | BetaURLImageSource | BetaFileImageSource`
- `BetaBase64ImageSource`
- `data: string`
- `media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"`
- `"image/jpeg"`
- `"image/png"`
- `"image/gif"`
- `"image/webp"`
- `type: "base64"`
- `"base64"`
- `BetaURLImageSource`
- `type: "url"`
- `"url"`
- `url: string`
- `BetaFileImageSource`
- `file_id: string`
- `type: "file"`
- `"file"`
- `type: "image"`
- `"image"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `BetaRequestDocumentBlock`
- `source: BetaBase64PDFSource | BetaPlainTextSource | BetaContentBlockSource | 2 more`
- `BetaBase64PDFSource`
- `data: string`
- `media_type: "application/pdf"`
- `"application/pdf"`
- `type: "base64"`
- `"base64"`
- `BetaPlainTextSource`
- `data: string`
- `media_type: "text/plain"`
- `"text/plain"`
- `type: "text"`
- `"text"`
- `BetaContentBlockSource`
- `content: string | Array`
- `string`
- `Array`
- `BetaTextBlockParam`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `BetaCitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `BetaImageBlockParam`
- `source: BetaBase64ImageSource | BetaURLImageSource | BetaFileImageSource`
- `BetaBase64ImageSource`
- `data: string`
- `media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"`
- `"image/jpeg"`
- `"image/png"`
- `"image/gif"`
- `"image/webp"`
- `type: "base64"`
- `"base64"`
- `BetaURLImageSource`
- `type: "url"`
- `"url"`
- `url: string`
- `BetaFileImageSource`
- `file_id: string`
- `type: "file"`
- `"file"`
- `type: "image"`
- `"image"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `type: "content"`
- `"content"`
- `BetaURLPDFSource`
- `type: "url"`
- `"url"`
- `url: string`
- `BetaFileDocumentSource`
- `file_id: string`
- `type: "file"`
- `"file"`
- `type: "document"`
- `"document"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: BetaCitationsConfigParam | null`
- `enabled?: boolean`
- `context?: string | null`
- `title?: string | null`
- `BetaSearchResultBlockParam`
- `content: Array`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `BetaCitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `source: string`
- `title: string`
- `type: "search_result"`
- `"search_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: BetaCitationsConfigParam`
- `enabled?: boolean`
- `BetaThinkingBlockParam`
- `signature: string`
- `thinking: string`
- `type: "thinking"`
- `"thinking"`
- `BetaRedactedThinkingBlockParam`
- `data: string`
- `type: "redacted_thinking"`
- `"redacted_thinking"`
- `BetaToolUseBlockParam`
- `id: string`
- `input: Record`
- `name: string`
- `type: "tool_use"`
- `"tool_use"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `caller?: BetaDirectCaller | BetaServerToolCaller`
Tool invocation directly from the model.
- `BetaDirectCaller`
Tool invocation directly from the model.
- `type: "direct"`
- `"direct"`
- `BetaServerToolCaller`
Tool invocation generated by a server-side tool.
- `tool_id: string`
- `type: "code_execution_20250825"`
- `"code_execution_20250825"`
- `BetaToolResultBlockParam`
- `tool_use_id: string`
- `type: "tool_result"`
- `"tool_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `content?: string | Array`
- `string`
- `Array`
- `BetaTextBlockParam`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `BetaCitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `BetaImageBlockParam`
- `source: BetaBase64ImageSource | BetaURLImageSource | BetaFileImageSource`
- `BetaBase64ImageSource`
- `data: string`
- `media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"`
- `"image/jpeg"`
- `"image/png"`
- `"image/gif"`
- `"image/webp"`
- `type: "base64"`
- `"base64"`
- `BetaURLImageSource`
- `type: "url"`
- `"url"`
- `url: string`
- `BetaFileImageSource`
- `file_id: string`
- `type: "file"`
- `"file"`
- `type: "image"`
- `"image"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `BetaSearchResultBlockParam`
- `content: Array`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `BetaCitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `source: string`
- `title: string`
- `type: "search_result"`
- `"search_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: BetaCitationsConfigParam`
- `enabled?: boolean`
- `BetaRequestDocumentBlock`
- `source: BetaBase64PDFSource | BetaPlainTextSource | BetaContentBlockSource | 2 more`
- `BetaBase64PDFSource`
- `data: string`
- `media_type: "application/pdf"`
- `"application/pdf"`
- `type: "base64"`
- `"base64"`
- `BetaPlainTextSource`
- `data: string`
- `media_type: "text/plain"`
- `"text/plain"`
- `type: "text"`
- `"text"`
- `BetaContentBlockSource`
- `content: string | Array`
- `string`
- `Array`
- `BetaTextBlockParam`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `BetaCitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `BetaImageBlockParam`
- `source: BetaBase64ImageSource | BetaURLImageSource | BetaFileImageSource`
- `BetaBase64ImageSource`
- `data: string`
- `media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"`
- `"image/jpeg"`
- `"image/png"`
- `"image/gif"`
- `"image/webp"`
- `type: "base64"`
- `"base64"`
- `BetaURLImageSource`
- `type: "url"`
- `"url"`
- `url: string`
- `BetaFileImageSource`
- `file_id: string`
- `type: "file"`
- `"file"`
- `type: "image"`
- `"image"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `type: "content"`
- `"content"`
- `BetaURLPDFSource`
- `type: "url"`
- `"url"`
- `url: string`
- `BetaFileDocumentSource`
- `file_id: string`
- `type: "file"`
- `"file"`
- `type: "document"`
- `"document"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: BetaCitationsConfigParam | null`
- `enabled?: boolean`
- `context?: string | null`
- `title?: string | null`
- `BetaToolReferenceBlockParam`
Tool reference block that can be included in tool_result content.
- `tool_name: string`
- `type: "tool_reference"`
- `"tool_reference"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `is_error?: boolean`
- `BetaServerToolUseBlockParam`
- `id: string`
- `input: Record`
- `name: "web_search" | "web_fetch" | "code_execution" | 4 more`
- `"web_search"`
- `"web_fetch"`
- `"code_execution"`
- `"bash_code_execution"`
- `"text_editor_code_execution"`
- `"tool_search_tool_regex"`
- `"tool_search_tool_bm25"`
- `type: "server_tool_use"`
- `"server_tool_use"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `caller?: BetaDirectCaller | BetaServerToolCaller`
Tool invocation directly from the model.
- `BetaDirectCaller`
Tool invocation directly from the model.
- `type: "direct"`
- `"direct"`
- `BetaServerToolCaller`
Tool invocation generated by a server-side tool.
- `tool_id: string`
- `type: "code_execution_20250825"`
- `"code_execution_20250825"`
- `BetaWebSearchToolResultBlockParam`
- `content: BetaWebSearchToolResultBlockParamContent`
- `Array`
- `encrypted_content: string`
- `title: string`
- `type: "web_search_result"`
- `"web_search_result"`
- `url: string`
- `page_age?: string | null`
- `BetaWebSearchToolRequestError`
- `error_code: BetaWebSearchToolResultErrorCode`
- `"invalid_tool_input"`
- `"unavailable"`
- `"max_uses_exceeded"`
- `"too_many_requests"`
- `"query_too_long"`
- `"request_too_large"`
- `type: "web_search_tool_result_error"`
- `"web_search_tool_result_error"`
- `tool_use_id: string`
- `type: "web_search_tool_result"`
- `"web_search_tool_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `BetaWebFetchToolResultBlockParam`
- `content: BetaWebFetchToolResultErrorBlockParam | BetaWebFetchBlockParam`
- `BetaWebFetchToolResultErrorBlockParam`
- `error_code: BetaWebFetchToolResultErrorCode`
- `"invalid_tool_input"`
- `"url_too_long"`
- `"url_not_allowed"`
- `"url_not_accessible"`
- `"unsupported_content_type"`
- `"too_many_requests"`
- `"max_uses_exceeded"`
- `"unavailable"`
- `type: "web_fetch_tool_result_error"`
- `"web_fetch_tool_result_error"`
- `BetaWebFetchBlockParam`
- `content: BetaRequestDocumentBlock`
- `source: BetaBase64PDFSource | BetaPlainTextSource | BetaContentBlockSource | 2 more`
- `BetaBase64PDFSource`
- `data: string`
- `media_type: "application/pdf"`
- `"application/pdf"`
- `type: "base64"`
- `"base64"`
- `BetaPlainTextSource`
- `data: string`
- `media_type: "text/plain"`
- `"text/plain"`
- `type: "text"`
- `"text"`
- `BetaContentBlockSource`
- `content: string | Array`
- `string`
- `Array`
- `BetaTextBlockParam`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `BetaCitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `BetaImageBlockParam`
- `source: BetaBase64ImageSource | BetaURLImageSource | BetaFileImageSource`
- `BetaBase64ImageSource`
- `data: string`
- `media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"`
- `"image/jpeg"`
- `"image/png"`
- `"image/gif"`
- `"image/webp"`
- `type: "base64"`
- `"base64"`
- `BetaURLImageSource`
- `type: "url"`
- `"url"`
- `url: string`
- `BetaFileImageSource`
- `file_id: string`
- `type: "file"`
- `"file"`
- `type: "image"`
- `"image"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `type: "content"`
- `"content"`
- `BetaURLPDFSource`
- `type: "url"`
- `"url"`
- `url: string`
- `BetaFileDocumentSource`
- `file_id: string`
- `type: "file"`
- `"file"`
- `type: "document"`
- `"document"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: BetaCitationsConfigParam | null`
- `enabled?: boolean`
- `context?: string | null`
- `title?: string | null`
- `type: "web_fetch_result"`
- `"web_fetch_result"`
- `url: string`
Fetched content URL
- `retrieved_at?: string | null`
ISO 8601 timestamp when the content was retrieved
- `tool_use_id: string`
- `type: "web_fetch_tool_result"`
- `"web_fetch_tool_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `BetaCodeExecutionToolResultBlockParam`
- `content: BetaCodeExecutionToolResultBlockParamContent`
- `BetaCodeExecutionToolResultErrorParam`
- `error_code: BetaCodeExecutionToolResultErrorCode`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `type: "code_execution_tool_result_error"`
- `"code_execution_tool_result_error"`
- `BetaCodeExecutionResultBlockParam`
- `content: Array`
- `file_id: string`
- `type: "code_execution_output"`
- `"code_execution_output"`
- `return_code: number`
- `stderr: string`
- `stdout: string`
- `type: "code_execution_result"`
- `"code_execution_result"`
- `tool_use_id: string`
- `type: "code_execution_tool_result"`
- `"code_execution_tool_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `BetaBashCodeExecutionToolResultBlockParam`
- `content: BetaBashCodeExecutionToolResultErrorParam | BetaBashCodeExecutionResultBlockParam`
- `BetaBashCodeExecutionToolResultErrorParam`
- `error_code: "invalid_tool_input" | "unavailable" | "too_many_requests" | 2 more`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `"output_file_too_large"`
- `type: "bash_code_execution_tool_result_error"`
- `"bash_code_execution_tool_result_error"`
- `BetaBashCodeExecutionResultBlockParam`
- `content: Array`
- `file_id: string`
- `type: "bash_code_execution_output"`
- `"bash_code_execution_output"`
- `return_code: number`
- `stderr: string`
- `stdout: string`
- `type: "bash_code_execution_result"`
- `"bash_code_execution_result"`
- `tool_use_id: string`
- `type: "bash_code_execution_tool_result"`
- `"bash_code_execution_tool_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `BetaTextEditorCodeExecutionToolResultBlockParam`
- `content: BetaTextEditorCodeExecutionToolResultErrorParam | BetaTextEditorCodeExecutionViewResultBlockParam | BetaTextEditorCodeExecutionCreateResultBlockParam | BetaTextEditorCodeExecutionStrReplaceResultBlockParam`
- `BetaTextEditorCodeExecutionToolResultErrorParam`
- `error_code: "invalid_tool_input" | "unavailable" | "too_many_requests" | 2 more`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `"file_not_found"`
- `type: "text_editor_code_execution_tool_result_error"`
- `"text_editor_code_execution_tool_result_error"`
- `error_message?: string | null`
- `BetaTextEditorCodeExecutionViewResultBlockParam`
- `content: string`
- `file_type: "text" | "image" | "pdf"`
- `"text"`
- `"image"`
- `"pdf"`
- `type: "text_editor_code_execution_view_result"`
- `"text_editor_code_execution_view_result"`
- `num_lines?: number | null`
- `start_line?: number | null`
- `total_lines?: number | null`
- `BetaTextEditorCodeExecutionCreateResultBlockParam`
- `is_file_update: boolean`
- `type: "text_editor_code_execution_create_result"`
- `"text_editor_code_execution_create_result"`
- `BetaTextEditorCodeExecutionStrReplaceResultBlockParam`
- `type: "text_editor_code_execution_str_replace_result"`
- `"text_editor_code_execution_str_replace_result"`
- `lines?: Array | null`
- `new_lines?: number | null`
- `new_start?: number | null`
- `old_lines?: number | null`
- `old_start?: number | null`
- `tool_use_id: string`
- `type: "text_editor_code_execution_tool_result"`
- `"text_editor_code_execution_tool_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `BetaToolSearchToolResultBlockParam`
- `content: BetaToolSearchToolResultErrorParam | BetaToolSearchToolSearchResultBlockParam`
- `BetaToolSearchToolResultErrorParam`
- `error_code: "invalid_tool_input" | "unavailable" | "too_many_requests" | "execution_time_exceeded"`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `type: "tool_search_tool_result_error"`
- `"tool_search_tool_result_error"`
- `BetaToolSearchToolSearchResultBlockParam`
- `tool_references: Array`
- `tool_name: string`
- `type: "tool_reference"`
- `"tool_reference"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `type: "tool_search_tool_search_result"`
- `"tool_search_tool_search_result"`
- `tool_use_id: string`
- `type: "tool_search_tool_result"`
- `"tool_search_tool_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `BetaMCPToolUseBlockParam`
- `id: string`
- `input: Record`
- `name: string`
- `server_name: string`
The name of the MCP server
- `type: "mcp_tool_use"`
- `"mcp_tool_use"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `BetaRequestMCPToolResultBlockParam`
- `tool_use_id: string`
- `type: "mcp_tool_result"`
- `"mcp_tool_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `content?: string | Array`
- `string`
- `Array`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `BetaCitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `is_error?: boolean`
- `BetaContainerUploadBlockParam`
A content block that represents a file to be uploaded to the container
Files uploaded via this block will be available in the container's input directory.
- `file_id: string`
- `type: "container_upload"`
- `"container_upload"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `role: "user" | "assistant"`
- `"user"`
- `"assistant"`
- `model: Model`
Body param: The model that will complete your prompt.
See [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options.
- `"claude-opus-4-5-20251101" | "claude-opus-4-5" | "claude-3-7-sonnet-latest" | 17 more`
- `"claude-opus-4-5-20251101"`
Premium model combining maximum intelligence with practical performance
- `"claude-opus-4-5"`
Premium model combining maximum intelligence with practical performance
- `"claude-3-7-sonnet-latest"`
High-performance model with early extended thinking
- `"claude-3-7-sonnet-20250219"`
High-performance model with early extended thinking
- `"claude-3-5-haiku-latest"`
Fastest and most compact model for near-instant responsiveness
- `"claude-3-5-haiku-20241022"`
Our fastest model
- `"claude-haiku-4-5"`
Hybrid model, capable of near-instant responses and extended thinking
- `"claude-haiku-4-5-20251001"`
Hybrid model, capable of near-instant responses and extended thinking
- `"claude-sonnet-4-20250514"`
High-performance model with extended thinking
- `"claude-sonnet-4-0"`
High-performance model with extended thinking
- `"claude-4-sonnet-20250514"`
High-performance model with extended thinking
- `"claude-sonnet-4-5"`
Our best model for real-world agents and coding
- `"claude-sonnet-4-5-20250929"`
Our best model for real-world agents and coding
- `"claude-opus-4-0"`
Our most capable model
- `"claude-opus-4-20250514"`
Our most capable model
- `"claude-4-opus-20250514"`
Our most capable model
- `"claude-opus-4-1-20250805"`
Our most capable model
- `"claude-3-opus-latest"`
Excels at writing and complex tasks
- `"claude-3-opus-20240229"`
Excels at writing and complex tasks
- `"claude-3-haiku-20240307"`
Our previous most fast and cost-effective
- `(string & {})`
- `context_management?: BetaContextManagementConfig | null`
Body param: Context management configuration.
This allows you to control how Claude manages context across multiple requests, such as whether to clear function results or not.
- `edits?: Array`
List of context management edits to apply
- `BetaClearToolUses20250919Edit`
- `type: "clear_tool_uses_20250919"`
- `"clear_tool_uses_20250919"`
- `clear_at_least?: BetaInputTokensClearAtLeast | null`
Minimum number of tokens that must be cleared when triggered. Context will only be modified if at least this many tokens can be removed.
- `type: "input_tokens"`
- `"input_tokens"`
- `value: number`
- `clear_tool_inputs?: boolean | Array | null`
Whether to clear all tool inputs (bool) or specific tool inputs to clear (list)
- `boolean`
- `Array`
- `exclude_tools?: Array | null`
Tool names whose uses are preserved from clearing
- `keep?: BetaToolUsesKeep`
Number of tool uses to retain in the conversation
- `type: "tool_uses"`
- `"tool_uses"`
- `value: number`
- `trigger?: BetaInputTokensTrigger | BetaToolUsesTrigger`
Condition that triggers the context management strategy
- `BetaInputTokensTrigger`
- `type: "input_tokens"`
- `"input_tokens"`
- `value: number`
- `BetaToolUsesTrigger`
- `type: "tool_uses"`
- `"tool_uses"`
- `value: number`
- `BetaClearThinking20251015Edit`
- `type: "clear_thinking_20251015"`
- `"clear_thinking_20251015"`
- `keep?: BetaThinkingTurns | BetaAllThinkingTurns | "all"`
Number of most recent assistant turns to keep thinking blocks for. Older turns will have their thinking blocks removed.
- `BetaThinkingTurns`
- `type: "thinking_turns"`
- `"thinking_turns"`
- `value: number`
- `BetaAllThinkingTurns`
- `type: "all"`
- `"all"`
- `"all"`
- `"all"`
- `mcp_servers?: Array`
Body param: MCP servers to be utilized in this request
- `name: string`
- `type: "url"`
- `"url"`
- `url: string`
- `authorization_token?: string | null`
- `tool_configuration?: BetaRequestMCPServerToolConfiguration | null`
- `allowed_tools?: Array | null`
- `enabled?: boolean | null`
- `output_config?: BetaOutputConfig`
Body param: Configuration options for the model's output, such as the output format.
- `effort?: "low" | "medium" | "high" | null`
How much effort the model should put into its response. Higher effort levels may result in more thorough analysis but take longer.
Valid values are `low`, `medium`, or `high`.
- `"low"`
- `"medium"`
- `"high"`
- `format?: BetaJSONOutputFormat | null`
A schema to specify Claude's output format in responses. See [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)
- `schema: Record`
The JSON schema of the format
- `type: "json_schema"`
- `"json_schema"`
- `output_format?: BetaJSONOutputFormat | null`
Body param: Deprecated: Use `output_config.format` instead. See [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)
A schema to specify Claude's output format in responses. This parameter will be removed in a future release.
- `schema: Record`
The JSON schema of the format
- `type: "json_schema"`
- `"json_schema"`
- `system?: string | Array`
Body param: System prompt.
A system prompt is a way of providing context and instructions to Claude, such as specifying a particular goal or role. See our [guide to system prompts](https://docs.claude.com/en/docs/system-prompts).
- `string`
- `Array`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `BetaCitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `thinking?: BetaThinkingConfigParam`
Body param: Configuration for enabling Claude's extended thinking.
When enabled, responses include `thinking` content blocks showing Claude's thinking process before the final answer. Requires a minimum budget of 1,024 tokens and counts towards your `max_tokens` limit.
See [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) for details.
- `BetaThinkingConfigEnabled`
- `budget_tokens: number`
Determines how many tokens Claude can use for its internal reasoning process. Larger budgets can enable more thorough analysis for complex problems, improving response quality.
Must be ≥1024 and less than `max_tokens`.
See [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) for details.
- `type: "enabled"`
- `"enabled"`
- `BetaThinkingConfigDisabled`
- `type: "disabled"`
- `"disabled"`
- `tool_choice?: BetaToolChoice`
Body param: How the model should use the provided tools. The model can use a specific tool, any available tool, decide by itself, or not use tools at all.
- `BetaToolChoiceAuto`
The model will automatically decide whether to use tools.
- `type: "auto"`
- `"auto"`
- `disable_parallel_tool_use?: boolean`
Whether to disable parallel tool use.
Defaults to `false`. If set to `true`, the model will output at most one tool use.
- `BetaToolChoiceAny`
The model will use any available tools.
- `type: "any"`
- `"any"`
- `disable_parallel_tool_use?: boolean`
Whether to disable parallel tool use.
Defaults to `false`. If set to `true`, the model will output exactly one tool use.
- `BetaToolChoiceTool`
The model will use the specified tool with `tool_choice.name`.
- `name: string`
The name of the tool to use.
- `type: "tool"`
- `"tool"`
- `disable_parallel_tool_use?: boolean`
Whether to disable parallel tool use.
Defaults to `false`. If set to `true`, the model will output exactly one tool use.
- `BetaToolChoiceNone`
The model will not be allowed to use tools.
- `type: "none"`
- `"none"`
- `tools?: Array`
Body param: Definitions of tools that the model may use.
If you include `tools` in your API request, the model may return `tool_use` content blocks that represent the model's use of those tools. You can then run those tools using the tool input generated by the model and then optionally return results back to the model using `tool_result` content blocks.
There are two types of tools: **client tools** and **server tools**. The behavior described below applies to client tools. For [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview#server-tools), see their individual documentation as each has its own behavior (e.g., the [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)).
Each tool definition includes:
* `name`: Name of the tool.
* `description`: Optional, but strongly-recommended description of the tool.
* `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the tool `input` shape that the model will produce in `tool_use` output content blocks.
For example, if you defined `tools` as:
```json
[
{
"name": "get_stock_price",
"description": "Get the current stock price for a given ticker symbol.",
"input_schema": {
"type": "object",
"properties": {
"ticker": {
"type": "string",
"description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
}
},
"required": ["ticker"]
}
}
]
```
And then asked the model "What's the S&P 500 at today?", the model might produce `tool_use` content blocks in the response like this:
```json
[
{
"type": "tool_use",
"id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
"name": "get_stock_price",
"input": { "ticker": "^GSPC" }
}
]
```
You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an input, and return the following back to the model in a subsequent `user` message:
```json
[
{
"type": "tool_result",
"tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
"content": "259.75 USD"
}
]
```
Tools can be used for workflows that include running client-side tools and functions, or more generally whenever you want the model to produce a particular JSON structure of output.
See our [guide](https://docs.claude.com/en/docs/tool-use) for more details.
- `BetaTool`
- `input_schema: InputSchema`
[JSON schema](https://json-schema.org/draft/2020-12) for this tool's input.
This defines the shape of the `input` that your tool accepts and that the model will produce.
- `type: "object"`
- `"object"`
- `properties?: Record | null`
- `required?: Array | null`
- `name: string`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `description?: string`
Description of what this tool does.
Tool descriptions should be as detailed as possible. The more information that the model has about what the tool is and how to use it, the better it will perform. You can use natural language descriptions to reinforce important aspects of the tool input JSON schema.
- `input_examples?: Array>`
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `type?: "custom" | null`
- `"custom"`
- `BetaToolBash20241022`
- `name: "bash"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"bash"`
- `type: "bash_20241022"`
- `"bash_20241022"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `input_examples?: Array>`
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaToolBash20250124`
- `name: "bash"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"bash"`
- `type: "bash_20250124"`
- `"bash_20250124"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `input_examples?: Array>`
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaCodeExecutionTool20250522`
- `name: "code_execution"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"code_execution"`
- `type: "code_execution_20250522"`
- `"code_execution_20250522"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaCodeExecutionTool20250825`
- `name: "code_execution"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"code_execution"`
- `type: "code_execution_20250825"`
- `"code_execution_20250825"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaToolComputerUse20241022`
- `display_height_px: number`
The height of the display in pixels.
- `display_width_px: number`
The width of the display in pixels.
- `name: "computer"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"computer"`
- `type: "computer_20241022"`
- `"computer_20241022"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `display_number?: number | null`
The X11 display number (e.g. 0, 1) for the display.
- `input_examples?: Array>`
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaMemoryTool20250818`
- `name: "memory"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"memory"`
- `type: "memory_20250818"`
- `"memory_20250818"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `input_examples?: Array>`
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaToolComputerUse20250124`
- `display_height_px: number`
The height of the display in pixels.
- `display_width_px: number`
The width of the display in pixels.
- `name: "computer"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"computer"`
- `type: "computer_20250124"`
- `"computer_20250124"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `display_number?: number | null`
The X11 display number (e.g. 0, 1) for the display.
- `input_examples?: Array>`
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaToolTextEditor20241022`
- `name: "str_replace_editor"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"str_replace_editor"`
- `type: "text_editor_20241022"`
- `"text_editor_20241022"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `input_examples?: Array>`
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaToolComputerUse20251124`
- `display_height_px: number`
The height of the display in pixels.
- `display_width_px: number`
The width of the display in pixels.
- `name: "computer"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"computer"`
- `type: "computer_20251124"`
- `"computer_20251124"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `display_number?: number | null`
The X11 display number (e.g. 0, 1) for the display.
- `enable_zoom?: boolean`
Whether to enable an action to take a zoomed-in screenshot of the screen.
- `input_examples?: Array>`
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaToolTextEditor20250124`
- `name: "str_replace_editor"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"str_replace_editor"`
- `type: "text_editor_20250124"`
- `"text_editor_20250124"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `input_examples?: Array>`
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaToolTextEditor20250429`
- `name: "str_replace_based_edit_tool"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"str_replace_based_edit_tool"`
- `type: "text_editor_20250429"`
- `"text_editor_20250429"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `input_examples?: Array>`
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaToolTextEditor20250728`
- `name: "str_replace_based_edit_tool"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"str_replace_based_edit_tool"`
- `type: "text_editor_20250728"`
- `"text_editor_20250728"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `input_examples?: Array>`
- `max_characters?: number | null`
Maximum number of characters to display when viewing a file. If not specified, defaults to displaying the full file.
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaWebSearchTool20250305`
- `name: "web_search"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"web_search"`
- `type: "web_search_20250305"`
- `"web_search_20250305"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `allowed_domains?: Array | null`
If provided, only these domains will be included in results. Cannot be used alongside `blocked_domains`.
- `blocked_domains?: Array | null`
If provided, these domains will never appear in results. Cannot be used alongside `allowed_domains`.
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `max_uses?: number | null`
Maximum number of times the tool can be used in the API request.
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `user_location?: UserLocation | null`
Parameters for the user's location. Used to provide more relevant search results.
- `type: "approximate"`
- `"approximate"`
- `city?: string | null`
The city of the user.
- `country?: string | null`
The two letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the user.
- `region?: string | null`
The region of the user.
- `timezone?: string | null`
The [IANA timezone](https://nodatime.org/TimeZones) of the user.
- `BetaWebFetchTool20250910`
- `name: "web_fetch"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"web_fetch"`
- `type: "web_fetch_20250910"`
- `"web_fetch_20250910"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `allowed_domains?: Array | null`
List of domains to allow fetching from
- `blocked_domains?: Array | null`
List of domains to block fetching from
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: BetaCitationsConfigParam | null`
Citations configuration for fetched documents. Citations are disabled by default.
- `enabled?: boolean`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `max_content_tokens?: number | null`
Maximum number of tokens used by including web page text content in the context. The limit is approximate and does not apply to binary content such as PDFs.
- `max_uses?: number | null`
Maximum number of times the tool can be used in the API request.
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaToolSearchToolBm25_20251119`
- `name: "tool_search_tool_bm25"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"tool_search_tool_bm25"`
- `type: "tool_search_tool_bm25_20251119" | "tool_search_tool_bm25"`
- `"tool_search_tool_bm25_20251119"`
- `"tool_search_tool_bm25"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaToolSearchToolRegex20251119`
- `name: "tool_search_tool_regex"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"tool_search_tool_regex"`
- `type: "tool_search_tool_regex_20251119" | "tool_search_tool_regex"`
- `"tool_search_tool_regex_20251119"`
- `"tool_search_tool_regex"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
- `BetaMCPToolset`
Configuration for a group of tools from an MCP server.
Allows configuring enabled status and defer_loading for all tools
from an MCP server, with optional per-tool overrides.
- `mcp_server_name: string`
Name of the MCP server to configure tools for
- `type: "mcp_toolset"`
- `"mcp_toolset"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `configs?: Record | null`
Configuration overrides for specific tools, keyed by tool name
- `defer_loading?: boolean`
- `enabled?: boolean`
- `default_config?: BetaMCPToolDefaultConfig`
Default configuration applied to all tools from this server
- `defer_loading?: boolean`
- `enabled?: boolean`
- `betas?: Array`
Header param: Optional header to specify the beta version(s) you want to use.
- `(string & {})`
- `"message-batches-2024-09-24" | "prompt-caching-2024-07-31" | "computer-use-2024-10-22" | 16 more`
- `"message-batches-2024-09-24"`
- `"prompt-caching-2024-07-31"`
- `"computer-use-2024-10-22"`
- `"computer-use-2025-01-24"`
- `"pdfs-2024-09-25"`
- `"token-counting-2024-11-01"`
- `"token-efficient-tools-2025-02-19"`
- `"output-128k-2025-02-19"`
- `"files-api-2025-04-14"`
- `"mcp-client-2025-04-04"`
- `"mcp-client-2025-11-20"`
- `"dev-full-thinking-2025-05-14"`
- `"interleaved-thinking-2025-05-14"`
- `"code-execution-2025-05-22"`
- `"extended-cache-ttl-2025-04-11"`
- `"context-1m-2025-08-07"`
- `"context-management-2025-06-27"`
- `"model-context-window-exceeded-2025-08-26"`
- `"skills-2025-10-02"`
### Returns
- `BetaMessageTokensCount`
- `context_management: BetaCountTokensContextManagementResponse | null`
Information about context management applied to the message.
- `original_input_tokens: number`
The original token count before context management was applied
- `input_tokens: number`
The total number of tokens across the provided list of messages, system prompt, and tools.
### Example
```typescript
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic({
apiKey: process.env['ANTHROPIC_API_KEY'], // This is the default and can be omitted
});
const betaMessageTokensCount = await client.beta.messages.countTokens({
messages: [{ content: 'string', role: 'user' }],
model: 'claude-opus-4-5-20251101',
});
console.log(betaMessageTokensCount.context_management);
```
## Domain Types
### Beta All Thinking Turns
- `BetaAllThinkingTurns`
- `type: "all"`
- `"all"`
### Beta Base64 Image Source
- `BetaBase64ImageSource`
- `data: string`
- `media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"`
- `"image/jpeg"`
- `"image/png"`
- `"image/gif"`
- `"image/webp"`
- `type: "base64"`
- `"base64"`
### Beta Base64 PDF Source
- `BetaBase64PDFSource`
- `data: string`
- `media_type: "application/pdf"`
- `"application/pdf"`
- `type: "base64"`
- `"base64"`
### Beta Bash Code Execution Output Block
- `BetaBashCodeExecutionOutputBlock`
- `file_id: string`
- `type: "bash_code_execution_output"`
- `"bash_code_execution_output"`
### Beta Bash Code Execution Output Block Param
- `BetaBashCodeExecutionOutputBlockParam`
- `file_id: string`
- `type: "bash_code_execution_output"`
- `"bash_code_execution_output"`
### Beta Bash Code Execution Result Block
- `BetaBashCodeExecutionResultBlock`
- `content: Array`
- `file_id: string`
- `type: "bash_code_execution_output"`
- `"bash_code_execution_output"`
- `return_code: number`
- `stderr: string`
- `stdout: string`
- `type: "bash_code_execution_result"`
- `"bash_code_execution_result"`
### Beta Bash Code Execution Result Block Param
- `BetaBashCodeExecutionResultBlockParam`
- `content: Array`
- `file_id: string`
- `type: "bash_code_execution_output"`
- `"bash_code_execution_output"`
- `return_code: number`
- `stderr: string`
- `stdout: string`
- `type: "bash_code_execution_result"`
- `"bash_code_execution_result"`
### Beta Bash Code Execution Tool Result Block
- `BetaBashCodeExecutionToolResultBlock`
- `content: BetaBashCodeExecutionToolResultError | BetaBashCodeExecutionResultBlock`
- `BetaBashCodeExecutionToolResultError`
- `error_code: "invalid_tool_input" | "unavailable" | "too_many_requests" | 2 more`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `"output_file_too_large"`
- `type: "bash_code_execution_tool_result_error"`
- `"bash_code_execution_tool_result_error"`
- `BetaBashCodeExecutionResultBlock`
- `content: Array`
- `file_id: string`
- `type: "bash_code_execution_output"`
- `"bash_code_execution_output"`
- `return_code: number`
- `stderr: string`
- `stdout: string`
- `type: "bash_code_execution_result"`
- `"bash_code_execution_result"`
- `tool_use_id: string`
- `type: "bash_code_execution_tool_result"`
- `"bash_code_execution_tool_result"`
### Beta Bash Code Execution Tool Result Block Param
- `BetaBashCodeExecutionToolResultBlockParam`
- `content: BetaBashCodeExecutionToolResultErrorParam | BetaBashCodeExecutionResultBlockParam`
- `BetaBashCodeExecutionToolResultErrorParam`
- `error_code: "invalid_tool_input" | "unavailable" | "too_many_requests" | 2 more`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `"output_file_too_large"`
- `type: "bash_code_execution_tool_result_error"`
- `"bash_code_execution_tool_result_error"`
- `BetaBashCodeExecutionResultBlockParam`
- `content: Array`
- `file_id: string`
- `type: "bash_code_execution_output"`
- `"bash_code_execution_output"`
- `return_code: number`
- `stderr: string`
- `stdout: string`
- `type: "bash_code_execution_result"`
- `"bash_code_execution_result"`
- `tool_use_id: string`
- `type: "bash_code_execution_tool_result"`
- `"bash_code_execution_tool_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
### Beta Bash Code Execution Tool Result Error
- `BetaBashCodeExecutionToolResultError`
- `error_code: "invalid_tool_input" | "unavailable" | "too_many_requests" | 2 more`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `"output_file_too_large"`
- `type: "bash_code_execution_tool_result_error"`
- `"bash_code_execution_tool_result_error"`
### Beta Bash Code Execution Tool Result Error Param
- `BetaBashCodeExecutionToolResultErrorParam`
- `error_code: "invalid_tool_input" | "unavailable" | "too_many_requests" | 2 more`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `"output_file_too_large"`
- `type: "bash_code_execution_tool_result_error"`
- `"bash_code_execution_tool_result_error"`
### Beta Cache Control Ephemeral
- `BetaCacheControlEphemeral`
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
### Beta Cache Creation
- `BetaCacheCreation`
- `ephemeral_1h_input_tokens: number`
The number of input tokens used to create the 1 hour cache entry.
- `ephemeral_5m_input_tokens: number`
The number of input tokens used to create the 5 minute cache entry.
### Beta Citation Char Location
- `BetaCitationCharLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `file_id: string | null`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
### Beta Citation Char Location Param
- `BetaCitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
### Beta Citation Config
- `BetaCitationConfig`
- `enabled: boolean`
### Beta Citation Content Block Location
- `BetaCitationContentBlockLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `file_id: string | null`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
### Beta Citation Content Block Location Param
- `BetaCitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
### Beta Citation Page Location
- `BetaCitationPageLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `file_id: string | null`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
### Beta Citation Page Location Param
- `BetaCitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
### Beta Citation Search Result Location
- `BetaCitationSearchResultLocation`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
### Beta Citation Search Result Location Param
- `BetaCitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
### Beta Citation Web Search Result Location Param
- `BetaCitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
### Beta Citations Config Param
- `BetaCitationsConfigParam`
- `enabled?: boolean`
### Beta Citations Delta
- `BetaCitationsDelta`
- `citation: BetaCitationCharLocation | BetaCitationPageLocation | BetaCitationContentBlockLocation | 2 more`
- `BetaCitationCharLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `file_id: string | null`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `file_id: string | null`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `file_id: string | null`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationsWebSearchResultLocation`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocation`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `type: "citations_delta"`
- `"citations_delta"`
### Beta Citations Web Search Result Location
- `BetaCitationsWebSearchResultLocation`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
### Beta Clear Thinking 20251015 Edit
- `BetaClearThinking20251015Edit`
- `type: "clear_thinking_20251015"`
- `"clear_thinking_20251015"`
- `keep?: BetaThinkingTurns | BetaAllThinkingTurns | "all"`
Number of most recent assistant turns to keep thinking blocks for. Older turns will have their thinking blocks removed.
- `BetaThinkingTurns`
- `type: "thinking_turns"`
- `"thinking_turns"`
- `value: number`
- `BetaAllThinkingTurns`
- `type: "all"`
- `"all"`
- `"all"`
- `"all"`
### Beta Clear Thinking 20251015 Edit Response
- `BetaClearThinking20251015EditResponse`
- `cleared_input_tokens: number`
Number of input tokens cleared by this edit.
- `cleared_thinking_turns: number`
Number of thinking turns that were cleared.
- `type: "clear_thinking_20251015"`
The type of context management edit applied.
- `"clear_thinking_20251015"`
### Beta Clear Tool Uses 20250919 Edit
- `BetaClearToolUses20250919Edit`
- `type: "clear_tool_uses_20250919"`
- `"clear_tool_uses_20250919"`
- `clear_at_least?: BetaInputTokensClearAtLeast | null`
Minimum number of tokens that must be cleared when triggered. Context will only be modified if at least this many tokens can be removed.
- `type: "input_tokens"`
- `"input_tokens"`
- `value: number`
- `clear_tool_inputs?: boolean | Array | null`
Whether to clear all tool inputs (bool) or specific tool inputs to clear (list)
- `boolean`
- `Array`
- `exclude_tools?: Array | null`
Tool names whose uses are preserved from clearing
- `keep?: BetaToolUsesKeep`
Number of tool uses to retain in the conversation
- `type: "tool_uses"`
- `"tool_uses"`
- `value: number`
- `trigger?: BetaInputTokensTrigger | BetaToolUsesTrigger`
Condition that triggers the context management strategy
- `BetaInputTokensTrigger`
- `type: "input_tokens"`
- `"input_tokens"`
- `value: number`
- `BetaToolUsesTrigger`
- `type: "tool_uses"`
- `"tool_uses"`
- `value: number`
### Beta Clear Tool Uses 20250919 Edit Response
- `BetaClearToolUses20250919EditResponse`
- `cleared_input_tokens: number`
Number of input tokens cleared by this edit.
- `cleared_tool_uses: number`
Number of tool uses that were cleared.
- `type: "clear_tool_uses_20250919"`
The type of context management edit applied.
- `"clear_tool_uses_20250919"`
### Beta Code Execution Output Block
- `BetaCodeExecutionOutputBlock`
- `file_id: string`
- `type: "code_execution_output"`
- `"code_execution_output"`
### Beta Code Execution Output Block Param
- `BetaCodeExecutionOutputBlockParam`
- `file_id: string`
- `type: "code_execution_output"`
- `"code_execution_output"`
### Beta Code Execution Result Block
- `BetaCodeExecutionResultBlock`
- `content: Array`
- `file_id: string`
- `type: "code_execution_output"`
- `"code_execution_output"`
- `return_code: number`
- `stderr: string`
- `stdout: string`
- `type: "code_execution_result"`
- `"code_execution_result"`
### Beta Code Execution Result Block Param
- `BetaCodeExecutionResultBlockParam`
- `content: Array`
- `file_id: string`
- `type: "code_execution_output"`
- `"code_execution_output"`
- `return_code: number`
- `stderr: string`
- `stdout: string`
- `type: "code_execution_result"`
- `"code_execution_result"`
### Beta Code Execution Tool 20250522
- `BetaCodeExecutionTool20250522`
- `name: "code_execution"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"code_execution"`
- `type: "code_execution_20250522"`
- `"code_execution_20250522"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
### Beta Code Execution Tool 20250825
- `BetaCodeExecutionTool20250825`
- `name: "code_execution"`
Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
- `"code_execution"`
- `type: "code_execution_20250825"`
- `"code_execution_20250825"`
- `allowed_callers?: Array<"direct" | "code_execution_20250825">`
- `"direct"`
- `"code_execution_20250825"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `defer_loading?: boolean`
If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search.
- `strict?: boolean`
When true, guarantees schema validation on tool names and inputs
### Beta Code Execution Tool Result Block
- `BetaCodeExecutionToolResultBlock`
- `content: BetaCodeExecutionToolResultBlockContent`
- `BetaCodeExecutionToolResultError`
- `error_code: BetaCodeExecutionToolResultErrorCode`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `type: "code_execution_tool_result_error"`
- `"code_execution_tool_result_error"`
- `BetaCodeExecutionResultBlock`
- `content: Array`
- `file_id: string`
- `type: "code_execution_output"`
- `"code_execution_output"`
- `return_code: number`
- `stderr: string`
- `stdout: string`
- `type: "code_execution_result"`
- `"code_execution_result"`
- `tool_use_id: string`
- `type: "code_execution_tool_result"`
- `"code_execution_tool_result"`
### Beta Code Execution Tool Result Block Content
- `BetaCodeExecutionToolResultBlockContent = BetaCodeExecutionToolResultError | BetaCodeExecutionResultBlock`
- `BetaCodeExecutionToolResultError`
- `error_code: BetaCodeExecutionToolResultErrorCode`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `type: "code_execution_tool_result_error"`
- `"code_execution_tool_result_error"`
- `BetaCodeExecutionResultBlock`
- `content: Array`
- `file_id: string`
- `type: "code_execution_output"`
- `"code_execution_output"`
- `return_code: number`
- `stderr: string`
- `stdout: string`
- `type: "code_execution_result"`
- `"code_execution_result"`
### Beta Code Execution Tool Result Block Param
- `BetaCodeExecutionToolResultBlockParam`
- `content: BetaCodeExecutionToolResultBlockParamContent`
- `BetaCodeExecutionToolResultErrorParam`
- `error_code: BetaCodeExecutionToolResultErrorCode`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `type: "code_execution_tool_result_error"`
- `"code_execution_tool_result_error"`
- `BetaCodeExecutionResultBlockParam`
- `content: Array`
- `file_id: string`
- `type: "code_execution_output"`
- `"code_execution_output"`
- `return_code: number`
- `stderr: string`
- `stdout: string`
- `type: "code_execution_result"`
- `"code_execution_result"`
- `tool_use_id: string`
- `type: "code_execution_tool_result"`
- `"code_execution_tool_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
### Beta Code Execution Tool Result Block Param Content
- `BetaCodeExecutionToolResultBlockParamContent = BetaCodeExecutionToolResultErrorParam | BetaCodeExecutionResultBlockParam`
- `BetaCodeExecutionToolResultErrorParam`
- `error_code: BetaCodeExecutionToolResultErrorCode`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `type: "code_execution_tool_result_error"`
- `"code_execution_tool_result_error"`
- `BetaCodeExecutionResultBlockParam`
- `content: Array`
- `file_id: string`
- `type: "code_execution_output"`
- `"code_execution_output"`
- `return_code: number`
- `stderr: string`
- `stdout: string`
- `type: "code_execution_result"`
- `"code_execution_result"`
### Beta Code Execution Tool Result Error
- `BetaCodeExecutionToolResultError`
- `error_code: BetaCodeExecutionToolResultErrorCode`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `type: "code_execution_tool_result_error"`
- `"code_execution_tool_result_error"`
### Beta Code Execution Tool Result Error Code
- `BetaCodeExecutionToolResultErrorCode = "invalid_tool_input" | "unavailable" | "too_many_requests" | "execution_time_exceeded"`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
### Beta Code Execution Tool Result Error Param
- `BetaCodeExecutionToolResultErrorParam`
- `error_code: BetaCodeExecutionToolResultErrorCode`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `type: "code_execution_tool_result_error"`
- `"code_execution_tool_result_error"`
### Beta Container
- `BetaContainer`
Information about the container used in the request (for the code execution tool)
- `id: string`
Identifier for the container used in this request
- `expires_at: string`
The time at which the container will expire.
- `skills: Array | null`
Skills loaded in the container
- `skill_id: string`
Skill ID
- `type: "anthropic" | "custom"`
Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined)
- `"anthropic"`
- `"custom"`
- `version: string`
Skill version or 'latest' for most recent version
### Beta Container Params
- `BetaContainerParams`
Container parameters with skills to be loaded.
- `id?: string | null`
Container id
- `skills?: Array | null`
List of skills to load in the container
- `skill_id: string`
Skill ID
- `type: "anthropic" | "custom"`
Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined)
- `"anthropic"`
- `"custom"`
- `version?: string`
Skill version or 'latest' for most recent version
### Beta Container Upload Block
- `BetaContainerUploadBlock`
Response model for a file uploaded to the container.
- `file_id: string`
- `type: "container_upload"`
- `"container_upload"`
### Beta Container Upload Block Param
- `BetaContainerUploadBlockParam`
A content block that represents a file to be uploaded to the container
Files uploaded via this block will be available in the container's input directory.
- `file_id: string`
- `type: "container_upload"`
- `"container_upload"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
### Beta Content Block
- `BetaContentBlock = BetaTextBlock | BetaThinkingBlock | BetaRedactedThinkingBlock | 11 more`
Response model for a file uploaded to the container.
- `BetaTextBlock`
- `citations: Array | null`
Citations supporting the text block.
The type of citation returned will depend on the type of document being cited. Citing a PDF results in `page_location`, plain text results in `char_location`, and content document results in `content_block_location`.
- `BetaCitationCharLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `file_id: string | null`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `file_id: string | null`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `file_id: string | null`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationsWebSearchResultLocation`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocation`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `text: string`
- `type: "text"`
- `"text"`
- `BetaThinkingBlock`
- `signature: string`
- `thinking: string`
- `type: "thinking"`
- `"thinking"`
- `BetaRedactedThinkingBlock`
- `data: string`
- `type: "redacted_thinking"`
- `"redacted_thinking"`
- `BetaToolUseBlock`
- `id: string`
- `input: Record`
- `name: string`
- `type: "tool_use"`
- `"tool_use"`
- `caller?: BetaDirectCaller | BetaServerToolCaller`
Tool invocation directly from the model.
- `BetaDirectCaller`
Tool invocation directly from the model.
- `type: "direct"`
- `"direct"`
- `BetaServerToolCaller`
Tool invocation generated by a server-side tool.
- `tool_id: string`
- `type: "code_execution_20250825"`
- `"code_execution_20250825"`
- `BetaServerToolUseBlock`
- `id: string`
- `input: Record`
- `name: "web_search" | "web_fetch" | "code_execution" | 4 more`
- `"web_search"`
- `"web_fetch"`
- `"code_execution"`
- `"bash_code_execution"`
- `"text_editor_code_execution"`
- `"tool_search_tool_regex"`
- `"tool_search_tool_bm25"`
- `type: "server_tool_use"`
- `"server_tool_use"`
- `caller?: BetaDirectCaller | BetaServerToolCaller`
Tool invocation directly from the model.
- `BetaDirectCaller`
Tool invocation directly from the model.
- `type: "direct"`
- `"direct"`
- `BetaServerToolCaller`
Tool invocation generated by a server-side tool.
- `tool_id: string`
- `type: "code_execution_20250825"`
- `"code_execution_20250825"`
- `BetaWebSearchToolResultBlock`
- `content: BetaWebSearchToolResultBlockContent`
- `BetaWebSearchToolResultError`
- `error_code: BetaWebSearchToolResultErrorCode`
- `"invalid_tool_input"`
- `"unavailable"`
- `"max_uses_exceeded"`
- `"too_many_requests"`
- `"query_too_long"`
- `"request_too_large"`
- `type: "web_search_tool_result_error"`
- `"web_search_tool_result_error"`
- `Array`
- `encrypted_content: string`
- `page_age: string | null`
- `title: string`
- `type: "web_search_result"`
- `"web_search_result"`
- `url: string`
- `tool_use_id: string`
- `type: "web_search_tool_result"`
- `"web_search_tool_result"`
- `BetaWebFetchToolResultBlock`
- `content: BetaWebFetchToolResultErrorBlock | BetaWebFetchBlock`
- `BetaWebFetchToolResultErrorBlock`
- `error_code: BetaWebFetchToolResultErrorCode`
- `"invalid_tool_input"`
- `"url_too_long"`
- `"url_not_allowed"`
- `"url_not_accessible"`
- `"unsupported_content_type"`
- `"too_many_requests"`
- `"max_uses_exceeded"`
- `"unavailable"`
- `type: "web_fetch_tool_result_error"`
- `"web_fetch_tool_result_error"`
- `BetaWebFetchBlock`
- `content: BetaDocumentBlock`
- `citations: BetaCitationConfig | null`
Citation configuration for the document
- `enabled: boolean`
- `source: BetaBase64PDFSource | BetaPlainTextSource`
- `BetaBase64PDFSource`
- `data: string`
- `media_type: "application/pdf"`
- `"application/pdf"`
- `type: "base64"`
- `"base64"`
- `BetaPlainTextSource`
- `data: string`
- `media_type: "text/plain"`
- `"text/plain"`
- `type: "text"`
- `"text"`
- `title: string | null`
The title of the document
- `type: "document"`
- `"document"`
- `retrieved_at: string | null`
ISO 8601 timestamp when the content was retrieved
- `type: "web_fetch_result"`
- `"web_fetch_result"`
- `url: string`
Fetched content URL
- `tool_use_id: string`
- `type: "web_fetch_tool_result"`
- `"web_fetch_tool_result"`
- `BetaCodeExecutionToolResultBlock`
- `content: BetaCodeExecutionToolResultBlockContent`
- `BetaCodeExecutionToolResultError`
- `error_code: BetaCodeExecutionToolResultErrorCode`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `type: "code_execution_tool_result_error"`
- `"code_execution_tool_result_error"`
- `BetaCodeExecutionResultBlock`
- `content: Array`
- `file_id: string`
- `type: "code_execution_output"`
- `"code_execution_output"`
- `return_code: number`
- `stderr: string`
- `stdout: string`
- `type: "code_execution_result"`
- `"code_execution_result"`
- `tool_use_id: string`
- `type: "code_execution_tool_result"`
- `"code_execution_tool_result"`
- `BetaBashCodeExecutionToolResultBlock`
- `content: BetaBashCodeExecutionToolResultError | BetaBashCodeExecutionResultBlock`
- `BetaBashCodeExecutionToolResultError`
- `error_code: "invalid_tool_input" | "unavailable" | "too_many_requests" | 2 more`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `"output_file_too_large"`
- `type: "bash_code_execution_tool_result_error"`
- `"bash_code_execution_tool_result_error"`
- `BetaBashCodeExecutionResultBlock`
- `content: Array`
- `file_id: string`
- `type: "bash_code_execution_output"`
- `"bash_code_execution_output"`
- `return_code: number`
- `stderr: string`
- `stdout: string`
- `type: "bash_code_execution_result"`
- `"bash_code_execution_result"`
- `tool_use_id: string`
- `type: "bash_code_execution_tool_result"`
- `"bash_code_execution_tool_result"`
- `BetaTextEditorCodeExecutionToolResultBlock`
- `content: BetaTextEditorCodeExecutionToolResultError | BetaTextEditorCodeExecutionViewResultBlock | BetaTextEditorCodeExecutionCreateResultBlock | BetaTextEditorCodeExecutionStrReplaceResultBlock`
- `BetaTextEditorCodeExecutionToolResultError`
- `error_code: "invalid_tool_input" | "unavailable" | "too_many_requests" | 2 more`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `"file_not_found"`
- `error_message: string | null`
- `type: "text_editor_code_execution_tool_result_error"`
- `"text_editor_code_execution_tool_result_error"`
- `BetaTextEditorCodeExecutionViewResultBlock`
- `content: string`
- `file_type: "text" | "image" | "pdf"`
- `"text"`
- `"image"`
- `"pdf"`
- `num_lines: number | null`
- `start_line: number | null`
- `total_lines: number | null`
- `type: "text_editor_code_execution_view_result"`
- `"text_editor_code_execution_view_result"`
- `BetaTextEditorCodeExecutionCreateResultBlock`
- `is_file_update: boolean`
- `type: "text_editor_code_execution_create_result"`
- `"text_editor_code_execution_create_result"`
- `BetaTextEditorCodeExecutionStrReplaceResultBlock`
- `lines: Array | null`
- `new_lines: number | null`
- `new_start: number | null`
- `old_lines: number | null`
- `old_start: number | null`
- `type: "text_editor_code_execution_str_replace_result"`
- `"text_editor_code_execution_str_replace_result"`
- `tool_use_id: string`
- `type: "text_editor_code_execution_tool_result"`
- `"text_editor_code_execution_tool_result"`
- `BetaToolSearchToolResultBlock`
- `content: BetaToolSearchToolResultError | BetaToolSearchToolSearchResultBlock`
- `BetaToolSearchToolResultError`
- `error_code: "invalid_tool_input" | "unavailable" | "too_many_requests" | "execution_time_exceeded"`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `error_message: string | null`
- `type: "tool_search_tool_result_error"`
- `"tool_search_tool_result_error"`
- `BetaToolSearchToolSearchResultBlock`
- `tool_references: Array`
- `tool_name: string`
- `type: "tool_reference"`
- `"tool_reference"`
- `type: "tool_search_tool_search_result"`
- `"tool_search_tool_search_result"`
- `tool_use_id: string`
- `type: "tool_search_tool_result"`
- `"tool_search_tool_result"`
- `BetaMCPToolUseBlock`
- `id: string`
- `input: Record`
- `name: string`
The name of the MCP tool
- `server_name: string`
The name of the MCP server
- `type: "mcp_tool_use"`
- `"mcp_tool_use"`
- `BetaMCPToolResultBlock`
- `content: string | Array`
- `string`
- `Array`
- `citations: Array | null`
Citations supporting the text block.
The type of citation returned will depend on the type of document being cited. Citing a PDF results in `page_location`, plain text results in `char_location`, and content document results in `content_block_location`.
- `BetaCitationCharLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `file_id: string | null`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `file_id: string | null`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocation`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `file_id: string | null`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationsWebSearchResultLocation`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocation`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `text: string`
- `type: "text"`
- `"text"`
- `is_error: boolean`
- `tool_use_id: string`
- `type: "mcp_tool_result"`
- `"mcp_tool_result"`
- `BetaContainerUploadBlock`
Response model for a file uploaded to the container.
- `file_id: string`
- `type: "container_upload"`
- `"container_upload"`
### Beta Content Block Param
- `BetaContentBlockParam = BetaTextBlockParam | BetaImageBlockParam | BetaRequestDocumentBlock | 15 more`
Regular text content.
- `BetaTextBlockParam`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `BetaCitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `BetaImageBlockParam`
- `source: BetaBase64ImageSource | BetaURLImageSource | BetaFileImageSource`
- `BetaBase64ImageSource`
- `data: string`
- `media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"`
- `"image/jpeg"`
- `"image/png"`
- `"image/gif"`
- `"image/webp"`
- `type: "base64"`
- `"base64"`
- `BetaURLImageSource`
- `type: "url"`
- `"url"`
- `url: string`
- `BetaFileImageSource`
- `file_id: string`
- `type: "file"`
- `"file"`
- `type: "image"`
- `"image"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `BetaRequestDocumentBlock`
- `source: BetaBase64PDFSource | BetaPlainTextSource | BetaContentBlockSource | 2 more`
- `BetaBase64PDFSource`
- `data: string`
- `media_type: "application/pdf"`
- `"application/pdf"`
- `type: "base64"`
- `"base64"`
- `BetaPlainTextSource`
- `data: string`
- `media_type: "text/plain"`
- `"text/plain"`
- `type: "text"`
- `"text"`
- `BetaContentBlockSource`
- `content: string | Array`
- `string`
- `Array`
- `BetaTextBlockParam`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `BetaCitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `BetaImageBlockParam`
- `source: BetaBase64ImageSource | BetaURLImageSource | BetaFileImageSource`
- `BetaBase64ImageSource`
- `data: string`
- `media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"`
- `"image/jpeg"`
- `"image/png"`
- `"image/gif"`
- `"image/webp"`
- `type: "base64"`
- `"base64"`
- `BetaURLImageSource`
- `type: "url"`
- `"url"`
- `url: string`
- `BetaFileImageSource`
- `file_id: string`
- `type: "file"`
- `"file"`
- `type: "image"`
- `"image"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `type: "content"`
- `"content"`
- `BetaURLPDFSource`
- `type: "url"`
- `"url"`
- `url: string`
- `BetaFileDocumentSource`
- `file_id: string`
- `type: "file"`
- `"file"`
- `type: "document"`
- `"document"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: BetaCitationsConfigParam | null`
- `enabled?: boolean`
- `context?: string | null`
- `title?: string | null`
- `BetaSearchResultBlockParam`
- `content: Array`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `BetaCitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `source: string`
- `title: string`
- `type: "search_result"`
- `"search_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: BetaCitationsConfigParam`
- `enabled?: boolean`
- `BetaThinkingBlockParam`
- `signature: string`
- `thinking: string`
- `type: "thinking"`
- `"thinking"`
- `BetaRedactedThinkingBlockParam`
- `data: string`
- `type: "redacted_thinking"`
- `"redacted_thinking"`
- `BetaToolUseBlockParam`
- `id: string`
- `input: Record`
- `name: string`
- `type: "tool_use"`
- `"tool_use"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `caller?: BetaDirectCaller | BetaServerToolCaller`
Tool invocation directly from the model.
- `BetaDirectCaller`
Tool invocation directly from the model.
- `type: "direct"`
- `"direct"`
- `BetaServerToolCaller`
Tool invocation generated by a server-side tool.
- `tool_id: string`
- `type: "code_execution_20250825"`
- `"code_execution_20250825"`
- `BetaToolResultBlockParam`
- `tool_use_id: string`
- `type: "tool_result"`
- `"tool_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `content?: string | Array`
- `string`
- `Array`
- `BetaTextBlockParam`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `BetaCitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `BetaImageBlockParam`
- `source: BetaBase64ImageSource | BetaURLImageSource | BetaFileImageSource`
- `BetaBase64ImageSource`
- `data: string`
- `media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"`
- `"image/jpeg"`
- `"image/png"`
- `"image/gif"`
- `"image/webp"`
- `type: "base64"`
- `"base64"`
- `BetaURLImageSource`
- `type: "url"`
- `"url"`
- `url: string`
- `BetaFileImageSource`
- `file_id: string`
- `type: "file"`
- `"file"`
- `type: "image"`
- `"image"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `BetaSearchResultBlockParam`
- `content: Array`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `BetaCitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `source: string`
- `title: string`
- `type: "search_result"`
- `"search_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: BetaCitationsConfigParam`
- `enabled?: boolean`
- `BetaRequestDocumentBlock`
- `source: BetaBase64PDFSource | BetaPlainTextSource | BetaContentBlockSource | 2 more`
- `BetaBase64PDFSource`
- `data: string`
- `media_type: "application/pdf"`
- `"application/pdf"`
- `type: "base64"`
- `"base64"`
- `BetaPlainTextSource`
- `data: string`
- `media_type: "text/plain"`
- `"text/plain"`
- `type: "text"`
- `"text"`
- `BetaContentBlockSource`
- `content: string | Array`
- `string`
- `Array`
- `BetaTextBlockParam`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `BetaCitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `BetaImageBlockParam`
- `source: BetaBase64ImageSource | BetaURLImageSource | BetaFileImageSource`
- `BetaBase64ImageSource`
- `data: string`
- `media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"`
- `"image/jpeg"`
- `"image/png"`
- `"image/gif"`
- `"image/webp"`
- `type: "base64"`
- `"base64"`
- `BetaURLImageSource`
- `type: "url"`
- `"url"`
- `url: string`
- `BetaFileImageSource`
- `file_id: string`
- `type: "file"`
- `"file"`
- `type: "image"`
- `"image"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `type: "content"`
- `"content"`
- `BetaURLPDFSource`
- `type: "url"`
- `"url"`
- `url: string`
- `BetaFileDocumentSource`
- `file_id: string`
- `type: "file"`
- `"file"`
- `type: "document"`
- `"document"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: BetaCitationsConfigParam | null`
- `enabled?: boolean`
- `context?: string | null`
- `title?: string | null`
- `BetaToolReferenceBlockParam`
Tool reference block that can be included in tool_result content.
- `tool_name: string`
- `type: "tool_reference"`
- `"tool_reference"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `is_error?: boolean`
- `BetaServerToolUseBlockParam`
- `id: string`
- `input: Record`
- `name: "web_search" | "web_fetch" | "code_execution" | 4 more`
- `"web_search"`
- `"web_fetch"`
- `"code_execution"`
- `"bash_code_execution"`
- `"text_editor_code_execution"`
- `"tool_search_tool_regex"`
- `"tool_search_tool_bm25"`
- `type: "server_tool_use"`
- `"server_tool_use"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `caller?: BetaDirectCaller | BetaServerToolCaller`
Tool invocation directly from the model.
- `BetaDirectCaller`
Tool invocation directly from the model.
- `type: "direct"`
- `"direct"`
- `BetaServerToolCaller`
Tool invocation generated by a server-side tool.
- `tool_id: string`
- `type: "code_execution_20250825"`
- `"code_execution_20250825"`
- `BetaWebSearchToolResultBlockParam`
- `content: BetaWebSearchToolResultBlockParamContent`
- `Array`
- `encrypted_content: string`
- `title: string`
- `type: "web_search_result"`
- `"web_search_result"`
- `url: string`
- `page_age?: string | null`
- `BetaWebSearchToolRequestError`
- `error_code: BetaWebSearchToolResultErrorCode`
- `"invalid_tool_input"`
- `"unavailable"`
- `"max_uses_exceeded"`
- `"too_many_requests"`
- `"query_too_long"`
- `"request_too_large"`
- `type: "web_search_tool_result_error"`
- `"web_search_tool_result_error"`
- `tool_use_id: string`
- `type: "web_search_tool_result"`
- `"web_search_tool_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `BetaWebFetchToolResultBlockParam`
- `content: BetaWebFetchToolResultErrorBlockParam | BetaWebFetchBlockParam`
- `BetaWebFetchToolResultErrorBlockParam`
- `error_code: BetaWebFetchToolResultErrorCode`
- `"invalid_tool_input"`
- `"url_too_long"`
- `"url_not_allowed"`
- `"url_not_accessible"`
- `"unsupported_content_type"`
- `"too_many_requests"`
- `"max_uses_exceeded"`
- `"unavailable"`
- `type: "web_fetch_tool_result_error"`
- `"web_fetch_tool_result_error"`
- `BetaWebFetchBlockParam`
- `content: BetaRequestDocumentBlock`
- `source: BetaBase64PDFSource | BetaPlainTextSource | BetaContentBlockSource | 2 more`
- `BetaBase64PDFSource`
- `data: string`
- `media_type: "application/pdf"`
- `"application/pdf"`
- `type: "base64"`
- `"base64"`
- `BetaPlainTextSource`
- `data: string`
- `media_type: "text/plain"`
- `"text/plain"`
- `type: "text"`
- `"text"`
- `BetaContentBlockSource`
- `content: string | Array`
- `string`
- `Array`
- `BetaTextBlockParam`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `BetaCitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `BetaImageBlockParam`
- `source: BetaBase64ImageSource | BetaURLImageSource | BetaFileImageSource`
- `BetaBase64ImageSource`
- `data: string`
- `media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"`
- `"image/jpeg"`
- `"image/png"`
- `"image/gif"`
- `"image/webp"`
- `type: "base64"`
- `"base64"`
- `BetaURLImageSource`
- `type: "url"`
- `"url"`
- `url: string`
- `BetaFileImageSource`
- `file_id: string`
- `type: "file"`
- `"file"`
- `type: "image"`
- `"image"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `type: "content"`
- `"content"`
- `BetaURLPDFSource`
- `type: "url"`
- `"url"`
- `url: string`
- `BetaFileDocumentSource`
- `file_id: string`
- `type: "file"`
- `"file"`
- `type: "document"`
- `"document"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: BetaCitationsConfigParam | null`
- `enabled?: boolean`
- `context?: string | null`
- `title?: string | null`
- `type: "web_fetch_result"`
- `"web_fetch_result"`
- `url: string`
Fetched content URL
- `retrieved_at?: string | null`
ISO 8601 timestamp when the content was retrieved
- `tool_use_id: string`
- `type: "web_fetch_tool_result"`
- `"web_fetch_tool_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `BetaCodeExecutionToolResultBlockParam`
- `content: BetaCodeExecutionToolResultBlockParamContent`
- `BetaCodeExecutionToolResultErrorParam`
- `error_code: BetaCodeExecutionToolResultErrorCode`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `type: "code_execution_tool_result_error"`
- `"code_execution_tool_result_error"`
- `BetaCodeExecutionResultBlockParam`
- `content: Array`
- `file_id: string`
- `type: "code_execution_output"`
- `"code_execution_output"`
- `return_code: number`
- `stderr: string`
- `stdout: string`
- `type: "code_execution_result"`
- `"code_execution_result"`
- `tool_use_id: string`
- `type: "code_execution_tool_result"`
- `"code_execution_tool_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `BetaBashCodeExecutionToolResultBlockParam`
- `content: BetaBashCodeExecutionToolResultErrorParam | BetaBashCodeExecutionResultBlockParam`
- `BetaBashCodeExecutionToolResultErrorParam`
- `error_code: "invalid_tool_input" | "unavailable" | "too_many_requests" | 2 more`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `"output_file_too_large"`
- `type: "bash_code_execution_tool_result_error"`
- `"bash_code_execution_tool_result_error"`
- `BetaBashCodeExecutionResultBlockParam`
- `content: Array`
- `file_id: string`
- `type: "bash_code_execution_output"`
- `"bash_code_execution_output"`
- `return_code: number`
- `stderr: string`
- `stdout: string`
- `type: "bash_code_execution_result"`
- `"bash_code_execution_result"`
- `tool_use_id: string`
- `type: "bash_code_execution_tool_result"`
- `"bash_code_execution_tool_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `BetaTextEditorCodeExecutionToolResultBlockParam`
- `content: BetaTextEditorCodeExecutionToolResultErrorParam | BetaTextEditorCodeExecutionViewResultBlockParam | BetaTextEditorCodeExecutionCreateResultBlockParam | BetaTextEditorCodeExecutionStrReplaceResultBlockParam`
- `BetaTextEditorCodeExecutionToolResultErrorParam`
- `error_code: "invalid_tool_input" | "unavailable" | "too_many_requests" | 2 more`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `"file_not_found"`
- `type: "text_editor_code_execution_tool_result_error"`
- `"text_editor_code_execution_tool_result_error"`
- `error_message?: string | null`
- `BetaTextEditorCodeExecutionViewResultBlockParam`
- `content: string`
- `file_type: "text" | "image" | "pdf"`
- `"text"`
- `"image"`
- `"pdf"`
- `type: "text_editor_code_execution_view_result"`
- `"text_editor_code_execution_view_result"`
- `num_lines?: number | null`
- `start_line?: number | null`
- `total_lines?: number | null`
- `BetaTextEditorCodeExecutionCreateResultBlockParam`
- `is_file_update: boolean`
- `type: "text_editor_code_execution_create_result"`
- `"text_editor_code_execution_create_result"`
- `BetaTextEditorCodeExecutionStrReplaceResultBlockParam`
- `type: "text_editor_code_execution_str_replace_result"`
- `"text_editor_code_execution_str_replace_result"`
- `lines?: Array | null`
- `new_lines?: number | null`
- `new_start?: number | null`
- `old_lines?: number | null`
- `old_start?: number | null`
- `tool_use_id: string`
- `type: "text_editor_code_execution_tool_result"`
- `"text_editor_code_execution_tool_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `BetaToolSearchToolResultBlockParam`
- `content: BetaToolSearchToolResultErrorParam | BetaToolSearchToolSearchResultBlockParam`
- `BetaToolSearchToolResultErrorParam`
- `error_code: "invalid_tool_input" | "unavailable" | "too_many_requests" | "execution_time_exceeded"`
- `"invalid_tool_input"`
- `"unavailable"`
- `"too_many_requests"`
- `"execution_time_exceeded"`
- `type: "tool_search_tool_result_error"`
- `"tool_search_tool_result_error"`
- `BetaToolSearchToolSearchResultBlockParam`
- `tool_references: Array`
- `tool_name: string`
- `type: "tool_reference"`
- `"tool_reference"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `type: "tool_search_tool_search_result"`
- `"tool_search_tool_search_result"`
- `tool_use_id: string`
- `type: "tool_search_tool_result"`
- `"tool_search_tool_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `BetaMCPToolUseBlockParam`
- `id: string`
- `input: Record`
- `name: string`
- `server_name: string`
The name of the MCP server
- `type: "mcp_tool_use"`
- `"mcp_tool_use"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `BetaRequestMCPToolResultBlockParam`
- `tool_use_id: string`
- `type: "mcp_tool_result"`
- `"mcp_tool_result"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `content?: string | Array`
- `string`
- `Array`
- `text: string`
- `type: "text"`
- `"text"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
- `citations?: Array | null`
- `BetaCitationCharLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_char_index: number`
- `start_char_index: number`
- `type: "char_location"`
- `"char_location"`
- `BetaCitationPageLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_page_number: number`
- `start_page_number: number`
- `type: "page_location"`
- `"page_location"`
- `BetaCitationContentBlockLocationParam`
- `cited_text: string`
- `document_index: number`
- `document_title: string | null`
- `end_block_index: number`
- `start_block_index: number`
- `type: "content_block_location"`
- `"content_block_location"`
- `BetaCitationWebSearchResultLocationParam`
- `cited_text: string`
- `encrypted_index: string`
- `title: string | null`
- `type: "web_search_result_location"`
- `"web_search_result_location"`
- `url: string`
- `BetaCitationSearchResultLocationParam`
- `cited_text: string`
- `end_block_index: number`
- `search_result_index: number`
- `source: string`
- `start_block_index: number`
- `title: string | null`
- `type: "search_result_location"`
- `"search_result_location"`
- `is_error?: boolean`
- `BetaContainerUploadBlockParam`
A content block that represents a file to be uploaded to the container
Files uploaded via this block will be available in the container's input directory.
- `file_id: string`
- `type: "container_upload"`
- `"container_upload"`
- `cache_control?: BetaCacheControlEphemeral | null`
Create a cache control breakpoint at this content block.
- `type: "ephemeral"`
- `"ephemeral"`
- `ttl?: "5m" | "1h"`
The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
- `"5m"`
- `"1h"`
### Beta Content Block Source
- `BetaContentBlockSource`
- `content: string | Array`
- `string`
- `Array