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

client-initialization.mddocs/

0

# Client Initialization

1

2

Comprehensive guide to creating and configuring the Anthropic client instances for interacting with the Anthropic API. The SDK provides both synchronous and asynchronous clients with extensive configuration options for authentication, timeouts, retries, custom headers, and HTTP client customization.

3

4

## Core Imports

5

6

```python

7

from anthropic import Anthropic, AsyncAnthropic

8

from anthropic import Client, AsyncClient # Aliases

9

```

10

11

For type annotations:

12

13

```python

14

import httpx

15

from anthropic.types import Timeout, RequestOptions, NotGiven

16

```

17

18

## Basic Usage

19

20

### Basic Client Initialization

21

22

```python

23

from anthropic import Anthropic

24

25

# Initialize with API key from environment variable ANTHROPIC_API_KEY

26

client = Anthropic()

27

28

# Or explicitly provide the API key

29

client = Anthropic(api_key="your-api-key-here")

30

31

# Use the client to make API calls

32

message = client.messages.create(

33

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

34

max_tokens=1024,

35

messages=[{"role": "user", "content": "Hello!"}]

36

)

37

```

38

39

### Async Client Initialization

40

41

```python

42

from anthropic import AsyncAnthropic

43

import asyncio

44

45

async def main():

46

# Initialize async client

47

client = AsyncAnthropic(api_key="your-api-key-here")

48

49

# Use the async client

50

message = await client.messages.create(

51

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

52

max_tokens=1024,

53

messages=[{"role": "user", "content": "Hello!"}]

54

)

55

56

print(message.content[0].text)

57

58

asyncio.run(main())

59

```

60

61

### Environment-Based Configuration

62

63

```python

64

import os

65

66

# Set environment variables before importing

67

os.environ["ANTHROPIC_API_KEY"] = "your-api-key"

68

os.environ["ANTHROPIC_BASE_URL"] = "https://custom-api.example.com"

69

70

from anthropic import Anthropic

71

72

# Client automatically uses environment variables

73

client = Anthropic()

74

```

75

76

## Capabilities

77

78

### Client Constructors

79

80

Primary constructor for the synchronous Anthropic client.

81

82

```python { .api }

83

class Anthropic:

84

"""

85

Synchronous client for interacting with the Anthropic API.

86

87

Automatically infers api_key from ANTHROPIC_API_KEY environment variable

88

and auth_token from ANTHROPIC_AUTH_TOKEN environment variable if not provided.

89

Base URL defaults to https://api.anthropic.com or ANTHROPIC_BASE_URL env var.

90

"""

91

92

def __init__(

93

self,

94

*,

95

api_key: str | None = None,

96

auth_token: str | None = None,

97

base_url: str | httpx.URL | None = None,

98

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

99

max_retries: int = 2,

100

default_headers: Mapping[str, str] | None = None,

101

default_query: Mapping[str, object] | None = None,

102

http_client: httpx.Client | None = None,

103

) -> None:

104

"""

105

Parameters:

106

api_key: Anthropic API key. Defaults to ANTHROPIC_API_KEY env var.

107

auth_token: Authentication token. Defaults to ANTHROPIC_AUTH_TOKEN env var.

108

base_url: Base URL for API requests. Defaults to https://api.anthropic.com.

109

timeout: Request timeout in seconds or httpx.Timeout object.

110

Defaults to 600 seconds (10 minutes) with 5 second connect timeout.

111

max_retries: Maximum number of retry attempts. Defaults to 2.

112

default_headers: Default headers to include in all requests.

113

default_query: Default query parameters to include in all requests.

114

http_client: Custom httpx.Client instance. Use DefaultHttpxClient to retain SDK defaults.

115

"""

116

117

# Resource properties

118

completions: Completions

119

messages: Messages

120

models: Models

121

beta: Beta

122

123

# Response wrapper properties

124

with_raw_response: AnthropicWithRawResponse

125

with_streaming_response: AnthropicWithStreamedResponse

126

127

# Legacy prompt constants

128

HUMAN_PROMPT: str = "\n\nHuman:"

129

AI_PROMPT: str = "\n\nAssistant:"

130

```

131

132

Primary constructor for the asynchronous Anthropic client.

133

134

