๐Ÿ“ LLM & AI

AsyncAnthropic: Async Client for the Claude API

P
Author
PyLand Team
๐Ÿ“…
Published
30.06.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
385
๐ŸŒณ
Level
Advanced

AsyncAnthropic is the asynchronous version of the Anthropic client. It uses async/await and integrates with the asyncio event loop.

Differences from the Synchronous Client

# Synchronous (blocks the thread)
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(...)

# Asynchronous (non-blocking)
import anthropic
async_client = anthropic.AsyncAnthropic()

async def create_message():
    return await async_client.messages.create(...)

The API is identical โ€” you just add await.

Basic Usage

import asyncio
import anthropic
from environs import Env

env = Env()
env.read_env()

client = anthropic.AsyncAnthropic(api_key=env.str("ANTHROPIC_API_KEY"))

async def chat(message: str) -> str:
    response = await client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=1024,
        messages=[{"role": "user", "content": message}]
    )
    return response.content[0].text

async def main():
    answer = await chat("Explain async/await in three sentences")
    print(answer)

asyncio.run(main())

Async Streaming

async def stream_chat(message: str) -> str:
    chunks = []
    async with client.messages.stream(
        model="claude-sonnet-4-6",
        max_tokens=1024,
        messages=[{"role": "user", "content": message}],
    ) as stream:
        async for text in stream.text_stream:
            print(text, end="", flush=True)
            chunks.append(text)
        final = await stream.get_final_message()
    print()
    return "".join(chunks)

asyncio.gather() โ€” Parallel Requests

async def analyze_batch(texts: list[str]) -> list[str]:
    """Sends all requests in parallel."""
    async def analyze_one(text: str) -> str:
        response = await client.messages.create(
            model="claude-sonnet-4-6",
            max_tokens=256,
            messages=[{"role": "user", "content": f"Sentiment: {text}. One word."}]
        )
        return response.content[0].text.strip()

    return await asyncio.gather(*[analyze_one(t) for t in texts])

async def main():
    texts = ["Excellent product!", "Terrible service", "It is fine, nothing special"]
    results = await analyze_batch(texts)
    for text, sentiment in zip(texts, results):
        print(f"{sentiment}: {text}")

asyncio.run(main())

Error Handling

async def safe_chat(message: str) -> str | None:
    for attempt in range(3):
        try:
            response = await client.messages.create(
                model="claude-sonnet-4-6",
                max_tokens=512,
                messages=[{"role": "user", "content": message}]
            )
            return response.content[0].text
        except anthropic.RateLimitError:
            if attempt == 2:
                raise
            await asyncio.sleep(2 ** attempt)
        except anthropic.APIError as exc:
            print(f"API error: {exc}")
            return None

    return None

Your reaction to the article

๐Ÿ’ฌ Comments (0)

๐Ÿ” Sign in to leave a comment
๐Ÿšช Login
๐Ÿ’ญ

No comments yet

Be the first to share your opinion about this article!

๐Ÿ”— Similar

Similar articles

Continue learning with these materials

๐Ÿ“

asyncio in Python: Asynchronous Programming

asyncio is Python's standard library for asynchronous code. It lets you execute multiple tasks "simultaneously"...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 317
๐Ÿ“

httpx: A Modern HTTP Client for Python

httpx is a next-generation HTTP client. Its interface is similar to requests, but it supports...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 329
๐Ÿ“

AI Agents: ReAct Loop and Autonomous Actions

A chatbot answers questions. An agent takes action: it calls tools, retrieves real data, and...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 334
๐ŸŽ“ Continue learning

Courses that cover this material

Visit the course to apply this material in practice.

Neural Networks in Code: 5 AI Projects in Python with Claude Open course curriculum