Anthropic Python SDK

repository·main·Indexed 26 days ago

https://github.com/anthropics/anthropic-sdk-python

The official Python library for the anthropic API, providing a programmatic interface to interact with Claude models. It includes support for the Messages API, Message Batches, and Model information, as well as a specialized AnthropicGoogleCloud client for Google Cloud Platform integration using IAM credentials. The SDK also provides access to beta features for agents, environments, and experimental message capabilities. Requires Python 3.9 or higher.

Tokens
16.9K
Snippets
30
Records
88
Agent score
86%

What's inside anthropic-sdk-python

  1. Run a managed agent's tools locally with EnvironmentWorker

    main

    To run tools for a managed agent in a self-hosted environment, use client.beta.environments.work.worker(...) (which returns an EnvironmentWorker). This worker polls the environment for work, sets up a workdir, downloads agent skills, and executes tools in response to agent.tool_use or agent.custom_tool_use events.

    Key features:

    • Polling: Use .run() to start a loop that polls for work.
    • Single Item: Use .handle_item(...) to process a specific work item already claimed.
    • Environment Variables: If no arguments are passed to handle_item(), it reads ANTHROPIC_WORK_ID, ANTHROPIC_ENVIRONMENT_ID, ANTHROPIC_SESSION_ID, and ANTHROPIC_ENVIRONMENT_KEY from the environment.
    • Async Only: This is built on anyio and works with asyncio or trio.
    import os, asyncio
    from anthropic import AsyncAnthropic
    from anthropic.lib.tools import beta_async_tool
    from anthropic.lib.tools.agent_toolset import beta_agent_toolset_20260401
    
    client = AsyncAnthropic()
    
    @beta_async_tool
    async def deploy(target: str) -> str:
        ...
    
    # Start a worker that loops forever
    await client.beta.environments.work.worker(
        environment_id=os.environ["ANTHROPIC_ENVIRONMENT_ID"],
        environment_key=os.environ["ANTHROPIC_ENVIRONMENT_KEY"],
        workdir="/workspace",
        # Use a factory to bind the toolset to the session's AgentToolContext
        tools=lambda env: [*beta_agent_toolset_20260401(env), deploy],
    ).run()
  2. Integrate MCP servers using Anthropic MCP helpers

    main

    The SDK provides helpers to convert Model Context Protocol (MCP) types to Anthropic API types. This is useful for local MCP servers.

    Requirement: pip install anthropic[mcp] (Python 3.10+)

    When to use MCP helpers vs mcp_servers parameter:

    • Use mcp_servers for remote servers accessible via URL (tool support only).
    • Use MCP helpers for local servers, or when you need access to MCP prompts, resources, or more granular connection control.
  3. Stream messages using client.messages.stream()

    main

    Use client.messages.stream() as an asynchronous context manager to receive a MessageStream. This stream allows you to iterate over events, use lenses like .text_stream for easy text access, and accumulate the final message object.

    Note: The synchronous client provides the same interface without async/await. The stream is cancelled when the context manager exits, but you can call stream.close() to abort early.

    async with client.messages.stream(
        max_tokens=1024,
        messages=[
            {
                "role": "user",
                "content": "Say hello there!",
            }
        ],
        model="claude-sonnet-5",
    ) as stream:
        async for text in stream.text_stream:
            print(text, end="", flush=True)
        print()
  4. Get started with the Anthropic Python SDK

    main

    To use the SDK, import the Anthropic class and initialize a client. By default, the client looks for an API key in the ANTHROPIC_API_KEY environment variable, so you can omit the api_key argument if it is set. Use client.messages.create to send messages to Claude models.

    import os
    from anthropic import Anthropic
    
    client = Anthropic(
        api_key=os.environ.get("ANTHROPIC_API_KEY"),  # This is the default and can be omitted
    )
    
    message = client.messages.create(
        max_tokens=1024,
        messages=[
            {
                "role": "user",
                "content": "Hello, Claude",
            }
        ],
    
        model="claude-opus-4-6",
    )
    
    print(message.content)
  5. Define tools using the @beta_tool decorator

    main

    You can define tools for Claude by using the @beta_tool decorator on a Python function. The decorator automatically inspects the function's arguments and docstring to generate a JSON schema for the tool's input_schema.

    If you are using an asynchronous client, use the @beta_async_tool decorator and define your function with async def instead.

    from anthropic import beta_tool
    
    @beta_tool
    def sum(left: int, right: int) -> str:
        """Adds two integers together.
        Args:
            left (int): The first integer to add.
            right (int): The second integer to add.
        Returns:
            int: The sum of left and right integers.
        """
        return str(left + right)
  6. Authenticate with AnthropicGoogleCloud

    main

    The AnthropicGoogleCloud client authenticates using Google Cloud IAM credentials. It does not use ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, or ANTHROPIC_BASE_URL.

    Authentication follows this precedence (first match wins, unless skip_auth=True):

    1. token_provider: A callable returning a GCP access token (invoked on every request).
    2. credentials: A google.auth.Credentials object.
    3. Application Default Credentials (ADC): Discovered via google.auth.default() (e.g., via gcloud auth application-default login or GOOGLE_APPLICATION_CREDENTIALS).

    A workspace_id is required unless skip_auth=True is used with an explicit base_url.

  7. Configure AnthropicGoogleCloud client

    main

    The following configuration options can be passed to the client constructor or set via environment variables:

    ArgumentEnvironment variableNotes
    projectANTHROPIC_GOOGLE_CLOUD_PROJECTOnly needed when the base URL is derived; if omitted, back-filled from Google credentials on the first request.
    locationRequired only when deriving the base URL.
    workspace_idANTHROPIC_GOOGLE_CLOUD_WORKSPACE_IDRequired unless skip_auth=True with an explicit base_url.
    base_urlANTHROPIC_GOOGLE_CLOUD_BASE_URLOverrides the derived gateway URL.
    skip_authFor pre-authenticated proxies: skips token attachment and the workspace requirement.
  8. Initialize AnthropicFoundry client

    main

    Use AnthropicFoundry (synchronous) or AsyncAnthropicFoundry (asynchronous) to connect to the Claude Platform on Google Cloud/Azure.

    Authentication can be provided via an api_key or an azure_ad_token_provider (a callable returning a string or an awaitable returning a string). These two methods are mutually exclusive.

    If arguments are not provided, the client automatically infers them from the following environment variables:

    • api_key from ANTHROPIC_FOUNDRY_API_KEY
    • resource from ANTHROPIC_FOUNDRY_RESOURCE
    • base_url from ANTHROPIC_FOUNDRY_BASE_URL
  9. Security warning for the bash tool

    main

    The bash tool executes an unrestricted /bin/bash directly on the host. Unlike the file tools (read, write, edit, glob, grep) which are confined to the workdir, bash is not sandboxed.

    Best Practices:

    • Run the worker inside a container or another isolation boundary.
    • To control the subprocess environment for bash, pass an AgentToolContext(env=...).