or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

batches.mdbeta.mdclient-initialization.mderrors.mdindex.mdmessages.mdmodels.mdplatform-clients.mdstreaming.mdtools-builtin.mdtools-decorators.mdtools-function.mdtools-memory.mdtools-runners.mdtools.mdtypes.md

beta.mddocs/

0

# Beta Features

1

2

Beta features provide access to experimental and preview functionality in the Anthropic API. These features include extended message capabilities, file management, AI skills, structured outputs, context management, and enhanced tool support.

3

4

## Package Information

5

6

- **Package Name**: anthropic

7

- **Module**: anthropic.resources.beta

8

- **Language**: Python

9

- **Installation**: `pip install anthropic`

10

11

## Core Imports

12

13

```python

14

from anthropic import Anthropic

15

16

client = Anthropic()

17

# Access beta features through the beta resource

18

beta_response = client.beta.messages.create(...)

19

```

20

21

Async client:

22

23

```python

24

from anthropic import AsyncAnthropic

25

26

async_client = AsyncAnthropic()

27

beta_response = await async_client.beta.messages.create(...)

28

```

29

30

## Basic Usage

31

32

```python

33

from anthropic import Anthropic

34

35

client = Anthropic()

36

37

# Use beta messages API with extended features

38

message = client.beta.messages.create(

39

model="claude-3-5-sonnet-20241022",

40

max_tokens=1024,

41

messages=[

42

{"role": "user", "content": "What is 2+2?"}

43

]

44

)

45

46

print(message.content[0].text)

47

48

# Upload a file (beta feature)

49

with open("document.pdf", "rb") as f:

50

file = client.beta.files.upload(file=f)

51

print(f"Uploaded file: {file.id}")

52

53

# List uploaded files

54

files = client.beta.files.list()

55

for file in files:

56

print(f"{file.filename}: {file.bytes} bytes")

57

```

58

59

## Architecture

60

61

The Beta resource provides access to experimental features through sub-resources:

62

63

- **Messages**: Extended message API with structured outputs, context management, and advanced features

64

- **Files**: File upload and management for use with messages

65

- **Skills**: Create and manage custom AI skills

66

- **Models**: Beta model information and capabilities

67

68

All beta features require appropriate beta headers and may have different stability guarantees than stable APIs.

69

70

## Capabilities

71

72

### Beta Resource

73

74

Main entry point for accessing beta features and experimental functionality.

75

76

```python { .api }

77

class Beta:

78

"""Access to beta features and APIs."""

79

80

@property

81

def models(self) -> Models:

82

"""Beta models resource."""

83

...

84

85

@property

86

def messages(self) -> Messages:

87

"""Beta messages resource with extended features."""

88

...

89

90

@property

91

def files(self) -> Files:

92

"""File upload and management."""

93

...

94

95

@property

96

def skills(self) -> Skills:

97

"""AI skills management."""

98

...

99

100

@property

101

def with_raw_response(self) -> BetaWithRawResponse:

102

"""Return raw response objects instead of parsed content."""

103

...

104

105

@property

106

def with_streaming_response(self) -> BetaWithStreamingResponse:

107

"""Alternative to with_raw_response without eager reading."""

108

...

109

110

class AsyncBeta:

111

"""Async version of Beta resource."""

112

# Same properties and methods as Beta, all async

113

...

114

```

115

116

### Beta Messages API

117

118

Extended messages API with structured outputs, context management, and advanced content types.

119

120