```python { .api }

135

class AsyncAnthropic:

136

"""

137

Asynchronous client for interacting with the Anthropic API.

138

139

Automatically infers api_key from ANTHROPIC_API_KEY environment variable

140

and auth_token from ANTHROPIC_AUTH_TOKEN environment variable if not provided.

141

Base URL defaults to https://api.anthropic.com or ANTHROPIC_BASE_URL env var.

142

"""

143

144

def __init__(

145

self,

146

*,

147

api_key: str | None = None,

148

auth_token: str | None = None,

149

base_url: str | httpx.URL | None = None,

150

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

151

max_retries: int = 2,

152

default_headers: Mapping[str, str] | None = None,

153

default_query: Mapping[str, object] | None = None,

154

http_client: httpx.AsyncClient | None = None,

155

) -> None:

156

"""

157

Parameters:

158

api_key: Anthropic API key. Defaults to ANTHROPIC_API_KEY env var.

159

auth_token: Authentication token. Defaults to ANTHROPIC_AUTH_TOKEN env var.

160

base_url: Base URL for API requests. Defaults to https://api.anthropic.com.

161

timeout: Request timeout in seconds or httpx.Timeout object.

162

Defaults to 600 seconds (10 minutes) with 5 second connect timeout.

163

max_retries: Maximum number of retry attempts. Defaults to 2.

164

default_headers: Default headers to include in all requests.

165

default_query: Default query parameters to include in all requests.

166

http_client: Custom httpx.AsyncClient instance. Use DefaultAsyncHttpxClient to retain SDK defaults.

167

"""

168

169

# Resource properties

170

completions: AsyncCompletions

171

messages: AsyncMessages

172

models: AsyncModels

173

beta: AsyncBeta

174

175

# Response wrapper properties

176

with_raw_response: AsyncAnthropicWithRawResponse

177

with_streaming_response: AsyncAnthropicWithStreamedResponse

178

179

# Legacy prompt constants

180

HUMAN_PROMPT: str = "\n\nHuman:"

181

AI_PROMPT: str = "\n\nAssistant:"

182

```

183

184

### Client Aliases

185

186

Convenience aliases for the main client classes.

187

188

```python { .api }

189

# Alias for Anthropic

190

Client = Anthropic

191

192

# Alias for AsyncAnthropic

193

AsyncClient = AsyncAnthropic

194

```

195

196

Usage:

197

198

```python

199

from anthropic import Client, AsyncClient

200

201

# These are equivalent to using Anthropic and AsyncAnthropic

202

client = Client(api_key="your-api-key")

203

async_client = AsyncClient(api_key="your-api-key")

204

```

205

206

### Authentication Configuration

207

208

Both API key and bearer token authentication are supported.

209

210

```python

211

from anthropic import Anthropic

212

213

# API key authentication (most common)

214

client = Anthropic(api_key="your-api-key")

215

216

# Bearer token authentication

217

client = Anthropic(auth_token="your-auth-token")

218

219

# Environment variable authentication (recommended for production)

220

# Set ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN

221

client = Anthropic()

222

```

223

224

### Timeout Configuration

225

226

Configure request timeouts with granular control over connection and read timeouts.

227

228

```python

229

from anthropic import Anthropic

230

import httpx

231

232

# Simple timeout in seconds (applies to all operations)

233

client = Anthropic(

234

api_key="your-api-key",

235

timeout=30.0

236

)

237

238

# Granular timeout configuration

239

client = Anthropic(

240

api_key="your-api-key",

241

timeout=httpx.Timeout(

242

timeout=60.0, # Total timeout

243

connect=5.0, # Connection timeout

244

read=30.0, # Read timeout

245

write=10.0, # Write timeout

246

pool=5.0 # Pool timeout

247

)

248

)

249

250

# Disable timeout (not recommended for production)

251

client = Anthropic(

252

api_key="your-api-key",

253

timeout=None

254

)

255

256

# Default timeout if not specified:

257

# - Total: 600 seconds (10 minutes)

258

# - Connect: 5 seconds

259

```

260

261

### Retry Configuration

262

263

Configure automatic retry behavior for failed requests.

264

265

