- Spec files
pypi-anthropic
Describes: pkg:pypi/anthropic@0.66.x
- Description
- The official Python library for the anthropic API
- Author
- tessl
- Last updated
configuration.md docs/
1# Configuration and Utilities23Client 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.45## Capabilities67### Client Configuration89Comprehensive configuration options for customizing client behavior, HTTP settings, and request handling.1011```python { .api }12class Anthropic:13def __init__(14self,15*,16api_key: Optional[str] = None,17base_url: Optional[str] = None,18timeout: Optional[Timeout] = None,19max_retries: Optional[int] = None,20default_headers: Optional[Mapping[str, str]] = None,21default_query: Optional[Mapping[str, object]] = None,22http_client: Optional[httpx.Client] = None,23**kwargs24): ...2526class AsyncAnthropic:27def __init__(28self,29*,30api_key: Optional[str] = None,31base_url: Optional[str] = None,32timeout: Optional[Timeout] = None,33max_retries: Optional[int] = None,34default_headers: Optional[Mapping[str, str]] = None,35default_query: Optional[Mapping[str, object]] = None,36http_client: Optional[httpx.AsyncClient] = None,37**kwargs38): ...3940@property41def with_raw_response(self) -> AnthropicWithRawResponse: ...4243@property44def with_streaming_response(self) -> AnthropicWithStreamedResponse: ...45```4647### HTTP Client Options4849Default HTTP client implementations with different backends and customization options.5051```python { .api }52class DefaultHttpxClient:53"""Default synchronous HTTP client using httpx"""54def __init__(55self,56*,57limits: Optional[httpx.Limits] = None,58timeout: Optional[httpx.Timeout] = None,59proxies: Optional[httpx._types.ProxiesTypes] = None,60**kwargs61): ...6263class DefaultAsyncHttpxClient:64"""Default asynchronous HTTP client using httpx"""65def __init__(66self,67*,68limits: Optional[httpx.Limits] = None,69timeout: Optional[httpx.Timeout] = None,70proxies: Optional[httpx._types.ProxiesTypes] = None,71**kwargs72): ...7374class DefaultAioHttpClient:75"""Alternative async HTTP client using aiohttp"""76def __init__(77self,78*,79timeout: Optional[aiohttp.ClientTimeout] = None,80connector: Optional[aiohttp.BaseConnector] = None,81**kwargs82): ...83```8485### Request Configuration Types8687Types for configuring individual requests and global client settings.8889```python { .api }90class RequestOptions(TypedDict, total=False):91headers: Optional[Mapping[str, str]]92max_retries: Optional[int]93timeout: Optional[Timeout]94params: Optional[Mapping[str, object]]95extra_json: Optional[Mapping[str, object]]9697class Timeout:98"""Timeout configuration for requests"""99def __init__(100self,101total: Optional[float] = None,102*,103connect: Optional[float] = None,104read: Optional[float] = None,105write: Optional[float] = None,106pool: Optional[float] = None107): ...108109class Transport:110"""HTTP transport configuration"""111pass112113class ProxiesTypes:114"""Proxy configuration types"""115pass116```117118### Utility Functions119120Helper functions for file handling and request preparation.121122```python { .api }123def file_from_path(path: Union[str, Path]) -> Any:124"""Create file object from file path for uploads"""125...126```127128### Constants129130Default configuration values and SDK constants.131132```python { .api }133DEFAULT_TIMEOUT: float134DEFAULT_MAX_RETRIES: int135DEFAULT_CONNECTION_LIMITS: httpx.Limits136137HUMAN_PROMPT: str # Legacy prompt marker138AI_PROMPT: str # Legacy prompt marker139```140141## Usage Examples142143### Basic Client Configuration144145```python146import os147from anthropic import Anthropic148149# Basic configuration with API key150client = Anthropic(151api_key=os.environ.get("ANTHROPIC_API_KEY")152)153154# Configuration with custom base URL155client = Anthropic(156api_key=os.environ.get("ANTHROPIC_API_KEY"),157base_url="https://api.anthropic.com/v1" # Custom endpoint158)159160# Configuration with timeout settings161client = Anthropic(162api_key=os.environ.get("ANTHROPIC_API_KEY"),163timeout=30.0 # 30 second timeout164)165```166167### Advanced Timeout Configuration168169```python170from anthropic import Anthropic, Timeout171import httpx172173# Detailed timeout configuration174timeout_config = Timeout(175total=60.0, # Total request timeout176connect=10.0, # Connection timeout177read=30.0, # Read timeout178write=30.0, # Write timeout179pool=5.0 # Pool timeout180)181182client = Anthropic(183api_key=os.environ.get("ANTHROPIC_API_KEY"),184timeout=timeout_config185)186187# Using httpx.Timeout directly188httpx_timeout = httpx.Timeout(189timeout=45.0,190connect=5.0,191read=20.0,192write=20.0,193pool=2.0194)195196client = Anthropic(197api_key=os.environ.get("ANTHROPIC_API_KEY"),198timeout=httpx_timeout199)200```201202### Retry Configuration203204```python205# Configure retry behavior206client = Anthropic(207api_key=os.environ.get("ANTHROPIC_API_KEY"),208max_retries=5 # Retry up to 5 times on failure209)210211# Disable retries212client = Anthropic(213api_key=os.environ.get("ANTHROPIC_API_KEY"),214max_retries=0215)216217# Per-request retry override218message = client.messages.create(219model="claude-sonnet-4-20250514",220max_tokens=1024,221messages=[{"role": "user", "content": "Hello!"}],222extra_options={"max_retries": 2} # Override global retry setting223)224```225226### Custom Headers and Authentication227228```python229# Add custom headers230client = Anthropic(231api_key=os.environ.get("ANTHROPIC_API_KEY"),232default_headers={233"User-Agent": "MyApp/1.0",234"X-Custom-Header": "custom-value"235}236)237238# Per-request headers239message = client.messages.create(240model="claude-sonnet-4-20250514",241max_tokens=1024,242messages=[{"role": "user", "content": "Hello!"}],243extra_options={244"headers": {245"X-Request-ID": "req-12345",246"X-User-ID": "user-67890"247}248}249)250```251252### HTTP Client Customization253254```python255import httpx256from anthropic import Anthropic, DefaultHttpxClient257258# Custom HTTP client with connection limits259custom_limits = httpx.Limits(260max_keepalive_connections=10,261max_connections=20,262keepalive_expiry=30.0263)264265http_client = DefaultHttpxClient(266limits=custom_limits,267timeout=httpx.Timeout(30.0)268)269270client = Anthropic(271api_key=os.environ.get("ANTHROPIC_API_KEY"),272http_client=http_client273)274275# Using custom httpx client directly276custom_httpx_client = httpx.Client(277limits=httpx.Limits(max_connections=50),278timeout=httpx.Timeout(45.0),279headers={"User-Agent": "MyCustomApp/2.0"}280)281282client = Anthropic(283api_key=os.environ.get("ANTHROPIC_API_KEY"),284http_client=custom_httpx_client285)286```287288### Proxy Configuration289290```python291import httpx292from anthropic import Anthropic293294# HTTP proxy295proxies = {296"http://": "http://proxy.example.com:8080",297"https://": "https://proxy.example.com:8080"298}299300client = Anthropic(301api_key=os.environ.get("ANTHROPIC_API_KEY"),302http_client=httpx.Client(proxies=proxies)303)304305# SOCKS proxy306client = Anthropic(307api_key=os.environ.get("ANTHROPIC_API_KEY"),308http_client=httpx.Client(309proxies="socks5://proxy.example.com:1080"310)311)312313# Proxy with authentication314proxy_with_auth = "http://user:pass@proxy.example.com:8080"315client = Anthropic(316api_key=os.environ.get("ANTHROPIC_API_KEY"),317http_client=httpx.Client(proxies=proxy_with_auth)318)319```320321### Async Client Configuration322323```python324import asyncio325import httpx326from anthropic import AsyncAnthropic, DefaultAsyncHttpxClient, DefaultAioHttpClient327328# Basic async client329async_client = AsyncAnthropic(330api_key=os.environ.get("ANTHROPIC_API_KEY")331)332333# Custom async httpx client334custom_async_client = DefaultAsyncHttpxClient(335limits=httpx.Limits(max_connections=25),336timeout=httpx.Timeout(60.0)337)338339async_client = AsyncAnthropic(340api_key=os.environ.get("ANTHROPIC_API_KEY"),341http_client=custom_async_client342)343344# Using aiohttp backend for better async performance345aiohttp_client = DefaultAioHttpClient(346timeout=aiohttp.ClientTimeout(total=60)347)348349async_client = AsyncAnthropic(350api_key=os.environ.get("ANTHROPIC_API_KEY"),351http_client=aiohttp_client352)353```354355### Environment-based Configuration356357```python358import os359from anthropic import Anthropic360361class AnthropicConfig:362"""Configuration management for Anthropic client"""363364def __init__(self):365self.api_key = os.environ.get("ANTHROPIC_API_KEY")366self.base_url = os.environ.get("ANTHROPIC_BASE_URL", "https://api.anthropic.com")367self.timeout = float(os.environ.get("ANTHROPIC_TIMEOUT", "30"))368self.max_retries = int(os.environ.get("ANTHROPIC_MAX_RETRIES", "3"))369self.proxy = os.environ.get("HTTP_PROXY")370371def create_client(self) -> Anthropic:372"""Create configured Anthropic client"""373374# Build HTTP client with proxy if specified375http_client = None376if self.proxy:377http_client = httpx.Client(proxies=self.proxy)378379return Anthropic(380api_key=self.api_key,381base_url=self.base_url,382timeout=self.timeout,383max_retries=self.max_retries,384http_client=http_client385)386387# Usage with environment variables388config = AnthropicConfig()389client = config.create_client()390```391392### File Utilities393394```python395from anthropic import file_from_path396from pathlib import Path397398# Create file object for upload399image_file = file_from_path("./image.jpg")400document_file = file_from_path(Path("./document.pdf"))401402# Use in message with image403message = client.messages.create(404model="claude-sonnet-4-20250514",405max_tokens=1024,406messages=[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 result416}417},418{419"type": "text",420"text": "What's in this image?"421}422]423}424]425)426```427428### Production Configuration429430```python431import logging432from anthropic import Anthropic433import httpx434435def create_production_client() -> Anthropic:436"""Create a production-ready Anthropic client"""437438# Configure logging439logging.basicConfig(level=logging.INFO)440441# Production HTTP client settings442limits = httpx.Limits(443max_keepalive_connections=20, # Keep connections alive444max_connections=100, # Allow more concurrent connections445keepalive_expiry=60.0 # Keep connections for 60 seconds446)447448timeout = httpx.Timeout(449total=120.0, # Allow longer requests in production450connect=10.0, # Quick connection timeout451read=60.0, # Allow time for long responses452write=30.0, # Reasonable write timeout453pool=5.0 # Quick pool timeout454)455456# Create client with production settings457client = Anthropic(458api_key=os.environ.get("ANTHROPIC_API_KEY"),459max_retries=5, # More retries in production460timeout=timeout,461http_client=httpx.Client(462limits=limits,463timeout=timeout464),465default_headers={466"User-Agent": "MyApp-Production/1.0",467"X-Environment": "production"468}469)470471return client472473# Usage474production_client = create_production_client()475```476477### Development vs Production Configuration478479```python480import os481from anthropic import Anthropic482483def create_anthropic_client(environment: str = "development") -> Anthropic:484"""Create client configured for different environments"""485486base_config = {487"api_key": os.environ.get("ANTHROPIC_API_KEY")488}489490if environment == "development":491return Anthropic(492**base_config,493timeout=10.0, # Shorter timeout for dev494max_retries=1, # Fewer retries for faster feedback495default_headers={496"X-Environment": "development",497"X-Debug": "true"498}499)500501elif environment == "staging":502return Anthropic(503**base_config,504timeout=30.0,505max_retries=3,506default_headers={507"X-Environment": "staging"508}509)510511elif environment == "production":512return Anthropic(513**base_config,514timeout=60.0,515max_retries=5,516default_headers={517"X-Environment": "production",518"User-Agent": "MyApp/1.0"519}520)521522else:523raise ValueError(f"Unknown environment: {environment}")524525# Usage526env = os.environ.get("APP_ENV", "development")527client = create_anthropic_client(env)528```529530### Client Connection Pooling531532```python533import httpx534from anthropic import Anthropic535536# Shared HTTP client for connection pooling across multiple Anthropic instances537shared_http_client = httpx.Client(538limits=httpx.Limits(539max_keepalive_connections=50,540max_connections=100541),542timeout=httpx.Timeout(30.0)543)544545# Multiple clients sharing the same connection pool546client1 = Anthropic(547api_key=os.environ.get("ANTHROPIC_API_KEY_1"),548http_client=shared_http_client549)550551client2 = Anthropic(552api_key=os.environ.get("ANTHROPIC_API_KEY_2"),553http_client=shared_http_client554)555556# Remember to close the shared client when done557try:558# Use clients...559response1 = client1.messages.create(...)560response2 = client2.messages.create(...)561finally:562shared_http_client.close()563```564565### Raw Response Access566567Access raw HTTP responses with headers and status codes for advanced debugging and response processing.568569```python570from anthropic import Anthropic571572client = Anthropic()573574# Get raw response with headers and status code575raw_response = client.with_raw_response.messages.create(576model="claude-sonnet-4-20250514",577max_tokens=1024,578messages=[{"role": "user", "content": "Hello!"}]579)580581# Access response details582print(f"Status Code: {raw_response.status_code}")583print(f"Headers: {raw_response.headers}")584print(f"Content: {raw_response.content}")585586# Parse the response content587message = raw_response.parse() # Returns normal Message object588```589590### Streaming Response Wrappers591592Access streaming responses with raw response details for advanced stream processing.593594```python595# Streaming with raw response access596with client.with_streaming_response.messages.create(597model="claude-sonnet-4-20250514",598max_tokens=1024,599messages=[{"role": "user", "content": "Write a story"}],600stream=True601) as stream_response:602603# Access stream metadata604print(f"Status: {stream_response.status_code}")605print(f"Headers: {stream_response.headers}")606607# Process streaming content608for chunk in stream_response.iter_lines():609if chunk:610print(chunk)611612# Async streaming with raw response access613async with client.with_streaming_response.messages.create(614model="claude-sonnet-4-20250514",615max_tokens=1024,616messages=[{"role": "user", "content": "Write a story"}],617stream=True618) as async_stream_response:619620async for chunk in async_stream_response.iter_lines():621if chunk:622print(chunk)623```