```python { .api }

121

class Messages:

122

"""Beta messages API with extended features."""

123

124

def create(

125

self,

126

*,

127

max_tokens: int,

128

messages: List[BetaMessageParam],

129

model: str,

130

metadata: BetaMetadataParam | NotGiven = NOT_GIVEN,

131

stop_sequences: List[str] | NotGiven = NOT_GIVEN,

132

stream: bool | NotGiven = NOT_GIVEN,

133

system: str | List[BetaContentBlockParam] | NotGiven = NOT_GIVEN,

134

temperature: float | NotGiven = NOT_GIVEN,

135

thinking: BetaThinkingConfigParam | NotGiven = NOT_GIVEN,

136

tool_choice: BetaToolChoiceParam | NotGiven = NOT_GIVEN,

137

tools: List[BetaToolUnionParam] | NotGiven = NOT_GIVEN,

138

top_k: int | NotGiven = NOT_GIVEN,

139

top_p: float | NotGiven = NOT_GIVEN,

140

output_format: BetaOutputFormatParam | NotGiven = NOT_GIVEN,

141

context_management: BetaContextManagementConfigParam | NotGiven = NOT_GIVEN,

142

betas: List[str] | NotGiven = NOT_GIVEN,

143

extra_headers: Headers | None = None,

144

extra_query: Query | None = None,

145

extra_body: Body | None = None,

146

timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,

147

) -> BetaMessage:

148

"""

149

Create a message with beta features.

150

151

Args:

152

max_tokens: Maximum tokens to generate

153

messages: Input messages (conversation history)

154

model: Model identifier

155

metadata: Request metadata (user_id, etc.)

156

stop_sequences: Custom stop sequences

157

stream: Enable streaming response

158

system: System prompt (string or blocks)

159

temperature: Sampling temperature (0.0-1.0)

160

thinking: Extended thinking configuration

161

tool_choice: Tool selection strategy

162

tools: Available tools

163

top_k: Top-k sampling parameter

164

top_p: Nucleus sampling parameter

165

output_format: Structured output format specification

166

context_management: Context management configuration

167

betas: Beta feature flags to enable

168

extra_headers: Additional HTTP headers

169

extra_query: Additional query parameters

170

extra_body: Additional JSON properties

171

timeout: Request timeout

172

173

Returns:

174

BetaMessage with extended content types and metadata

175

"""

176

...

177

178

def parse(

179

self,

180

*,

181

max_tokens: int,

182

messages: List[BetaMessageParam],

183

model: str,

184

output_format: BetaOutputFormatParam,

185

# ... same parameters as create

186

) -> ParsedBetaMessage[ResponseFormatT]:

187

"""

188

Create a message and parse structured output.

189

190

Returns:

191

ParsedBetaMessage with typed parsed_output field

192

"""

193

...

194

195

def stream(

196

self,

197

*,

198

max_tokens: int,

199

messages: List[BetaMessageParam],

200

model: str,

201

# ... same parameters as create

202

) -> BetaMessageStreamManager:

203

"""

204

Create streaming beta message.

205

206

Returns:

207

Context manager for BetaMessageStream

208

"""

209

...

210

211

def tool_runner(

212

self,

213

tools: List[BetaToolUnion],

214

*,

215

max_tokens: int,

216

messages: List[BetaMessageParam],

217

model: str,

218

# ... same parameters as create

219

) -> BetaToolRunner:

220

"""

221

Run tool loop with automatic tool execution.

222

223

Args:

224

tools: List of tool instances to execute

225

226

Returns:

227

BetaToolRunner for automatic tool calling

228

"""

229

...

230

231

def count_tokens(

232

self,

233

*,

234

messages: List[BetaMessageParam],

235

model: str,

236

system: str | List[BetaContentBlockParam] | NotGiven = NOT_GIVEN,

237

tool_choice: BetaToolChoiceParam | NotGiven = NOT_GIVEN,

238

tools: List[BetaToolUnionParam] | NotGiven = NOT_GIVEN,

239

betas: List[str] | NotGiven = NOT_GIVEN,

240

extra_headers: Headers | None = None,

241

extra_query: Query | None = None,

242

extra_body: Body | None = None,

243

timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,

244

) -> BetaMessageTokensCount:

245

"""

246

Count tokens with beta features.

247

248

Returns:

249

Token count information

250

"""

251

...

252

253

@property

254

def batches(self) -> Batches:

255

"""Beta message batches resource."""

256

...

257

258

class AsyncMessages:

259

"""Async version of beta Messages resource."""

260

# Same methods as Messages, all async

261

...

262

```

263

264

**Usage Example:**

265

266

```python

267

from anthropic import Anthropic

268

269

client = Anthropic()

270

271

# Basic beta message

272

message = client.beta.messages.create(

273

model="claude-3-5-sonnet-20241022",

274

max_tokens=1024,

275

messages=[

276

{"role": "user", "content": "Explain quantum computing"}

277

]

278

)

279

280

# Message with extended thinking

281

message = client.beta.messages.create(

282

model="claude-3-5-sonnet-20241022",

283

max_tokens=4096,

284

thinking={

285

"type": "enabled",

286

"budget_tokens": 2000

287

},

288

messages=[

289

{"role": "user", "content": "Solve this complex math problem: ..."}

290

]

291

)

292

293

# Access thinking content

294

for block in message.content:

295

if block.type == "thinking":

296

print(f"Reasoning: {block.thinking}")

297

elif block.type == "text":

298

print(f"Answer: {block.text}")

299

300

# Structured output with parsing

301

from pydantic import BaseModel

302

303

class AnalysisResult(BaseModel):

304

sentiment: str

305

confidence: float

306

key_points: list[str]

307

308

message = client.beta.messages.parse(

309

model="claude-3-5-sonnet-20241022",

310

max_tokens=1024,

311

messages=[

312

{"role": "user", "content": "Analyze this review: ..."}

313

],

314

output_format={

315

"type": "json_schema",

316

"json_schema": {

317

"name": "analysis",

318

"schema": AnalysisResult.model_json_schema()

319

}

320

}

321

)

322

323

# Access parsed output with type safety

324

analysis: AnalysisResult = message.parsed_output

325

print(f"Sentiment: {analysis.sentiment}")

326

print(f"Confidence: {analysis.confidence}")

327

```

328

329

### Files Resource

330

331

Upload and manage files for use with the Anthropic API.

332

333