```python

266

from anthropic import Anthropic

267

268

# Custom retry count

269

client = Anthropic(

270

api_key="your-api-key",

271

max_retries=5 # Retry up to 5 times

272

)

273

274

# Disable retries

275

client = Anthropic(

276

api_key="your-api-key",

277

max_retries=0

278

)

279

280

# Default: 2 retries with exponential backoff

281

# - Initial delay: 0.5 seconds

282

# - Maximum delay: 8.0 seconds

283

```

284

285

### Custom Headers and Query Parameters

286

287

Add default headers or query parameters to all requests.

288

289

```python

290

from anthropic import Anthropic

291

292

# Add custom headers for tracking or identification

293

client = Anthropic(

294

api_key="your-api-key",

295

default_headers={

296

"X-Custom-Header": "custom-value",

297

"X-Request-Source": "my-application",

298

"X-User-ID": "user-123"

299

}

300

)

301

302

# Add default query parameters

303

client = Anthropic(

304

api_key="your-api-key",

305

default_query={

306

"tracking_id": "abc123",

307

"source": "web-app"

308

}

309

)

310

311

# Combine both

312

client = Anthropic(

313

api_key="your-api-key",

314

default_headers={"X-App-Version": "1.0.0"},

315

default_query={"environment": "production"}

316

)

317

```

318

319

### Base URL Customization

320

321

Override the default API endpoint for custom deployments or proxies.

322

323

```python

324

from anthropic import Anthropic

325

import httpx

326

327

# Custom base URL as string

328

client = Anthropic(

329

api_key="your-api-key",

330

base_url="https://custom-api.example.com"

331

)

332

333

# Custom base URL as httpx.URL

334

client = Anthropic(

335

api_key="your-api-key",

336

base_url=httpx.URL("https://custom-api.example.com/v1")

337

)

338

339

# Environment variable (set ANTHROPIC_BASE_URL)

340

client = Anthropic(api_key="your-api-key") # Uses ANTHROPIC_BASE_URL if set

341

342

# Default: https://api.anthropic.com

343

```

344

345

### Custom HTTP Client Configuration

346

347

Provide a custom httpx client for advanced configuration including proxies, custom certificates, and connection pooling.

348

349

```python

350

from anthropic import Anthropic, DefaultHttpxClient

351

import httpx

352

353

# Use DefaultHttpxClient to retain SDK defaults

354

http_client = httpx.Client(

355

limits=httpx.Limits(

356

max_connections=1000,

357

max_keepalive_connections=100

358

),

359

timeout=httpx.Timeout(timeout=600.0, connect=5.0),

360

follow_redirects=True

361

)

362

363

client = Anthropic(

364

api_key="your-api-key",

365

http_client=http_client

366

)

367

368

# Custom client with proxy

369

http_client = httpx.Client(

370

proxies={

371

"http://": "http://proxy.example.com:8080",

372

"https://": "http://proxy.example.com:8080"

373

}

374

)

375

376

client = Anthropic(

377

api_key="your-api-key",

378

http_client=http_client

379

)

380

381

# Custom client with SSL verification disabled (not recommended for production)

382

http_client = httpx.Client(verify=False)

383

384

client = Anthropic(

385

api_key="your-api-key",

386

http_client=http_client

387

)

388

389

# Async client with custom configuration

390

async_http_client = httpx.AsyncClient(

391

limits=httpx.Limits(max_connections=100),

392

timeout=httpx.Timeout(timeout=30.0)

393

)

394

395

async_client = AsyncAnthropic(

396

api_key="your-api-key",

397

http_client=async_http_client

398

)

399

```

400

401

### Client Copying with Modified Options

402

403

Create a new client instance based on an existing one with modified options.

404

405

```python { .api }

406

def copy(

407

self,

408

*,

409

api_key: str | None = None,

410

auth_token: str | None = None,

411

base_url: str | httpx.URL | None = None,

412

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

413

http_client: httpx.Client | None = None,

414

max_retries: int | NotGiven = NOT_GIVEN,

415

default_headers: Mapping[str, str] | None = None,

416

set_default_headers: Mapping[str, str] | None = None,

417

default_query: Mapping[str, object] | None = None,

418

set_default_query: Mapping[str, object] | None = None,

419

) -> Self:

420

"""

421

Create a new client instance re-using options from the current client.

422

423

Parameters:

424

api_key: Override API key

425

auth_token: Override auth token

426

base_url: Override base URL

427

timeout: Override timeout configuration

428

http_client: Override HTTP client

429

max_retries: Override max retries

430

default_headers: Additional headers to merge with existing defaults

431

set_default_headers: Replace all default headers (mutually exclusive with default_headers)

432

default_query: Additional query params to merge with existing defaults

433

set_default_query: Replace all default query params (mutually exclusive with default_query)

434

435

Returns:

436

New client instance with combined configuration

437

438

Raises:

439

ValueError: If both default_headers and set_default_headers are provided,

440

or if both default_query and set_default_query are provided

441

"""

442

443

# Alias for inline usage

444

with_options = copy

445

```

