- Spec files
pypi-anthropic
Describes: pkg:pypi/anthropic@0.66.x
- Description
- The official Python library for the anthropic API
- Author
- tessl
- Last updated
index.md docs/
1# Anthropic Python SDK23The official Python library for the Anthropic API, providing convenient access to Claude AI models. This library offers both synchronous and asynchronous clients with comprehensive type definitions, streaming responses, message batching, tool use capabilities, and specialized integrations for AWS Bedrock and Google Vertex AI.45## Package Information67- **Package Name**: anthropic8- **Language**: Python9- **Installation**: `pip install anthropic`10- **Optional Dependencies**: `pip install anthropic[aiohttp]` for aiohttp support, `pip install anthropic[bedrock]` for AWS Bedrock, `pip install anthropic[vertex]` for Google Vertex AI1112## Core Imports1314```python15from anthropic import Anthropic, AsyncAnthropic16```1718For specialized integrations:1920```python21from anthropic import AnthropicBedrock, AsyncAnthropicBedrock22from anthropic import AnthropicVertex, AsyncAnthropicVertex23```2425## Basic Usage2627### Synchronous Client2829```python30import os31from anthropic import Anthropic3233client = Anthropic(34api_key=os.environ.get("ANTHROPIC_API_KEY"),35)3637message = client.messages.create(38max_tokens=1024,39messages=[40{41"role": "user",42"content": "Hello, Claude",43}44],45model="claude-sonnet-4-20250514",46)47print(message.content)48```4950### Asynchronous Client5152```python53import os54import asyncio55from anthropic import AsyncAnthropic5657client = AsyncAnthropic(58api_key=os.environ.get("ANTHROPIC_API_KEY"),59)6061async def main():62message = await client.messages.create(63max_tokens=1024,64messages=[65{66"role": "user",67"content": "Hello, Claude",68}69],70model="claude-sonnet-4-20250514",71)72print(message.content)7374asyncio.run(main())75```7677## Architecture7879The SDK follows a resource-based API design pattern:8081- **Client**: Main entry point (`Anthropic`, `AsyncAnthropic`) that manages authentication and HTTP configuration82- **Resources**: API endpoints organized by functionality (`messages`, `completions`, `models`, `beta`)83- **Types**: Comprehensive Pydantic models for all request parameters and response objects84- **Streaming**: Real-time response processing with event-based message streaming85- **Integrations**: Specialized clients for cloud platforms (Bedrock, Vertex AI)8687## Capabilities8889### Messages API9091Core conversational interface for interacting with Claude models, supporting multi-turn conversations, system prompts, tool use, streaming responses, and message batching.9293```python { .api }94def create(95max_tokens: int,96messages: List[MessageParam],97model: str,98*,99metadata: Optional[MetadataParam] = None,100service_tier: Optional[Literal["auto", "standard_only"]] = None,101stop_sequences: Optional[List[str]] = None,102stream: Optional[bool] = None,103system: Optional[str] = None,104temperature: Optional[float] = None,105thinking: Optional[ThinkingConfigParam] = None,106tool_choice: Optional[ToolChoiceParam] = None,107tools: Optional[List[ToolParam]] = None,108top_k: Optional[int] = None,109top_p: Optional[float] = None,110**kwargs111) -> Message: ...112113async def create(114max_tokens: int,115messages: List[MessageParam],116model: str,117*,118metadata: Optional[MetadataParam] = None,119service_tier: Optional[Literal["auto", "standard_only"]] = None,120stop_sequences: Optional[List[str]] = None,121stream: Optional[bool] = None,122system: Optional[str] = None,123temperature: Optional[float] = None,124thinking: Optional[ThinkingConfigParam] = None,125tool_choice: Optional[ToolChoiceParam] = None,126tools: Optional[List[ToolParam]] = None,127top_k: Optional[int] = None,128top_p: Optional[float] = None,129**kwargs130) -> Message: ...131132def count_tokens(133messages: List[MessageParam],134model: str,135*,136system: Optional[str] = None,137tool_choice: Optional[ToolChoiceParam] = None,138tools: Optional[List[ToolParam]] = None,139**kwargs140) -> MessageTokensCount: ...141```142143[Messages API](./messages.md)144145### Text Completions API146147Direct text completion interface for generating text from prompts, primarily used for specific use cases requiring the legacy completion format.148149```python { .api }150def create(151max_tokens_to_sample: int,152model: str,153prompt: str,154*,155metadata: Optional[MetadataParam] = None,156stop_sequences: Optional[List[str]] = None,157stream: Optional[bool] = None,158temperature: Optional[float] = None,159top_k: Optional[int] = None,160top_p: Optional[float] = None,161**kwargs162) -> Completion: ...163```164165[Text Completions](./completions.md)166167### Streaming Interface168169Real-time message streaming with event handlers for processing partial responses, tool use events, and completion updates as they arrive.170171```python { .api }172class MessageStream:173def __enter__(self) -> MessageStream: ...174def __exit__(self, exc_type, exc_val, exc_tb) -> None: ...175def __iter__(self) -> Iterator[MessageStreamEvent]: ...176177def on_text(self, handler: Callable[[TextEvent], None]) -> MessageStream: ...178def on_input_json(self, handler: Callable[[InputJsonEvent], None]) -> MessageStream: ...179def on_message_stop(self, handler: Callable[[MessageStopEvent], None]) -> MessageStream: ...180def get_final_message(self) -> Message: ...181182class AsyncMessageStream:183async def __aenter__(self) -> AsyncMessageStream: ...184async def __aexit__(self, exc_type, exc_val, exc_tb) -> None: ...185def __aiter__(self) -> AsyncIterator[MessageStreamEvent]: ...186187def on_text(self, handler: Callable[[TextEvent], Awaitable[None]]) -> AsyncMessageStream: ...188def on_input_json(self, handler: Callable[[InputJsonEvent], Awaitable[None]]) -> AsyncMessageStream: ...189def on_message_stop(self, handler: Callable[[MessageStopEvent], Awaitable[None]]) -> AsyncMessageStream: ...190async def get_final_message(self) -> Message: ...191```192193[Streaming](./streaming.md)194195### Models API196197Access to available Claude models, including model information, capabilities, and metadata for selecting appropriate models for different use cases.198199```python { .api }200def list(**kwargs) -> List[Model]: ...201async def list(**kwargs) -> List[Model]: ...202```203204[Models API](./models.md)205206### Tool Use (Function Calling)207208Integration system for connecting Claude with external functions and APIs, enabling Claude to use tools, call functions, and interact with external systems.209210```python { .api }211class ToolParam(TypedDict):212name: str213description: str214input_schema: Dict[str, Any]215216class ToolChoiceParam(TypedDict, total=False):217type: Literal["auto", "any", "none", "tool"]218name: Optional[str]219220class ToolUseBlock(TypedDict):221type: Literal["tool_use"]222id: str223name: str224input: Dict[str, Any]225226class ToolResultBlockParam(TypedDict):227type: Literal["tool_result"]228tool_use_id: str229content: Union[str, List[ContentBlockParam]]230is_error: Optional[bool]231```232233[Tool Use](./tools.md)234235### Message Batching236237Efficient processing of multiple message requests in batches, providing cost optimization and throughput improvements for high-volume applications.238239```python { .api }240def create(241requests: List[Dict[str, Any]],242**kwargs243) -> Any: ...244245def retrieve(batch_id: str, **kwargs) -> Any: ...246def list(**kwargs) -> Any: ...247def cancel(batch_id: str, **kwargs) -> Any: ...248```249250[Message Batching](./batching.md)251252### Beta Features253254Experimental and preview features including advanced capabilities, new model features, and cutting-edge functionality.255256```python { .api }257class Beta:258messages: BetaMessages259models: BetaModels260files: BetaFiles261262class AsyncBeta:263messages: AsyncBetaMessages264models: AsyncBetaModels265files: AsyncBetaFiles266```267268[Beta Features](./beta.md)269270### AWS Bedrock Integration271272Specialized client for accessing Claude models through Amazon Bedrock, with AWS authentication and Bedrock-specific configurations.273274```python { .api }275class AnthropicBedrock:276def __init__(277self,278*,279aws_access_key: Optional[str] = None,280aws_secret_key: Optional[str] = None,281aws_session_token: Optional[str] = None,282aws_region: Optional[str] = None,283**kwargs284): ...285286messages: Messages287completions: Completions288289class AsyncAnthropicBedrock:290def __init__(291self,292*,293aws_access_key: Optional[str] = None,294aws_secret_key: Optional[str] = None,295aws_session_token: Optional[str] = None,296aws_region: Optional[str] = None,297**kwargs298): ...299300messages: AsyncMessages301completions: AsyncCompletions302```303304[AWS Bedrock](./bedrock.md)305306### Google Vertex AI Integration307308Specialized client for accessing Claude models through Google Cloud Vertex AI, with Google Cloud authentication and Vertex-specific configurations.309310```python { .api }311class AnthropicVertex:312def __init__(313self,314*,315project_id: Optional[str] = None,316region: Optional[str] = None,317**kwargs318): ...319320messages: Messages321completions: Completions322323class AsyncAnthropicVertex:324def __init__(325self,326*,327project_id: Optional[str] = None,328region: Optional[str] = None,329**kwargs330): ...331332messages: AsyncMessages333completions: AsyncCompletions334```335336[Google Vertex AI](./vertex.md)337338### Error Handling339340Comprehensive exception hierarchy for handling API errors, network issues, authentication problems, and service-specific errors.341342```python { .api }343class AnthropicError(Exception): ...344class APIError(AnthropicError): ...345class APIStatusError(APIError): ...346class APITimeoutError(APIError): ...347class APIConnectionError(APIError): ...348class APIResponseValidationError(APIError): ...349350class BadRequestError(APIStatusError): ...351class AuthenticationError(APIStatusError): ...352class PermissionDeniedError(APIStatusError): ...353class NotFoundError(APIStatusError): ...354class ConflictError(APIStatusError): ...355class UnprocessableEntityError(APIStatusError): ...356class RateLimitError(APIStatusError): ...357class InternalServerError(APIStatusError): ...358```359360[Error Handling](./errors.md)361362### Configuration and Utilities363364Client configuration options, HTTP settings, timeout management, retry policies, and utility functions for file handling and request customization.365366```python { .api }367class Anthropic:368def __init__(369self,370*,371api_key: Optional[str] = None,372base_url: Optional[str] = None,373timeout: Optional[Timeout] = None,374max_retries: Optional[int] = None,375default_headers: Optional[Mapping[str, str]] = None,376default_query: Optional[Mapping[str, object]] = None,377http_client: Optional[httpx.Client] = None,378**kwargs379): ...380381@property382def with_raw_response(self) -> AnthropicWithRawResponse: ...383384@property385def with_streaming_response(self) -> AnthropicWithStreamedResponse: ...386387def file_from_path(path: Union[str, Path]) -> Any: ...388```389390[Configuration](./configuration.md)