```python { .api }

334

class Files:

335

"""Manage file uploads (beta feature)."""

336

337

def upload(

338

self,

339

*,

340

file: FileTypes,

341

betas: List[str] | NotGiven = NOT_GIVEN,

342

extra_headers: Headers | None = None,

343

extra_query: Query | None = None,

344

extra_body: Body | None = None,

345

timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,

346

) -> FileMetadata:

347

"""

348

Upload a file.

349

350

Args:

351

file: File to upload (file object, path, or tuple)

352

betas: Beta feature flags

353

extra_headers: Additional HTTP headers

354

extra_query: Additional query parameters

355

extra_body: Additional JSON properties

356

timeout: Request timeout

357

358

Returns:

359

FileMetadata with file ID and information

360

"""

361

...

362

363

def list(

364

self,

365

*,

366

after_id: str | NotGiven = NOT_GIVEN,

367

before_id: str | NotGiven = NOT_GIVEN,

368

limit: int | NotGiven = NOT_GIVEN,

369

betas: List[str] | NotGiven = NOT_GIVEN,

370

extra_headers: Headers | None = None,

371

extra_query: Query | None = None,

372

extra_body: Body | None = None,

373

timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,

374

) -> SyncPage[FileMetadata]:

375

"""

376

List uploaded files.

377

378

Args:

379

after_id: Cursor for pagination (after this ID)

380

before_id: Cursor for pagination (before this ID)

381

limit: Number of items per page (1-1000, default 20)

382

betas: Beta feature flags

383

extra_headers: Additional HTTP headers

384

extra_query: Additional query parameters

385

extra_body: Additional JSON properties

386

timeout: Request timeout

387

388

Returns:

389

Paginated list of FileMetadata

390

"""

391

...

392

393

def retrieve_metadata(

394

self,

395

file_id: str,

396

*,

397

betas: List[str] | NotGiven = NOT_GIVEN,

398

extra_headers: Headers | None = None,

399

extra_query: Query | None = None,

400

extra_body: Body | None = None,

401

timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,

402

) -> FileMetadata:

403

"""

404

Get file metadata.

405

406

Args:

407

file_id: ID of the file

408

betas: Beta feature flags

409

extra_headers: Additional HTTP headers

410

extra_query: Additional query parameters

411

extra_body: Additional JSON properties

412

timeout: Request timeout

413

414

Returns:

415

FileMetadata for the specified file

416

"""

417

...

418

419

def download(

420

self,

421

file_id: str,

422

*,

423

betas: List[str] | NotGiven = NOT_GIVEN,

424

extra_headers: Headers | None = None,

425

extra_query: Query | None = None,

426

extra_body: Body | None = None,

427

timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,

428

) -> BinaryAPIResponse:

429

"""

430

Download file content.

431

432

Args:

433

file_id: ID of the file

434

betas: Beta feature flags

435

extra_headers: Additional HTTP headers

436

extra_query: Additional query parameters

437

extra_body: Additional JSON properties

438

timeout: Request timeout

439

440

Returns:

441

Binary content of the file

442

"""

443

...

444

445

def delete(

446

self,

447

file_id: str,

448

*,

449

betas: List[str] | NotGiven = NOT_GIVEN,

450

extra_headers: Headers | None = None,

451

extra_query: Query | None = None,

452

extra_body: Body | None = None,

453

timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,

454

) -> DeletedFile:

455

"""

456

Delete a file.

457

458

Args:

459

file_id: ID of the file

460

betas: Beta feature flags

461

extra_headers: Additional HTTP headers

462

extra_query: Additional query parameters

463

extra_body: Additional JSON properties

464

timeout: Request timeout

465

466

Returns:

467

DeletedFile with deletion confirmation

468

"""

469

...

470

471

class AsyncFiles:

472

"""Async version of Files resource."""

473

# Same methods as Files, all async

474

...

475

```

476

477

**Usage Example:**

478

479

```python

480

from anthropic import Anthropic

481

482

client = Anthropic()

483

484

# Upload a file

485

with open("document.pdf", "rb") as f:

486

file = client.beta.files.upload(file=f)

487

print(f"Uploaded: {file.id}")

488

print(f"Filename: {file.filename}")

489

print(f"Size: {file.bytes} bytes")

490

491

# List all files

492

files = client.beta.files.list(limit=50)

493

for file in files:

494

print(f"{file.filename}: {file.created_at}")

495

496

# Get file metadata

497

metadata = client.beta.files.retrieve_metadata(file.id)

498

print(f"Purpose: {metadata.purpose}")

499

500

# Download file

501

content = client.beta.files.download(file.id)

502

with open("downloaded.pdf", "wb") as f:

503

f.write(content.read())

504

505

# Delete file

506

deleted = client.beta.files.delete(file.id)

507

print(f"Deleted: {deleted.deleted}")

508

```

509

510

### Skills Resource

511

512

Create and manage custom AI skills that extend Claude's capabilities.

513

514

```python { .api }

515

class Skills:

516

"""Manage AI skills (beta feature)."""

517

518

def create(

519

self,

520

*,

521

display_title: str | NotGiven = NOT_GIVEN,

522

files: List[FileTypes] | NotGiven = NOT_GIVEN,

523

betas: List[str] | NotGiven = NOT_GIVEN,

524

extra_headers: Headers | None = None,

525

extra_query: Query | None = None,

526

extra_body: Body | None = None,

527

timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,

528

) -> SkillCreateResponse:

529

"""

530

Create a new skill.

531

532

Args:

533

display_title: Human-readable label (not in prompt)

534

files: Files to upload for the skill

535

Must be in same directory with SKILL.md at root

536

betas: Beta feature flags

537

extra_headers: Additional HTTP headers

538

extra_query: Additional query parameters

539

extra_body: Additional JSON properties

540

timeout: Request timeout

541

542

Returns:

543

SkillCreateResponse with created skill information

544

"""

545

...

546

547

def retrieve(

548

self,

549

skill_id: str,

550

*,

551

betas: List[str] | NotGiven = NOT_GIVEN,

552

extra_headers: Headers | None = None,

553

extra_query: Query | None = None,

554

extra_body: Body | None = None,

555

timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,

556

) -> SkillRetrieveResponse:

557

"""

558

Get skill details.

559

560

Args:

561

skill_id: Unique identifier for the skill

562

betas: Beta feature flags

563

extra_headers: Additional HTTP headers

564

extra_query: Additional query parameters

565

extra_body: Additional JSON properties

566

timeout: Request timeout

567

568

Returns:

569

SkillRetrieveResponse with skill details

570

"""

571

...

572

573

def list(

574

self,

575

*,

576

limit: int | NotGiven = NOT_GIVEN,

577

page: str | NotGiven = NOT_GIVEN,

578

source: str | NotGiven = NOT_GIVEN,

579

betas: List[str] | NotGiven = NOT_GIVEN,

580

extra_headers: Headers | None = None,

581

extra_query: Query | None = None,

582

extra_body: Body | None = None,

583

timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,

584

) -> SyncPageCursor[SkillListResponse]:

585

"""

586

List skills.

587

588

Args:

589

limit: Results per page (max 100, default 20)

590

page: Pagination token from next_page

591

source: Filter by source ("custom" or "anthropic")

592

betas: Beta feature flags

593

extra_headers: Additional HTTP headers

594

extra_query: Additional query parameters

595

extra_body: Additional JSON properties

596

timeout: Request timeout

597

598

Returns:

599

Cursor-paginated list of SkillListResponse

600

"""

601

...

602

603

def delete(

604

self,

605

skill_id: str,

606

*,

607

betas: List[str] | NotGiven = NOT_GIVEN,

608

extra_headers: Headers | None = None,

609

extra_query: Query | None = None,

610

extra_body: Body | None = None,

611

timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,

612

) -> SkillDeleteResponse:

613

"""

614

Delete a skill.

615

616

Args:

617

skill_id: Unique identifier for the skill

618

betas: Beta feature flags

619

extra_headers: Additional HTTP headers

620

extra_query: Additional query parameters

621

extra_body: Additional JSON properties

622

timeout: Request timeout

623

624

Returns:

625

SkillDeleteResponse with deletion confirmation

626

"""

627

...

628

629

@property

630

def versions(self) -> Versions:

631

"""Skill versions sub-resource."""

632

...

633

634

class AsyncSkills:

635

"""Async version of Skills resource."""

636

# Same methods as Skills, all async

637

...

638

```

639

640

**Usage Example:**

641

642

```python

643

from anthropic import Anthropic

644

645

client = Anthropic()

646

647

# Create a skill with files

648

files = [

649

open("SKILL.md", "rb"),

650

open("helper.py", "rb"),

651

]

652

653

skill = client.beta.skills.create(

654

display_title="Data Analysis Helper",

655

files=files

656

)

657

print(f"Created skill: {skill.id}")

658

659

# List all skills

660

skills = client.beta.skills.list(source="custom")

661

for skill in skills:

662

print(f"{skill.id}: {skill.display_title}")

663

664

# Get skill details

665

details = client.beta.skills.retrieve(skill.id)

666

print(f"Description: {details.description}")

667

668

# Delete skill

669

deleted = client.beta.skills.delete(skill.id)

670

print(f"Deleted: {deleted.deleted}")

671

```

672

673

### Skill Versions Resource

674

675

Manage versions of AI skills.

676

677

```python { .api }

678

class Versions:

679

"""Manage skill versions."""

680

681

def create(

682

self,

683

skill_id: str,

684

*,

685

files: List[FileTypes] | NotGiven = NOT_GIVEN,

686

betas: List[str] | NotGiven = NOT_GIVEN,

687

extra_headers: Headers | None = None,

688

extra_query: Query | None = None,

689

extra_body: Body | None = None,

690

timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,

691

) -> VersionCreateResponse:

692

"""

693

Create a skill version.

694

695

Args:

696

skill_id: ID of the skill

697

files: Files for the new version

698

betas: Beta feature flags

699

extra_headers: Additional HTTP headers

700

extra_query: Additional query parameters

701

extra_body: Additional JSON properties

702

timeout: Request timeout

703

704

Returns:

705

VersionCreateResponse with new version information

706

"""

707

...

708

709

def retrieve(

710

self,

711

skill_id: str,

712

version_id: str,

713

*,

714

betas: List[str] | NotGiven = NOT_GIVEN,

715

extra_headers: Headers | None = None,

716

extra_query: Query | None = None,

717

extra_body: Body | None = None,

718

timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,

719

) -> VersionRetrieveResponse:

720

"""

721

Get version details.

722

723

Args:

724

skill_id: ID of the skill

725

version_id: ID of the version

726

betas: Beta feature flags

727

extra_headers: Additional HTTP headers

728

extra_query: Additional query parameters

729

extra_body: Additional JSON properties

730

timeout: Request timeout

731

732

Returns:

733

VersionRetrieveResponse with version details

734

"""

735

...

736

737

def list(

738

self,

739

skill_id: str,

740

*,

741

limit: int | NotGiven = NOT_GIVEN,

742

page: str | NotGiven = NOT_GIVEN,

743

betas: List[str] | NotGiven = NOT_GIVEN,

744

extra_headers: Headers | None = None,

745

extra_query: Query | None = None,

746

extra_body: Body | None = None,

747

timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,

748

) -> SyncPageCursor[VersionListResponse]:

749

"""

750

List versions.

751

752

Args:

753

skill_id: ID of the skill

754

limit: Results per page (max 100, default 20)

755

page: Pagination token from next_page

756

betas: Beta feature flags

757

extra_headers: Additional HTTP headers

758

extra_query: Additional query parameters

759

extra_body: Additional JSON properties

760

timeout: Request timeout

761

762

Returns:

763

Cursor-paginated list of VersionListResponse

764

"""

765

...

766

767

def delete(

768

self,

769

skill_id: str,

770

version_id: str,

771

*,

772

betas: List[str] | NotGiven = NOT_GIVEN,

773

extra_headers: Headers | None = None,

774

extra_query: Query | None = None,

775

extra_body: Body | None = None,

776

timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,

777

) -> VersionDeleteResponse:

778

"""

779

Delete a version.

780

781

Args:

782

skill_id: ID of the skill

783

version_id: ID of the version

784

betas: Beta feature flags

785

extra_headers: Additional HTTP headers

786

extra_query: Additional query parameters

787

extra_body: Additional JSON properties

788

timeout: Request timeout

789

790

Returns:

791

VersionDeleteResponse with deletion confirmation

792

"""

793

...

794

795

class AsyncVersions:

796

"""Async version of Versions resource."""

797

# Same methods as Versions, all async

798

...

799

```

800

801

**Usage Example:**

802

803

```python

804

from anthropic import Anthropic

805

806

client = Anthropic()

807

808

# Create a new version of a skill

809

new_version = client.beta.skills.versions.create(

810

skill_id="skill_123",

811

files=[

812

open("SKILL.md", "rb"),

813

open("updated_helper.py", "rb"),

814

]

815

)

816

print(f"Created version: {new_version.version_id}")

817

818

# List all versions

819

versions = client.beta.skills.versions.list(skill_id="skill_123")

820

for version in versions:

821

print(f"Version {version.version_id}: {version.created_at}")

822

823

# Get version details

824

details = client.beta.skills.versions.retrieve(

825

skill_id="skill_123",

826

version_id="ver_456"

827

)

828

829

# Delete old version

830

deleted = client.beta.skills.versions.delete(

831

skill_id="skill_123",

832

version_id="ver_old"

833

)

834

```

835

836

## Types

837

838

### BetaMessage

839

840

Extended message response with beta features.

841

842

```python { .api }

843

class BetaMessage(BaseModel):

844

"""Beta message response with extended features."""

845

846

id: str

847

"""Unique object identifier."""

848

849

container: BetaContainer | None

850

"""Container information for code execution tool."""

851

852

content: List[BetaContentBlock]

853

"""Content blocks generated by the model."""

854

855

context_management: BetaContextManagementResponse | None

856

"""Context management strategies applied."""

857

858

model: str

859

"""Model that completed the request."""

860

861

role: Literal["assistant"]

862

"""Always "assistant" for responses."""

863

864

stop_reason: BetaStopReason | None

865

"""Reason for stopping generation."""

866

867

stop_sequence: str | None

868

"""Stop sequence that was matched."""

869

870

type: Literal["message"]

871

"""Always "message"."""

872

873

usage: BetaUsage

874

"""Token usage information with extended metrics."""

875

```

876

877

### ParsedBetaMessage

878

879

Message with parsed structured output.

880

881

```python { .api }

882

class ParsedBetaMessage(BetaMessage, Generic[ResponseFormatT]):

883

"""Message with typed parsed output."""

884

885

parsed_output: ResponseFormatT | None

886

"""Parsed structured output matching output_format schema."""

887

```

888

889

### BetaContentBlock

890

891

Union of all beta content block types.

892

893

```python { .api }

894

BetaContentBlock = Union[

895

BetaTextBlock,

896

BetaThinkingBlock,

897

BetaRedactedThinkingBlock,

898

BetaToolUseBlock,

899

BetaServerToolUseBlock,

900

BetaWebSearchToolResultBlock,

901

BetaWebFetchToolResultBlock,

902

BetaCodeExecutionToolResultBlock,

903

BetaBashCodeExecutionToolResultBlock,

904

BetaTextEditorCodeExecutionToolResultBlock,

905

BetaMCPToolUseBlock,

906

BetaMCPToolResultBlock,

907

BetaContainerUploadBlock,

908

]

909

```

