Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Implementation:Anthropics Anthropic sdk python Anthropic Client Init

From Leeroopedia
Knowledge Sources
Domains API_Client, LLM
Last Updated 2026-02-15 00:00 GMT

Overview

This page documents the Anthropic.__init__ constructor and its async counterpart AsyncAnthropic.__init__. These constructors create a fully configured HTTP client instance that serves as the entry point for all Anthropic API interactions.

API Signature

class Anthropic(SyncAPIClient):
    def __init__(
        self,
        *,
        api_key: str | None = None,
        auth_token: str | None = None,
        base_url: str | httpx.URL | None = None,
        timeout: float | Timeout | None | NotGiven = not_given,
        max_retries: int = DEFAULT_MAX_RETRIES,  # 2
        default_headers: Mapping[str, str] | None = None,
        default_query: Mapping[str, object] | None = None,
        http_client: httpx.Client | None = None,
        _strict_response_validation: bool = False,
    ) -> None

Source Location

  • File: src/anthropic/_client.py
  • Sync class: Anthropic at lines 53-116
  • Async class: AsyncAnthropic at lines 293-356
  • Constants: src/anthropic/_constants.py

Import

from anthropic import Anthropic, AsyncAnthropic

Parameters

Parameter Type Default Description
api_key None Auto-reads ANTHROPIC_API_KEY env var API key for X-Api-Key header authentication
auth_token None Auto-reads ANTHROPIC_AUTH_TOKEN env var Bearer token for Authorization header authentication
base_url httpx.URL | None "https://api.anthropic.com" (falls back to ANTHROPIC_BASE_URL env var) Root URL for all API requests
timeout Timeout | None | NotGiven httpx.Timeout(timeout=600, connect=5.0) Request timeout; 10 minutes total, 5 second connect
max_retries int 2 Number of automatic retries on transient failures
default_headers None None Extra HTTP headers sent with every request
default_query None None Extra query parameters appended to every request URL
http_client None None Custom httpx client for advanced transport configuration

Output

A configured Anthropic instance with the following cached property resource accessors:

  • self.messages -- Returns a Messages resource (lazy-loaded on first access)
  • self.completions -- Returns a Completions resource (lazy-loaded on first access)
  • self.models -- Returns a Models resource (lazy-loaded on first access)
  • self.beta -- Returns a Beta resource (lazy-loaded on first access)

Constructor Logic

# 1. Resolve api_key: explicit arg -> env var -> None
if api_key is None:
    api_key = os.environ.get("ANTHROPIC_API_KEY")
self.api_key = api_key

# 2. Resolve auth_token: explicit arg -> env var -> None
if auth_token is None:
    auth_token = os.environ.get("ANTHROPIC_AUTH_TOKEN")
self.auth_token = auth_token

# 3. Resolve base_url: explicit arg -> env var -> default
if base_url is None:
    base_url = os.environ.get("ANTHROPIC_BASE_URL")
if base_url is None:
    base_url = "https://api.anthropic.com"

# 4. Initialize parent SyncAPIClient with resolved values
super().__init__(
    version=__version__,
    base_url=base_url,
    max_retries=max_retries,
    timeout=timeout,
    http_client=http_client,
    custom_headers=default_headers,
    custom_query=default_query,
    _strict_response_validation=_strict_response_validation,
)

# 5. Set default stream class
self._default_stream_cls = Stream

Authentication Headers

The client generates auth headers dynamically via properties:

@property
def auth_headers(self) -> dict[str, str]:
    return {**self._api_key_auth, **self._bearer_auth}

@property
def _api_key_auth(self) -> dict[str, str]:
    if self.api_key is None:
        return {}
    return {"X-Api-Key": self.api_key}

@property
def _bearer_auth(self) -> dict[str, str]:
    if self.auth_token is None:
        return {}
    return {"Authorization": f"Bearer {self.auth_token}"}

Async Variant

AsyncAnthropic mirrors the same constructor signature but extends AsyncAPIClient and uses httpx.AsyncClient:

from anthropic import AsyncAnthropic

async_client = AsyncAnthropic(api_key="sk-ant-...")

Usage Examples

import anthropic

# Basic -- uses ANTHROPIC_API_KEY env var
client = anthropic.Anthropic()

# Explicit API key
client = anthropic.Anthropic(api_key="sk-ant-...")

# Custom configuration
client = anthropic.Anthropic(
    api_key="sk-ant-...",
    max_retries=3,
    timeout=60.0,
)

# Async client
async_client = anthropic.AsyncAnthropic()

# Override options for a single call chain
response = client.with_options(timeout=120).messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Hello!"}],
)

Dependencies

  • httpx -- HTTP transport layer (httpx.Client, httpx.AsyncClient, httpx.Timeout)
  • os -- Environment variable resolution
  • typing_extensions -- Self, override decorators

Related Pages

Implements Principle

Requires Environment

Uses Heuristic

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment