← Blog

Claude API Python SDK: Async Examples That Work

2026-11-10 · 5 min read · SubToAPI Team

Why you need async for the Claude API

If you're building anything that calls Claude more than once per request — a batch job, a chatbot handling multiple users, a pipeline processing hundreds of documents — synchronous calls will bottleneck you. Each request to Claude takes anywhere from a few hundred milliseconds to several seconds depending on output length, and if you're making those calls one at a time in a for loop, you're paying for that latency serially instead of overlapping it.

The fix is asyncio. Anthropic's official Python SDK ships an async client (AsyncAnthropic) that mirrors the sync one but returns coroutines you can await, gather, or stream. This article walks through the patterns that actually come up in production: concurrent requests, async streaming, retry logic, and rate-limit-aware batching.

Setting up the async client

Install the SDK and use AsyncAnthropic instead of Anthropic:

import asyncio
from anthropic import AsyncAnthropic

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

async def ask(prompt: str) -> str:
    response = await client.messages.create(
        model="claude-3-5-sonnet-20241022",
        max_tokens=1024,
        messages=[{"role": "user", "content": prompt}],
    )
    return response.content[0].text

async def main():
    result = await ask("Summarize the plot of Dune in two sentences.")
    print(result)

asyncio.run(main())

This is identical in shape to the sync version — same method names, same parameters — just with async/await sprinkled in. That's the whole point of the SDK design: you don't relearn the API, you just unlock concurrency.

Running requests concurrently with asyncio.gather

The real payoff shows up when you have multiple independent prompts. Instead of awaiting them one by one, fire them together:

import asyncio
from anthropic import AsyncAnthropic

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

async def summarize(text: str) -> str:
    response = await client.messages.create(
        model="claude-3-5-sonnet-20241022",
        max_tokens=512,
        messages=[{"role": "user", "content": f"Summarize in one sentence: {text}"}],
    )
    return response.content[0].text

async def main():
    documents = ["doc 1 text...", "doc 2 text...", "doc 3 text..."]
    summaries = await asyncio.gather(*(summarize(doc) for doc in documents))
    for s in summaries:
        print(s)

asyncio.run(main())

On a single document this gains you nothing, but across ten or a hundred documents the wall-clock time collapses to roughly the duration of the slowest single call instead of the sum of all of them.

Bounding concurrency with a semaphore

Unbounded concurrency will hit rate limits fast. Wrap your calls with an asyncio.Semaphore to cap how many requests are in flight at once:

import asyncio
from anthropic import AsyncAnthropic

client = AsyncAnthropic(api_key="sk-ant-...")
sem = asyncio.Semaphore(5)  # max 5 concurrent requests

async def bounded_call(prompt: str) -> str:
    async with sem:
        response = await client.messages.create(
            model="claude-3-5-sonnet-20241022",
            max_tokens=512,
            messages=[{"role": "user", "content": prompt}],
        )
        return response.content[0].text

async def main():
    prompts = [f"Write a haiku about topic {i}" for i in range(30)]
    results = await asyncio.gather(*(bounded_call(p) for p in prompts))
    print(len(results), "responses received")

asyncio.run(main())

This pattern — Semaphore(N) plus gather — is the standard shape for any batch job against an LLM API, Claude included.

Async streaming

For chat UIs or anything where you want tokens as they're generated, use the async streaming context manager:

import asyncio
from anthropic import AsyncAnthropic

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

async def stream_response(prompt: str):
    async with client.messages.stream(
        model="claude-3-5-sonnet-20241022",
        max_tokens=1024,
        messages=[{"role": "user", "content": prompt}],
    ) as stream:
        async for text in stream.text_stream:
            print(text, end="", flush=True)
        final = await stream.get_final_message()
        print("\n\n---\nUsage:", final.usage)

asyncio.run(stream_response("Explain async/await in Python like I'm new to it."))

The async for over stream.text_stream yields text deltas as they arrive, and get_final_message() gives you the complete Message object afterward, including token usage.

Retrying on transient errors

Network blips and rate limits happen. A simple exponential backoff wrapper keeps your batch jobs resilient:

import asyncio
import random
from anthropic import AsyncAnthropic, RateLimitError, APIConnectionError

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

async def call_with_retry(prompt: str, max_attempts: int = 5) -> str:
    for attempt in range(max_attempts):
        try:
            response = await client.messages.create(
                model="claude-3-5-sonnet-20241022",
                max_tokens=512,
                messages=[{"role": "user", "content": prompt}],
            )
            return response.content[0].text
        except (RateLimitError, APIConnectionError):
            if attempt == max_attempts - 1:
                raise
            delay = (2 ** attempt) + random.random()
            await asyncio.sleep(delay)

Catch the specific exception classes rather than a bare except Exception — you want real errors (bad prompts, auth failures) to surface immediately, not get silently retried.

When a proxy layer simplifies this further

Writing your own semaphore, retry, and streaming logic is reasonable when you're calling Anthropic's API directly with a key tied to one developer account. It gets more complicated once you need per-application API keys, team-level usage visibility, or a stable endpoint that multiple services hit without sharing credentials.

That's the gap SubToAPI fills: it exposes your existing Claude access as a standard HTTPS API with sub_live_... keys you can issue per app, plus streaming, tool use, and usage metadata built in. Your async Python code barely changes — same httpx.AsyncClient or SDK pattern, just pointed at a different base URL with a different key:

import httpx
import asyncio

async def ask_subtoapi(prompt: str) -> str:
    async with httpx.AsyncClient() as client:
        response = await client.post(
            "https://api.subtoapi.app/v1/messages",
            headers={"Authorization": "Bearer sub_live_..."},
            json={
                "model": "claude-3-5-sonnet-20241022",
                "max_tokens": 512,
                "messages": [{"role": "user", "content": prompt}],
            },
        )
        return response.json()

asyncio.run(ask_subtoapi("Hello, Claude"))

See /docs/quickstart and /docs/messages for the full request/response reference, and /docs/streaming if you want the async streaming version. Plans start at /pricing, with a free trial at /signup.

A minimal async batch processor

Putting it together — a reusable function that processes a list of prompts with bounded concurrency and retries:

import asyncio
from anthropic import AsyncAnthropic

client = AsyncAnthropic(api_key="sk-ant-...")
sem = asyncio.Semaphore(8)

async def process_one(prompt: str) -> str:
    async with sem:
        try:
            response = await client.messages.create(
                model="claude-3-5-sonnet-20241022",
                max_tokens=512,
                messages=[{"role": "user", "content": prompt}],
            )
            return response.content[0].text
        except Exception as e:
            return f"ERROR: {e}"

async def process_batch(prompts: list[str]) -> list[str]:
    return await asyncio.gather(*(process_one(p) for p in prompts))

This shape scales from 10 prompts to 10,000 — just adjust the semaphore limit to match your rate limit tier.

questions

Does Anthropic's Python SDK support async natively, or do I need a separate library? It's native. Import AsyncAnthropic from the same anthropic package you already use for the sync Anthropic client — no extra dependency required.

How many concurrent Claude API requests can I safely run? It depends on your account's rate limit tier. Start with a semaphore of 5-10 concurrent requests, watch for RateLimitError responses, and tune the number up or down based on how often you hit limits.

Can I mix async Claude calls with other async I/O, like database queries? Yes — that's the main benefit of using AsyncAnthropic instead of threads. You can await Claude calls alongside asyncpg, httpx, or any other async library in the same event loop without blocking.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →