# Beta Features

The Anthropic SDK provides access to experimental and advanced features through the beta namespace. Beta features require specific beta headers and may change before general availability.

## Overview

Beta features include:
- **Code Execution**: Execute Python and bash code in sandboxed environments
- **Computer Use**: Bash, text editor, and computer control tools
- **Extended Thinking**: Access Claude's reasoning process
- **MCP (Model Context Protocol)**: External tool integration
- **Memory Tools**: Persistent memory across conversations
- **Web Search & Fetch**: Search the web and fetch content
- **Context Management**: Advanced context window management
- **Structured Outputs**: JSON output with automatic parsing
- **Files API**: File upload and management
- **Skills API**: Custom skill definitions

## Accessing Beta Features

Use the `client.beta` namespace and include appropriate beta headers:

```typescript
import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic();

const message = await client.beta.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 2048,
  betas: ['code-execution-2025-05-22'],  // Required beta header
  messages: [{ role: 'user', content: 'Execute Python code' }],
});
```

## Available Beta Headers

```typescript { .api }
type AnthropicBeta =
  | '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'
  | 'dev-full-thinking-2025-05-14'
  | 'interleaved-thinking-2025-05-14'
  | 'code-execution-2025-05-22'
  | 'code-execution-2025-08-25'
  | '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'
  ;
```

## Code Execution

Execute Python code in a sandboxed environment:

```typescript
const message = await client.beta.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 2048,
  betas: ['code-execution-2025-05-22'],
  tools: [
    {
      name: 'code_execution',
      type: 'code_execution_20250522',
    },
  ],
  messages: [
    {
      role: 'user',
      content: 'Calculate the factorial of 10 using Python.',
    },
  ],
});

// Claude will use code_execution tool
for (const block of message.content) {
  if (block.type === 'code_execution_result') {
    console.log('Output:', block.output);
  }
}
```

**Versions**:
- `code_execution_20250522`: Version from 2025-05-22
- `code_execution_20250825`: Version from 2025-08-25

## Computer Use Tools

Interact with computer interfaces:

### Bash Tool

```typescript
const message = await client.beta.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 2048,
  betas: ['computer-use-2025-01-24'],
  tools: [
    {
      name: 'bash',
      type: 'bash_20250124',
    },
  ],
  messages: [
    {
      role: 'user',
      content: 'List files in the current directory.',
    },
  ],
});
```

### Text Editor Tool

```typescript
const message = await client.beta.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 2048,
  betas: ['computer-use-2025-01-24'],
  tools: [
    {
      name: 'str_replace_editor',
      type: 'text_editor_20250728',
    },
  ],
  messages: [
    {
      role: 'user',
      content: 'Create a file and write "Hello World" to it.',
    },
  ],
});
```

**Tool Versions**:
- `bash_20241022`, `bash_20250124`: Bash execution
- `text_editor_20241022`, `text_editor_20250124`, `text_editor_20250429`, `text_editor_20250728`: Text editor operations
- `computer_use_20241022`, `computer_use_20250124`: Full computer control

## Extended Thinking

Access Claude's reasoning process:

```typescript
const message = await client.beta.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 4096,
  betas: ['dev-full-thinking-2025-05-14'],
  thinking: {
    type: 'enabled',
    budget_tokens: 2000,
  },
  messages: [
    {
      role: 'user',
      content: 'Solve this complex problem: ...',
    },
  ],
});

// Access thinking blocks
for (const block of message.content) {
  if (block.type === 'thinking') {
    console.log('Reasoning:', block.thinking);
    console.log('Signature:', block.signature);
  } else if (block.type === 'text') {
    console.log('Answer:', block.text);
  }
}
```

**Beta Headers**:
- `dev-full-thinking-2025-05-14`: Full thinking traces
- `interleaved-thinking-2025-05-14`: Interleaved thinking and responses

## Memory Tools

Persistent memory across conversations:

```typescript
const message = await client.beta.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 2048,
  betas: ['memory-2025-08-18'],
  tools: [
    {
      name: 'memory',
      type: 'memory_20250818',
      commands: {
        create: {
          enabled: true,
        },
        view: {
          enabled: true,
        },
        delete: {
          enabled: true,
        },
      },
    },
  ],
  messages: [
    {
      role: 'user',
      content: 'Remember that my name is Alice.',
    },
  ],
});

// Later conversation
const message2 = await client.beta.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 1024,
  betas: ['memory-2025-08-18'],
  tools: [
    {
      name: 'memory',
      type: 'memory_20250818',
      commands: {
        view: { enabled: true },
      },
    },
  ],
  messages: [
    {
      role: 'user',
      content: 'What is my name?',
    },
  ],
});
// Claude will recall: "Alice"
```

