pypi-anthropic

Description
The official Python library for the anthropic API
Author
tessl
Last updated

How to use

npx @tessl/cli registry install tessl/pypi-anthropic@0.66.0

configuration.md docs/

1
# Configuration and Utilities
2
3
Client configuration options, HTTP settings, timeout management, retry policies, and utility functions provide fine-grained control over SDK behavior and enable customization for different deployment scenarios.
4
5
## Capabilities
6
7
### Client Configuration
8
9
Comprehensive configuration options for customizing client behavior, HTTP settings, and request handling.
10
11
```python { .api }
12
class Anthropic:
13
def __init__(
14
self,
15
*,
16
api_key: Optional[str] = None,
17
base_url: Optional[str] = None,
18
timeout: Optional[Timeout] = None,
19
max_retries: Optional[int] = None,
20
default_headers: Optional[Mapping[str, str]] = None,
21
default_query: Optional[Mapping[str, object]] = None,
22
http_client: Optional[httpx.Client] = None,
23
**kwargs
24
): ...
25
26
class AsyncAnthropic:
27
def __init__(
28
self,
29
*,
30
api_key: Optional[str] = None,
31
base_url: Optional[str] = None,
32
timeout: Optional[Timeout] = None,
33
max_retries: Optional[int] = None,
34
default_headers: Optional[Mapping[str, str]] = None,
35
default_query: Optional[Mapping[str, object]] = None,
36
http_client: Optional[httpx.AsyncClient] = None,
37
**kwargs
38
): ...
39
40
@property
41
def with_raw_response(self) -> AnthropicWithRawResponse: ...
42
43
@property
44
def with_streaming_response(self) -> AnthropicWithStreamedResponse: ...
45
```
46
47
### HTTP Client Options
48
49
Default HTTP client implementations with different backends and customization options.
50
51
```python { .api }
52
class DefaultHttpxClient:
53
"""Default synchronous HTTP client using httpx"""
54
def __init__(
55
self,
56
*,
57
limits: Optional[httpx.Limits] = None,
58
timeout: Optional[httpx.Timeout] = None,
59
proxies: Optional[httpx._types.ProxiesTypes] = None,
60
**kwargs
61
): ...
62
63
class DefaultAsyncHttpxClient:
64
"""Default asynchronous HTTP client using httpx"""
65
def __init__(
66
self,
67
*,
68
limits: Optional[httpx.Limits] = None,
69
timeout: Optional[httpx.Timeout] = None,
70
proxies: Optional[httpx._types.ProxiesTypes] = None,
71
**kwargs
72
): ...
73
74
class DefaultAioHttpClient:
75
"""Alternative async HTTP client using aiohttp"""
76
def __init__(
77
self,
78
*,
79
timeout: Optional[aiohttp.ClientTimeout] = None,
80
connector: Optional[aiohttp.BaseConnector] = None,
81
**kwargs
82
): ...
83
```
84
85
### Request Configuration Types
86
87
Types for configuring individual requests and global client settings.
88
89
```python { .api }
90
class RequestOptions(TypedDict, total=False):
91
headers: Optional[Mapping[str, str]]
92
max_retries: Optional[int]
93
timeout: Optional[Timeout]
94
params: Optional[Mapping[str, object]]
95
extra_json: Optional[Mapping[str, object]]
96
97
class Timeout:
98
"""Timeout configuration for requests"""
99
def __init__(
100
self,
101
total: Optional[float] = None,
102
*,
103
connect: Optional[float] = None,
104
read: Optional[float] = None,
105
write: Optional[float] = None,
106
pool: Optional[float] = None
107
): ...
108
109
class Transport:
110
"""HTTP transport configuration"""
111
pass
112
113
class ProxiesTypes:
114
"""Proxy configuration types"""
115
pass
116
```
117
118
### Utility Functions
119
120
Helper functions for file handling and request preparation.
121
122
```python { .api }
123
def file_from_path(path: Union[str, Path]) -> Any:
124
"""Create file object from file path for uploads"""
125
...
126
```
127
128
### Constants
129
130
Default configuration values and SDK constants.
131
132
```python { .api }
133
DEFAULT_TIMEOUT: float
134
DEFAULT_MAX_RETRIES: int
135
DEFAULT_CONNECTION_LIMITS: httpx.Limits
136
137
HUMAN_PROMPT: str # Legacy prompt marker
138
AI_PROMPT: str # Legacy prompt marker
139
```
140
141
## Usage Examples
142
143
### Basic Client Configuration
144
145
```python
146
import os
147
from anthropic import Anthropic
148
149
# Basic configuration with API key
150
client = Anthropic(
151
api_key=os.environ.get("ANTHROPIC_API_KEY")
152
)
153
154
# Configuration with custom base URL
155
client = Anthropic(
156
api_key=os.environ.get("ANTHROPIC_API_KEY"),
157
base_url="https://api.anthropic.com/v1" # Custom endpoint
158
)
159
160
# Configuration with timeout settings
161
client = Anthropic(
162
api_key=os.environ.get("ANTHROPIC_API_KEY"),
163
timeout=30.0 # 30 second timeout
164
)
165
```
166
167
### Advanced Timeout Configuration
168
169
```python
170
from anthropic import Anthropic, Timeout
171
import httpx
172
173
# Detailed timeout configuration
174
timeout_config = Timeout(
175
total=60.0, # Total request timeout
176
connect=10.0, # Connection timeout
177
read=30.0, # Read timeout
178
write=30.0, # Write timeout
179
pool=5.0 # Pool timeout
180
)
181
182
client = Anthropic(
183
api_key=os.environ.get("ANTHROPIC_API_KEY"),
184
timeout=timeout_config
185
)
186
187
# Using httpx.Timeout directly
188
httpx_timeout = httpx.Timeout(
189
timeout=45.0,
190
connect=5.0,
191
read=20.0,
192
write=20.0,
193
pool=2.0
194
)
195
196
client = Anthropic(
197
api_key=os.environ.get("ANTHROPIC_API_KEY"),
198
timeout=httpx_timeout
199
)
200
```
201
202
### Retry Configuration
203
204
```python
205
# Configure retry behavior
206
client = Anthropic(
207
api_key=os.environ.get("ANTHROPIC_API_KEY"),
208
max_retries=5 # Retry up to 5 times on failure
209
)
210
211
# Disable retries
212
client = Anthropic(
213
api_key=os.environ.get("ANTHROPIC_API_KEY"),
214
max_retries=0
215
)
216
217
# Per-request retry override
218
message = client.messages.create(
219
model="claude-sonnet-4-20250514",
220
max_tokens=1024,
221
messages=[{"role": "user", "content": "Hello!"}],
222
extra_options={"max_retries": 2} # Override global retry setting
223
)
224
```
225
226
### Custom Headers and Authentication
227
228
```python
229
# Add custom headers
230
client = Anthropic(
231
api_key=os.environ.get("ANTHROPIC_API_KEY"),
232
default_headers={
233
"User-Agent": "MyApp/1.0",
234
"X-Custom-Header": "custom-value"
235
}
236
)
237
238
# Per-request headers
239
message = client.messages.create(
240
model="claude-sonnet-4-20250514",
241
max_tokens=1024,
242
messages=[{"role": "user", "content": "Hello!"}],
243
extra_options={
244
"headers": {
245
"X-Request-ID": "req-12345",
246
"X-User-ID": "user-67890"
247
}
248
}
249
)
250
```
251
252
### HTTP Client Customization
253
254
```python
255
import httpx
256
from anthropic import Anthropic, DefaultHttpxClient
257
258
# Custom HTTP client with connection limits
259
custom_limits = httpx.Limits(
260
max_keepalive_connections=10,
261
max_connections=20,
262
keepalive_expiry=30.0
263
)
264
265
http_client = DefaultHttpxClient(
266
limits=custom_limits,
267
timeout=httpx.Timeout(30.0)
268
)
269
270
client = Anthropic(
271
api_key=os.environ.get("ANTHROPIC_API_KEY"),
272
http_client=http_client
273
)
274
275
# Using custom httpx client directly
276
custom_httpx_client = httpx.Client(
277
limits=httpx.Limits(max_connections=50),
278
timeout=httpx.Timeout(45.0),
279
headers={"User-Agent": "MyCustomApp/2.0"}
280
)
281
282
client = Anthropic(
283
api_key=os.environ.get("ANTHROPIC_API_KEY"),
284
http_client=custom_httpx_client
285
)
286
```
287
288
### Proxy Configuration
289
290
```python
291
import httpx
292
from anthropic import Anthropic
293
294
# HTTP proxy
295
proxies = {
296
"http://": "http://proxy.example.com:8080",
297
"https://": "https://proxy.example.com:8080"
298
}
299
300
client = Anthropic(
301
api_key=os.environ.get("ANTHROPIC_API_KEY"),
302
http_client=httpx.Client(proxies=proxies)
303
)
304
305
# SOCKS proxy
306
client = Anthropic(
307
api_key=os.environ.get("ANTHROPIC_API_KEY"),
308
http_client=httpx.Client(
309
proxies="socks5://proxy.example.com:1080"
310
)
311
)
312
313
# Proxy with authentication
314
proxy_with_auth = "http://user:pass@proxy.example.com:8080"
315
client = Anthropic(
316
api_key=os.environ.get("ANTHROPIC_API_KEY"),
317
http_client=httpx.Client(proxies=proxy_with_auth)
318
)
319
```
320
321
### Async Client Configuration
322
323
```python
324
import asyncio
325
import httpx
326
from anthropic import AsyncAnthropic, DefaultAsyncHttpxClient, DefaultAioHttpClient
327
328
# Basic async client
329
async_client = AsyncAnthropic(
330
api_key=os.environ.get("ANTHROPIC_API_KEY")
331
)
332
333
# Custom async httpx client
334
custom_async_client = DefaultAsyncHttpxClient(
335
limits=httpx.Limits(max_connections=25),
336
timeout=httpx.Timeout(60.0)
337
)
338
339
async_client = AsyncAnthropic(
340
api_key=os.environ.get("ANTHROPIC_API_KEY"),
341
http_client=custom_async_client
342
)
343
344
# Using aiohttp backend for better async performance
345
aiohttp_client = DefaultAioHttpClient(
346
timeout=aiohttp.ClientTimeout(total=60)
347
)
348
349
async_client = AsyncAnthropic(
350
api_key=os.environ.get("ANTHROPIC_API_KEY"),
351
http_client=aiohttp_client
352
)
353
```
354
355
### Environment-based Configuration
356
357
```python
358
import os
359
from anthropic import Anthropic
360
361
class AnthropicConfig:
362
"""Configuration management for Anthropic client"""
363
364
def __init__(self):
365
self.api_key = os.environ.get("ANTHROPIC_API_KEY")
366
self.base_url = os.environ.get("ANTHROPIC_BASE_URL", "https://api.anthropic.com")
367
self.timeout = float(os.environ.get("ANTHROPIC_TIMEOUT", "30"))
368
self.max_retries = int(os.environ.get("ANTHROPIC_MAX_RETRIES", "3"))
369
self.proxy = os.environ.get("HTTP_PROXY")
370
371
def create_client(self) -> Anthropic:
372
"""Create configured Anthropic client"""
373
374
# Build HTTP client with proxy if specified
375
http_client = None
376
if self.proxy:
377
http_client = httpx.Client(proxies=self.proxy)
378
379
return Anthropic(
380
api_key=self.api_key,
381
base_url=self.base_url,
382
timeout=self.timeout,
383
max_retries=self.max_retries,
384
http_client=http_client
385
)
386
387
# Usage with environment variables
388
config = AnthropicConfig()
389
client = config.create_client()
390
```
391
392
### File Utilities
393
394
```python
395
from anthropic import file_from_path
396
from pathlib import Path
397
398
# Create file object for upload
399
image_file = file_from_path("./image.jpg")
400
document_file = file_from_path(Path("./document.pdf"))
401
402
# Use in message with image
403
message = client.messages.create(
404
model="claude-sonnet-4-20250514",
405
max_tokens=1024,
406
messages=[
407
{
408
"role": "user",
409
"content": [
410
{
411
"type": "image",
412
"source": {
413
"type": "base64",
414
"media_type": "image/jpeg",
415
"data": image_file # file_from_path result
416
}
417
},
418
{
419
"type": "text",
420
"text": "What's in this image?"
421
}
422
]
423
}
424
]
425
)
426
```
427
428
### Production Configuration
429
430
```python
431
import logging
432
from anthropic import Anthropic
433
import httpx
434
435
def create_production_client() -> Anthropic:
436
"""Create a production-ready Anthropic client"""
437
438
# Configure logging
439
logging.basicConfig(level=logging.INFO)
440
441
# Production HTTP client settings
442
limits = httpx.Limits(
443
max_keepalive_connections=20, # Keep connections alive
444
max_connections=100, # Allow more concurrent connections
445
keepalive_expiry=60.0 # Keep connections for 60 seconds
446
)
447
448
timeout = httpx.Timeout(
449
total=120.0, # Allow longer requests in production
450
connect=10.0, # Quick connection timeout
451
read=60.0, # Allow time for long responses
452
write=30.0, # Reasonable write timeout
453
pool=5.0 # Quick pool timeout
454
)
455
456
# Create client with production settings
457
client = Anthropic(
458
api_key=os.environ.get("ANTHROPIC_API_KEY"),
459
max_retries=5, # More retries in production
460
timeout=timeout,
461
http_client=httpx.Client(
462
limits=limits,
463
timeout=timeout
464
),
465
default_headers={
466
"User-Agent": "MyApp-Production/1.0",
467
"X-Environment": "production"
468
}
469
)
470
471
return client
472
473
# Usage
474
production_client = create_production_client()
475
```
476
477
### Development vs Production Configuration
478
479
```python
480
import os
481
from anthropic import Anthropic
482
483
def create_anthropic_client(environment: str = "development") -> Anthropic:
484
"""Create client configured for different environments"""
485
486
base_config = {
487
"api_key": os.environ.get("ANTHROPIC_API_KEY")
488
}
489
490
if environment == "development":
491
return Anthropic(
492
**base_config,
493
timeout=10.0, # Shorter timeout for dev
494
max_retries=1, # Fewer retries for faster feedback
495
default_headers={
496
"X-Environment": "development",
497
"X-Debug": "true"
498
}
499
)
500
501
elif environment == "staging":
502
return Anthropic(
503
**base_config,
504
timeout=30.0,
505
max_retries=3,
506
default_headers={
507
"X-Environment": "staging"
508
}
509
)
510
511
elif environment == "production":
512
return Anthropic(
513
**base_config,
514
timeout=60.0,
515
max_retries=5,
516
default_headers={
517
"X-Environment": "production",
518
"User-Agent": "MyApp/1.0"
519
}
520
)
521
522
else:
523
raise ValueError(f"Unknown environment: {environment}")
524
525
# Usage
526
env = os.environ.get("APP_ENV", "development")
527
client = create_anthropic_client(env)
528
```
529
530
### Client Connection Pooling
531
532
```python
533
import httpx
534
from anthropic import Anthropic
535
536
# Shared HTTP client for connection pooling across multiple Anthropic instances
537
shared_http_client = httpx.Client(
538
limits=httpx.Limits(
539
max_keepalive_connections=50,
540
max_connections=100
541
),
542
timeout=httpx.Timeout(30.0)
543
)
544
545
# Multiple clients sharing the same connection pool
546
client1 = Anthropic(
547
api_key=os.environ.get("ANTHROPIC_API_KEY_1"),
548
http_client=shared_http_client
549
)
550
551
client2 = Anthropic(
552
api_key=os.environ.get("ANTHROPIC_API_KEY_2"),
553
http_client=shared_http_client
554
)
555
556
# Remember to close the shared client when done
557
try:
558
# Use clients...
559
response1 = client1.messages.create(...)
560
response2 = client2.messages.create(...)
561
finally:
562
shared_http_client.close()
563
```
564
565
### Raw Response Access
566
567
Access raw HTTP responses with headers and status codes for advanced debugging and response processing.
568
569
```python
570
from anthropic import Anthropic
571
572
client = Anthropic()
573
574
# Get raw response with headers and status code
575
raw_response = client.with_raw_response.messages.create(
576
model="claude-sonnet-4-20250514",
577
max_tokens=1024,
578
messages=[{"role": "user", "content": "Hello!"}]
579
)
580
581
# Access response details
582
print(f"Status Code: {raw_response.status_code}")
583
print(f"Headers: {raw_response.headers}")
584
print(f"Content: {raw_response.content}")
585
586
# Parse the response content
587
message = raw_response.parse() # Returns normal Message object
588
```
589
590
### Streaming Response Wrappers
591
592
Access streaming responses with raw response details for advanced stream processing.
593
594
```python
595
# Streaming with raw response access
596
with client.with_streaming_response.messages.create(
597
model="claude-sonnet-4-20250514",
598
max_tokens=1024,
599
messages=[{"role": "user", "content": "Write a story"}],
600
stream=True
601
) as stream_response:
602
603
# Access stream metadata
604
print(f"Status: {stream_response.status_code}")
605
print(f"Headers: {stream_response.headers}")
606
607
# Process streaming content
608
for chunk in stream_response.iter_lines():
609
if chunk:
610
print(chunk)
611
612
# Async streaming with raw response access
613
async with client.with_streaming_response.messages.create(
614
model="claude-sonnet-4-20250514",
615
max_tokens=1024,
616
messages=[{"role": "user", "content": "Write a story"}],
617
stream=True
618
) as async_stream_response:
619
620
async for chunk in async_stream_response.iter_lines():
621
if chunk:
622
print(chunk)
623
```