446

447

Usage examples:

448

449

```python

450

from anthropic import Anthropic

451

452

# Create base client

453

base_client = Anthropic(

454

api_key="your-api-key",

455

timeout=30.0,

456

default_headers={"X-App": "my-app"}

457

)

458

459

# Create a copy with longer timeout

460

long_timeout_client = base_client.copy(timeout=120.0)

461

462

# Create a copy with additional headers (merges with existing)

463

tracked_client = base_client.copy(

464

default_headers={"X-Request-ID": "req-123"}

465

)

466

# Headers: {"X-App": "my-app", "X-Request-ID": "req-123"}

467

468

# Create a copy with completely new headers (replaces existing)

469

new_headers_client = base_client.copy(

470

set_default_headers={"X-New-App": "different-app"}

471

)

472

# Headers: {"X-New-App": "different-app"}

473

474

# Inline usage with with_options alias

475

message = base_client.with_options(timeout=60.0).messages.create(

476

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

477

max_tokens=1024,

478

messages=[{"role": "user", "content": "Hello!"}]

479

)

480

```

481

482

### Response Wrappers

483

484

Access raw HTTP responses or streaming-enabled response objects.

485

486

```python { .api }

487

# Property that returns a wrapper with access to raw responses

488

with_raw_response: AnthropicWithRawResponse

489

490

# Property that returns a wrapper with streaming-enabled responses

491

with_streaming_response: AnthropicWithStreamedResponse

492

```

493

494

Usage with raw responses:

495

496

```python

497

from anthropic import Anthropic

498

499

client = Anthropic(api_key="your-api-key")

500

501

# Access raw HTTP response

502

response = client.with_raw_response.messages.create(

503

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

504

max_tokens=1024,

505

messages=[{"role": "user", "content": "Hello!"}]

506

)

507

508

# Access response details

509

print(response.http_response.status_code) # HTTP status code

510

print(response.headers) # Response headers

511

print(response.status_code) # Shorthand for status code

512

print(response.retries_taken) # Number of retries

513

514

# Parse the response body

515

message = response.parse()

516

print(message.content[0].text)

517

```

518

519

Usage with streaming responses:

520

521

```python

522

from anthropic import Anthropic

523

524

client = Anthropic(api_key="your-api-key")

525

526

# Enable streaming on individual resource methods

527

with client.with_streaming_response.messages.create(

528

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

529

max_tokens=1024,

530

messages=[{"role": "user", "content": "Hello!"}]

531

) as response:

532

for line in response.iter_lines():

533

print(line)

534

```

535

536

### Default HTTP Client Classes

537

538

Pre-configured HTTP clients that retain SDK defaults.

539

540

```python { .api }

541

class DefaultHttpxClient(httpx.Client):

542

"""

543

Default synchronous httpx client with SDK defaults.

544

545

Default configuration:

546

- limits: max_connections=1000, max_keepalive_connections=100

547

- timeout: 600 seconds (10 minutes) with 5 second connect timeout

548

- follow_redirects: True

549

"""

550

551

class DefaultAsyncHttpxClient(httpx.AsyncClient):

552

"""

553

Default asynchronous httpx client with SDK defaults.

554

555

Default configuration:

556

- limits: max_connections=1000, max_keepalive_connections=100

557

- timeout: 600 seconds (10 minutes) with 5 second connect timeout

558

- follow_redirects: True

559

"""

560

```

561

562

Usage:

563

564

```python

565

from anthropic import Anthropic, DefaultHttpxClient

566

import httpx

567

568

# Extend SDK defaults with additional configuration

569

http_client = httpx.Client(

570

proxies={"https://": "http://proxy.example.com:8080"},

571

# SDK defaults are preserved: limits, timeout, follow_redirects

572

)

573

574

client = Anthropic(

575

api_key="your-api-key",

576

http_client=http_client

577

)

578

```

579

580

## Types

581

582

### Timeout Types

583

584

```python { .api }

585

# Type alias for httpx.Timeout

586

Timeout = httpx.Timeout

587

588

# Can be used as:

589

# - float: Simple timeout in seconds

590

# - httpx.Timeout: Granular timeout configuration

591

# - None: No timeout

592

# - NotGiven: Use default timeout

593

```

594

595

### Request Options

596

597

```python { .api }

598

class RequestOptions(TypedDict, total=False):

599

"""

600

Options for individual API requests.

601

602

Used to override client defaults on a per-request basis.

603

"""

604

605

extra_headers: Headers | None

606

extra_query: Query | None

607

extra_body: Body | None

608

timeout: float | httpx.Timeout | None | NotGiven

609

```

610

611

Usage:

612

613

```python

614

from anthropic import Anthropic

615

616

client = Anthropic(api_key="your-api-key")

617

618

# Override options for a single request

619

message = client.messages.create(

620

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

621

max_tokens=1024,

622

messages=[{"role": "user", "content": "Hello!"}],

623

extra_headers={"X-Request-ID": "unique-id"},

624

timeout=120.0

625

)

626

```

627

628

### Special Values

629

630

```python { .api }

631

# Sentinel value indicating parameter not provided

632

NOT_GIVEN: NotGiven

633

634

# Type for NOT_GIVEN

635

class NotGiven: ...

636

637

# Type for omitted values

638

class Omit: ...

639

640

# Value to explicitly omit a parameter

641

omit: Omit

642

```

643

644

## Environment Variables

645

646

The client automatically reads configuration from environment variables:

647

648

| Variable | Purpose | Default |

649

|----------|---------|---------|

650

| `ANTHROPIC_API_KEY` | API key for authentication | None (required) |

651

| `ANTHROPIC_AUTH_TOKEN` | Bearer token for authentication | None (alternative to API key) |

652

| `ANTHROPIC_BASE_URL` | Base URL for API requests | `https://api.anthropic.com` |

653

654

## Default Configuration Values

655

656

| Setting | Default Value | Description |

657

|---------|---------------|-------------|

658

| `timeout` | 600 seconds (10 minutes) | Total request timeout |

659

| `timeout.connect` | 5 seconds | Connection establishment timeout |

660

| `max_retries` | 2 | Maximum retry attempts |

661

| `base_url` | `https://api.anthropic.com` | API endpoint URL |

662

| `max_connections` | 1000 | Maximum concurrent connections |

663

| `max_keepalive_connections` | 100 | Maximum persistent connections |

664

| `initial_retry_delay` | 0.5 seconds | Initial retry delay |

665

| `max_retry_delay` | 8.0 seconds | Maximum retry delay |

666

667

## Complete Configuration Example

668

669

```python

670

from anthropic import Anthropic

671

import httpx

672

import os

673

674

# Production-ready client configuration

675

client = Anthropic(

676

# Authentication from environment

677

api_key=os.environ.get("ANTHROPIC_API_KEY"),

678

679

# Custom timeout for longer operations

680

timeout=httpx.Timeout(

681

timeout=120.0, # 2 minute total timeout

682

connect=5.0, # 5 second connect timeout

683

read=60.0, # 1 minute read timeout

684

),

685

686

# Aggressive retries for reliability

687

max_retries=5,

688

689

# Tracking headers

690

default_headers={

691

"X-Application": "my-production-app",

692

"X-Environment": "production",

693

"X-Version": "1.0.0",

694

},

695

696

# Custom HTTP client with proxy

697

http_client=httpx.Client(

698

proxies={

699

"http://": os.environ.get("HTTP_PROXY"),

700

"https://": os.environ.get("HTTPS_PROXY"),

701

},

702

limits=httpx.Limits(

703

max_connections=500,

704

max_keepalive_connections=50

705

),

706

)

707

)

708

709

# Use the client

710

message = client.messages.create(

711

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

712

max_tokens=1024,

713

messages=[{"role": "user", "content": "Hello!"}]

714

)

715

```

716