**Memory Commands**:
- `create`: Store new memory
- `view`: Retrieve memory
- `delete`: Remove memory
- `insert`: Add content to memory
- `str_replace`: Replace content in memory
- `rename`: Rename memory

## Web Search & Fetch

Search the web and fetch content:

### Web Search

```typescript
const message = await client.beta.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 2048,
  betas: ['web-search-2025-03-05'],
  tools: [
    {
      name: 'web_search',
      type: 'web_search_20250305',
    },
  ],
  messages: [
    {
      role: 'user',
      content: 'Search for recent AI news.',
    },
  ],
});

// Claude will use web_search tool and return results
for (const block of message.content) {
  if (block.type === 'web_search_result') {
    console.log('Query:', block.query);
    console.log('Results:', block.results);
  }
}
```

### Web Fetch

```typescript
const message = await client.beta.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 2048,
  betas: ['web-fetch-2025-09-10'],
  tools: [
    {
      name: 'web_fetch',
      type: 'web_fetch_20250910',
    },
  ],
  messages: [
    {
      role: 'user',
      content: 'Fetch the content from https://example.com',
    },
  ],
});
```

## MCP (Model Context Protocol)

Integrate external tools via MCP:

```typescript
const message = await client.beta.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 2048,
  betas: ['mcp-client-2025-04-04'],
  mcp_servers: [
    {
      url: 'https://mcp-server.example.com',
      tools: ['*'],  // Allow all tools from server
    },
  ],
  messages: [
    {
      role: 'user',
      content: 'Use external MCP tools.',
    },
  ],
});
```

## Context Management

Advanced context window management:

```typescript
const message = await client.beta.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 2048,
  betas: ['context-management-2025-06-27'],
  context_management: {
    input_tokens_clear_at_least: 50000,  // Clear when over 50k tokens
    tool_uses: {
      keep: 10,  // Keep last 10 tool uses
    },
    thinking_turns: {
      keep: 'all',  // Keep all thinking turns
    },
  },
  messages: longConversation,
});
```

**Configuration**:
- `input_tokens_clear_at_least`: Threshold for clearing context
- `tool_uses.keep`: Number of tool interactions to retain
- `thinking_turns.keep`: How many thinking turns to keep (`'all'` or `'none'`)

## Structured Outputs

JSON output with automatic parsing:

```typescript
import { betaZodOutputFormat } from '@anthropic-ai/sdk/helpers/zod';
import { z } from 'zod';

const outputFormat = betaZodOutputFormat(
  z.object({
    name: z.string(),
    age: z.number(),
    email: z.string().email(),
  })
);

const message = await client.beta.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 1024,
  betas: ['structured-outputs-2025-02-19'],
  output_format: {
    type: 'json_schema',
    schema: outputFormat.schema,
  },
  messages: [
    {
      role: 'user',
      content: 'Extract information from: John Doe, 30, john@example.com',
    },
  ],
});

// Parse output
const parsed = outputFormat.parse(message.content[0].text);
console.log(parsed.name); // "John Doe"
console.log(parsed.age); // 30
console.log(parsed.email); // "john@example.com"
```

Or use JSON Schema:

```typescript
import { betaJSONSchemaOutputFormat } from '@anthropic-ai/sdk/helpers/json-schema';

const outputFormat = betaJSONSchemaOutputFormat({
  type: 'object',
  properties: {
    sentiment: { type: 'string', enum: ['positive', 'negative', 'neutral'] },
    confidence: { type: 'number', minimum: 0, maximum: 1 },
  },
  required: ['sentiment', 'confidence'],
});

const message = await client.beta.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 512,
  betas: ['structured-outputs-2025-02-19'],
  output_format: {
    type: 'json_schema',
    schema: outputFormat.schema,
  },
  messages: [
    {
      role: 'user',
      content: 'Analyze sentiment: This product is amazing!',
    },
  ],
});

const parsed = outputFormat.parse(message.content[0].text);
console.log(parsed.sentiment); // "positive"
console.log(parsed.confidence); // 0.95
```

## Prompt Caching

Cache frequently used prompts for reduced latency:

```typescript
const message = await client.beta.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 1024,
  betas: ['prompt-caching-2024-07-31'],
  system: [
    {
      type: 'text',
      text: 'You are a helpful assistant.',
    },
    {
      type: 'text',
      text: largeKnowledgeBase,
      cache_control: {
        type: 'ephemeral',
        ttl: '1h',  // Cache for 1 hour
      },
    },
  ],
  messages: [
    {
      role: 'user',
      content: 'Question about the knowledge base...',
    },
  ],
});

console.log('Cache usage:', message.usage);
// {
//   input_tokens: 1000,
//   cache_read_input_tokens: 50000,  // Read from cache
//   output_tokens: 500
// }
```