910

911

### BetaTextBlock

912

913

Text content block.

914

915

```python { .api }

916

class BetaTextBlock(BaseModel):

917

"""Text content block."""

918

919

type: Literal["text"]

920

"""Always "text"."""

921

922

text: str

923

"""Text content."""

924

925

citations: List[BetaCitation] | None

926

"""Citations for text content."""

927

```

928

929

### BetaThinkingBlock

930

931

Extended thinking content block.

932

933

```python { .api }

934

class BetaThinkingBlock(BaseModel):

935

"""Extended thinking content."""

936

937

type: Literal["thinking"]

938

"""Always "thinking"."""

939

940

thinking: str

941

"""Thinking/reasoning content."""

942

```

943

944

### BetaRedactedThinkingBlock

945

946

Redacted thinking placeholder.

947

948

```python { .api }

949

class BetaRedactedThinkingBlock(BaseModel):

950

"""Redacted thinking placeholder."""

951

952

type: Literal["redacted_thinking"]

953

"""Always "redacted_thinking"."""

954

```

955

956

### BetaToolUseBlock

957

958

Tool invocation block.

959

960

```python { .api }

961

class BetaToolUseBlock(BaseModel):

962

"""Tool use request."""

963

964

type: Literal["tool_use"]

965

"""Always "tool_use"."""

966

967

id: str

968

"""Unique tool use identifier."""

969

970

name: str

971

"""Tool name."""

972

973

input: dict

974

"""Tool input parameters."""

975

```

976

977

### BetaUsage

978

979

Extended token usage information.

980

981

```python { .api }

982

class BetaUsage(BaseModel):

983

"""Extended usage metrics."""

984

985

input_tokens: int

986

"""Input tokens used."""

987

988

output_tokens: int

989

"""Output tokens generated."""

990

991

cache_creation_input_tokens: int | None

992

"""Tokens used to create cache."""

993

994

cache_read_input_tokens: int | None

995

"""Tokens read from cache."""

996

997

thinking_tokens: int | None

998

"""Tokens used for extended thinking."""

999

1000

cache_hit_input_tokens: int | None

1001

"""Tokens that hit cache."""

1002

```

1003

1004

### BetaMessageTokensCount

1005

1006

Token count result for beta messages.

1007

1008

```python { .api }

1009

class BetaMessageTokensCount(BaseModel):

1010

"""Token count with beta features."""

1011

1012

input_tokens: int

1013

"""Number of input tokens."""

1014

```

1015

1016

### FileMetadata

1017

1018

File upload metadata.

1019

1020

```python { .api }

1021

class FileMetadata(BaseModel):

1022

"""File metadata."""

1023

1024

id: str

1025

"""File identifier."""

1026

1027

type: Literal["file"]

1028

"""Always "file"."""

1029

1030

filename: str

1031

"""Original filename."""

1032

1033

bytes: int

1034

"""File size in bytes."""

1035

1036

purpose: str

1037

"""File purpose."""

1038

1039

created_at: datetime

1040

"""Upload timestamp."""

1041

```

1042

1043

### DeletedFile

1044

1045

File deletion confirmation.

1046

1047

```python { .api }

1048

class DeletedFile(BaseModel):

1049

"""File deletion result."""

1050

1051

id: str

1052

"""File identifier."""

1053

1054

type: Literal["file_deleted"]

1055

"""Always "file_deleted"."""

1056

1057

deleted: bool

1058

"""Deletion status."""

1059

```

1060

1061

### SkillCreateResponse

1062

1063

Skill creation result.

1064

1065

```python { .api }

1066

class SkillCreateResponse(BaseModel):

1067

"""Skill creation response."""

1068

1069

id: str

1070

"""Skill identifier."""

1071

1072

# Additional fields vary by API version

1073

```

1074

1075

### SkillRetrieveResponse

1076

1077

Skill details.

1078

1079

```python { .api }

1080

class SkillRetrieveResponse(BaseModel):

1081

"""Skill details."""

1082

1083

id: str

1084

"""Skill identifier."""

1085

1086

display_title: str | None

1087

"""Human-readable label."""

1088

1089

description: str | None

1090

"""Skill description."""

1091

1092

# Additional fields vary by API version

1093

```

1094

1095

### SkillListResponse

1096

1097

Skill in list response.

1098

1099

```python { .api }

1100

class SkillListResponse(BaseModel):

1101

"""Skill in list."""

1102

1103

id: str

1104

"""Skill identifier."""

1105

1106

# Additional fields vary by API version

1107

```

1108

1109

### SkillDeleteResponse

1110

1111

Skill deletion confirmation.

1112

1113

```python { .api }

1114

class SkillDeleteResponse(BaseModel):

1115

"""Skill deletion result."""

1116

1117

deleted: bool

1118

"""Deletion status."""

1119

```

1120

1121

### VersionCreateResponse

1122

1123

Version creation result.

1124

1125