**TTL Options**:
- `5m`: 5 minutes (default)
- `1h`: 1 hour (requires `extended-cache-ttl-2025-04-11` beta)

## Message Batches

Process multiple messages asynchronously:

```typescript
const batch = await client.beta.messages.batches.create({
  betas: ['message-batches-2024-09-24'],
  requests: [
    {
      custom_id: 'request-1',
      params: {
        model: 'claude-sonnet-4-5-20250929',
        max_tokens: 1024,
        messages: [{ role: 'user', content: 'Task 1' }],
      },
    },
    {
      custom_id: 'request-2',
      params: {
        model: 'claude-sonnet-4-5-20250929',
        max_tokens: 1024,
        messages: [{ role: 'user', content: 'Task 2' }],
      },
    },
  ],
});

console.log('Batch ID:', batch.id);
```

See [batches.md](./batches.md) for complete documentation.

## Files API

Upload and manage files:

```typescript
import { toFile } from '@anthropic-ai/sdk';
import fs from 'fs';

const file = await client.beta.files.upload({
  file: await toFile(fs.createReadStream('document.pdf'), 'document.pdf', { type: 'application/pdf' }),
  betas: ['files-api-2025-04-14'],
});

const message = await client.beta.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 2048,
  betas: ['files-api-2025-04-14'],
  messages: [
    {
      role: 'user',
      content: [
        {
          type: 'document',
          source: {
            type: 'file',
            file_id: file.id,
          },
        },
        {
          type: 'text',
          text: 'Summarize this document.',
        },
      ],
    },
  ],
});
```

See [files.md](./files.md) for complete documentation.

## Skills API

Create and manage custom skills:

```typescript
const skill = await client.beta.skills.create({
  name: 'data_analyzer',
  description: 'Analyze structured data',
  definition: {
    type: 'analysis',
    capabilities: ['statistics', 'visualization'],
  },
  betas: ['skills-2025-10-02'],
});

const message = await client.beta.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 2048,
  betas: ['skills-2025-10-02'],
  skills: [
    {
      type: 'skill',
      skill_id: skill.id,
    },
  ],
  messages: [
    {
      role: 'user',
      content: 'Analyze this data...',
    },
  ],
});
```

See [skills.md](./skills.md) for complete documentation.

## Combining Beta Features

Use multiple beta features together:

```typescript
const message = await client.beta.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 4096,
  betas: [
    'code-execution-2025-05-22',
    'dev-full-thinking-2025-05-14',
    'web-search-2025-03-05',
  ],
  thinking: {
    type: 'enabled',
    budget_tokens: 2000,
  },
  tools: [
    {
      name: 'code_execution',
      type: 'code_execution_20250522',
    },
    {
      name: 'web_search',
      type: 'web_search_20250305',
    },
  ],
  messages: [
    {
      role: 'user',
      content: 'Search for recent data on topic X, then analyze it with Python.',
    },
  ],
});

// Claude can use thinking, web search, and code execution together
```

## Beta API Namespace

All beta features are accessed through the `client.beta` namespace:

```typescript
client.beta.messages.*         // Beta messages API
client.beta.messages.batches.* // Beta message batches
client.beta.models.*           // Beta models API
client.beta.files.*            // Files API
client.beta.skills.*           // Skills API
client.beta.skills.versions.*  // Skill versions
```

## Best Practices

### Feature Detection

```typescript
// ✅ Good: Check beta support
const betaHeaders: AnthropicBeta[] = ['code-execution-2025-05-22'];

try {
  const message = await client.beta.messages.create({
    model: 'claude-sonnet-4-5-20250929',
    max_tokens: 2048,
    betas: betaHeaders,
    tools: [{ name: 'code_execution', type: 'code_execution_20250522' }],
    messages: [{ role: 'user', content: 'Execute code' }],
  });
} catch (error) {
  if (error instanceof Anthropic.BadRequestError) {
    console.error('Beta feature not available');
  }
}
```

### Migration Planning

```typescript
// ✅ Good: Prepare for GA migration
const USE_BETA = process.env.USE_CODE_EXECUTION === 'true';

const message = await (USE_BETA ? client.beta.messages : client.messages).create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 2048,
  ...(USE_BETA && { betas: ['code-execution-2025-05-22'] }),
  messages: [{ role: 'user', content: 'Task' }],
});
```

## See Also

- [Messages API](./messages.md) - Core message creation
- [Tools](./tools.md) - Tool use and helpers
- [Files](./files.md) - File upload and management
- [Skills](./skills.md) - Custom skill definitions
- [Batches](./batches.md) - Batch processing