```python { .api }

1126

class VersionCreateResponse(BaseModel):

1127

"""Version creation response."""

1128

1129

version_id: str

1130

"""Version identifier."""

1131

1132

# Additional fields vary by API version

1133

```

1134

1135

### VersionRetrieveResponse

1136

1137

Version details.

1138

1139

```python { .api }

1140

class VersionRetrieveResponse(BaseModel):

1141

"""Version details."""

1142

1143

version_id: str

1144

"""Version identifier."""

1145

1146

# Additional fields vary by API version

1147

```

1148

1149

### VersionListResponse

1150

1151

Version in list response.

1152

1153

```python { .api }

1154

class VersionListResponse(BaseModel):

1155

"""Version in list."""

1156

1157

version_id: str

1158

"""Version identifier."""

1159

1160

# Additional fields vary by API version

1161

```

1162

1163

### VersionDeleteResponse

1164

1165

Version deletion confirmation.

1166

1167

```python { .api }

1168

class VersionDeleteResponse(BaseModel):

1169

"""Version deletion result."""

1170

1171

deleted: bool

1172

"""Deletion status."""

1173

```

1174

1175

### BetaContextManagementResponse

1176

1177

Context management information.

1178

1179

```python { .api }

1180

class BetaContextManagementResponse(BaseModel):

1181

"""Context management response."""

1182

1183

# Fields vary by API version and strategy

1184

```

1185

1186

### BetaStopReason

1187

1188

Reason for stopping generation.

1189

1190

```python { .api }

1191

BetaStopReason = Literal[

1192

"end_turn", # Natural stopping point

1193

"max_tokens", # Exceeded max_tokens

1194

"stop_sequence", # Matched stop sequence

1195

"tool_use", # Invoked tools

1196

"pause_turn", # Paused long-running turn

1197

"refusal", # Policy violation

1198

]

1199

```

1200

1201

### BetaThinkingConfigParam

1202

1203

Extended thinking configuration.

1204

1205

```python { .api }

1206

class BetaThinkingConfigEnabledParam(TypedDict):

1207

"""Enable extended thinking."""

1208

1209

type: Literal["enabled"]

1210

"""Always "enabled"."""

1211

1212

budget_tokens: int | NotGiven

1213

"""Token budget for thinking (optional)."""

1214

1215

class BetaThinkingConfigDisabledParam(TypedDict):

1216

"""Disable extended thinking."""

1217

1218

type: Literal["disabled"]

1219

"""Always "disabled"."""

1220

1221

BetaThinkingConfigParam = Union[

1222

BetaThinkingConfigEnabledParam,

1223

BetaThinkingConfigDisabledParam

1224

]

1225

```

1226

1227

### BetaOutputFormatParam

1228

1229

Structured output format specification.

1230

1231

```python { .api }

1232

class BetaJSONSchemaParam(TypedDict):

1233

"""JSON schema for structured output."""

1234

1235

name: str

1236

"""Schema name."""

1237

1238

schema: dict

1239

"""JSON schema definition."""

1240

1241

strict: bool | NotGiven

1242

"""Strict validation (optional)."""

1243

1244

class BetaJSONOutputFormatParam(TypedDict):

1245

"""JSON output format."""

1246

1247

type: Literal["json_schema"]

1248

"""Always "json_schema"."""

1249

1250

json_schema: BetaJSONSchemaParam

1251

"""Schema specification."""

1252

1253

BetaOutputFormatParam = BetaJSONOutputFormatParam

1254

```

1255

1256

### BetaContextManagementConfigParam

1257

1258

Context management configuration.

1259

1260

```python { .api }

1261

class BetaContextManagementConfigParam(TypedDict):

1262

"""Context management config."""

1263

1264

# Fields vary by API version

1265

```

1266

1267

## Complete Examples

1268

1269

### Extended Thinking with Structured Output

1270

1271

```python

1272

from anthropic import Anthropic

1273

from pydantic import BaseModel

1274

1275

client = Anthropic()

1276

1277

class MathSolution(BaseModel):

1278

steps: list[str]

1279

answer: str

1280

confidence: float

1281

1282

message = client.beta.messages.parse(

1283

model="claude-3-5-sonnet-20241022",

1284

max_tokens=4096,

1285

thinking={

1286

"type": "enabled",

1287

"budget_tokens": 2000

1288

},

1289

messages=[

1290

{

1291

"role": "user",

1292

"content": "Solve: If x^2 + 2x - 3 = 0, what is x?"

1293

}

1294

],

1295

output_format={

1296

"type": "json_schema",

1297

"json_schema": {

1298

"name": "solution",

1299

"schema": MathSolution.model_json_schema()

1300

}

1301

}

1302

)

1303

1304

# Access thinking process

1305

for block in message.content:

1306

if block.type == "thinking":

1307

print(f"Reasoning:\n{block.thinking}\n")

1308

1309

# Access structured output

1310

solution: MathSolution = message.parsed_output

1311

print("Solution Steps:")

1312

for i, step in enumerate(solution.steps, 1):

1313

print(f"{i}. {step}")

1314

print(f"\nAnswer: {solution.answer}")

1315

print(f"Confidence: {solution.confidence:.0%}")

1316

```

1317

1318

### File Upload and Usage

1319

1320

```python

1321

from anthropic import Anthropic

1322

1323

client = Anthropic()

1324

1325

# Upload multiple files

1326

files = []

1327

for filename in ["data1.csv", "data2.csv", "report.pdf"]:

1328

with open(filename, "rb") as f:

1329

file = client.beta.files.upload(file=f)

1330

files.append(file)

1331

print(f"Uploaded {file.filename}: {file.id}")

1332

1333

# Use files in message (if supported by API)

1334

# This is a conceptual example

1335

message = client.beta.messages.create(

1336

model="claude-3-5-sonnet-20241022",

1337

max_tokens=2048,

1338

messages=[

1339

{

1340

"role": "user",

1341

"content": [

1342

{

1343

"type": "document",

1344

"source": {

1345

"type": "file",

1346

"file_id": files[0].id

1347

}

1348

},

1349

{

1350

"type": "text",

1351

"text": "Analyze this data"

1352

}

1353

]

1354

}

1355

]

1356

)

1357

1358

# Cleanup

1359

for file in files:

1360

client.beta.files.delete(file.id)

1361

```

1362

1363

### Creating and Using Skills

1364

1365

```python

1366

from anthropic import Anthropic

1367

1368

client = Anthropic()

1369

1370

# Create a skill directory structure first

1371

# SKILL.md should define the skill's capabilities

1372

# helper.py should contain supporting code

1373

1374

with open("skill/SKILL.md", "rb") as skill_md, \

1375

open("skill/helper.py", "rb") as helper:

1376

1377

skill = client.beta.skills.create(

1378

display_title="Data Processing Assistant",

1379

files=[skill_md, helper]

1380

)

1381

1382

print(f"Created skill: {skill.id}")

1383

1384

# Use the skill in messages (API-dependent)

1385

# This is a conceptual example

1386

message = client.beta.messages.create(

1387

model="claude-3-5-sonnet-20241022",

1388

max_tokens=1024,

1389

messages=[

1390

{

1391

"role": "user",

1392

"content": "Process this dataset using the skill"

1393

}

1394

],

1395

# skills=[skill.id] # Hypothetical parameter

1396

)

1397

1398

# Update the skill with a new version

1399

with open("skill/SKILL.md", "rb") as skill_md, \

1400

open("skill/improved_helper.py", "rb") as helper:

1401

1402

version = client.beta.skills.versions.create(

1403

skill_id=skill.id,

1404

files=[skill_md, helper]

1405

)

1406

1407

print(f"Created version: {version.version_id}")

1408

1409

# List all versions

1410

versions = client.beta.skills.versions.list(skill_id=skill.id)

1411

for v in versions:

1412

print(f"Version {v.version_id}")

1413

```

1414

1415

### Streaming Beta Messages

1416

1417

```python

1418

from anthropic import Anthropic

1419

1420

client = Anthropic()

1421

1422

# Stream beta message with extended features

1423

with client.beta.messages.stream(

1424

model="claude-3-5-sonnet-20241022",

1425

max_tokens=2048,

1426

thinking={

1427

"type": "enabled",

1428

"budget_tokens": 1000

1429

},

1430

messages=[

1431

{

1432

"role": "user",

1433

"content": "Explain quantum entanglement"

1434

}

1435

]

1436

) as stream:

1437

for event in stream:

1438

if event.type == "content_block_start":

1439

if event.content_block.type == "thinking":

1440

print("\n[Thinking...]")

1441

elif event.content_block.type == "text":

1442

print("\n[Answer]")

1443

1444

elif event.type == "content_block_delta":

1445

if event.delta.type == "thinking_delta":

1446

print(event.delta.thinking, end="", flush=True)

1447

elif event.delta.type == "text_delta":

1448

print(event.delta.text, end="", flush=True)

1449

1450

elif event.type == "message_stop":

1451

print("\n")

1452

1453

# Get final message

1454

final_message = stream.get_final_message()

1455

print(f"\nUsage: {final_message.usage.input_tokens} in, "

1456

f"{final_message.usage.output_tokens} out")

1457

if final_message.usage.thinking_tokens:

1458

print(f"Thinking tokens: {final_message.usage.thinking_tokens}")

1459

```

1460

1461

### Context Management

1462

1463

```python

1464

from anthropic import Anthropic

1465

1466

client = Anthropic()

1467

1468

# Use context management (API-dependent feature)

1469

# This is a conceptual example

1470

message = client.beta.messages.create(

1471

model="claude-3-5-sonnet-20241022",

1472

max_tokens=4096,

1473

context_management={

1474

# Configuration depends on API version

1475

"strategy": "auto",

1476

"trigger": {

1477

"type": "clear_at_least",

1478

"tokens": 50000

1479

}

1480

},

1481

messages=[

1482

{"role": "user", "content": "Very long conversation..."},

1483

{"role": "assistant", "content": "Response..."},

1484

# Many more messages...

1485

]

1486

)

1487

1488

# Check context management response

1489

if message.context_management:

1490

print(f"Context management applied: {message.context_management}")

1491

```

1492