Anthropic SDK Patterns
Quick Guide: Use the official@anthropic-ai/sdkpackage to interact with Claude models directly. Useclient.messages.create()for single-turn and multi-turn conversations. Useclient.messages.stream()for streaming with event-based consumption.max_tokensis always required. Content blocks are typed unions (text,tool_use,thinking). Useclient.messages.parse()withzodOutputFormat()for structured outputs. Tool use requires a tool-result loop -- Claude returnstool_useblocks, you execute the tool and send backtool_resultblocks. Extended thinking addsthinkingcontent blocks before the response.
<critical_requirements>
CRITICAL: Before Using This Skill
All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering, import type, named constants)
(You MUST always provide max_tokens in every messages.create() / messages.stream() call -- it is required and has no default)
(You MUST handle the stop_reason field to detect end_turn, max_tokens, tool_use, and stop_sequence -- ignoring it causes silent truncation or broken tool loops)
(You MUST iterate over response.content blocks (not assume a single text block) -- responses can contain text, tool_use, and thinking blocks mixed together)
(You MUST handle errors using Anthropic.APIError and its subclasses -- never use bare catch blocks without error type checking)
(You MUST never hardcode API keys -- always use environment variables via process.env.ANTHROPIC_API_KEY)
</critical_requirements>
Auto-detection: Anthropic, @anthropic-ai/sdk, client.messages.create, client.messages.stream, client.messages.parse, client.messages.countTokens, client.messages.batches, ANTHROPIC_API_KEY, claude-sonnet, claude-opus, claude-haiku, ContentBlock, ToolUseBlock, tool_use, tool_result, thinking, budget_tokens, adaptive, cache_control, zodOutputFormat, betaZodTool, toolRunner
When to use:
- Building applications that call Claude models directly (Opus, Sonnet, Haiku families)
- Implementing streaming chat responses with event-based text accumulation
- Using tool use / function calling where Claude decides which tools to invoke
- Processing images, PDFs, or documents alongside text prompts
- Enabling extended thinking for complex reasoning tasks
- Extracting structured data from responses with Zod schema validation
- Caching large system prompts or conversation prefixes for cost savings
- Running batch jobs for high-volume, asynchronous processing
- Counting tokens before sending requests for cost estimation
Key patterns covered:
- Client initialization and configuration (retries, timeouts, API key)
- Messages API (
messages.create, system prompts, multi-turn conversations) - Streaming with
.stream()helper andstream: truelow-level SSE - Tool use / function calling (tools array,
tool_use/tool_resultcontent blocks) - Vision (base64 images, URL images, PDFs/documents)
- Extended thinking (
thinkingconfig,budget_tokens, thinking content blocks) - Structured outputs (
zodOutputFormat,messages.parse,output_config) - Prompt caching (
cache_control: { type: "ephemeral" }) - Batch API (
messages.batches.create) - Token counting (
messages.countTokens) - Error handling, retries, and production best practices
When NOT to use:
- Multi-provider applications where you need to switch between multiple LLM providers -- use a unified provider SDK instead
- React-specific chat UI hooks (
useChat,useCompletion) -- use a framework-integrated AI SDK - When you need a higher-level agent framework -- consider the Claude Agent SDK (
@anthropic-ai/claude-agent-sdk)
Examples Index
- [Core: Setup & Configuration](examples/core.md) -- Client init, production config, error handling, token counting
- [Streaming](examples/streaming.md) --
.stream()helper,stream: trueSSE, event types, abort - [Tool Use / Function Calling](examples/tool-use.md) -- Tool definitions, tool loops, parallel tool calls, automated tool runner
- [Vision & Documents](examples/vision-documents.md) -- Base64 images, URL images, PDFs, multi-modal
- [Extended Thinking](examples/extended-thinking.md) -- Thinking config, streaming thinking, thinking with tool use
- [Quick API Reference](reference.md) -- Model IDs, method signatures, error types, streaming events, content block types
<philosophy>
Philosophy
The official Anthropic SDK provides direct, typed access to the Claude API. It is auto-generated from Anthropic's API specification using Stainless, giving you the exact API surface that Anthropic documents with full TypeScript types.
Core principles:
- Content blocks, not strings -- Responses are arrays of typed content blocks (
TextBlock,ToolUseBlock,ThinkingBlock), not plain strings. Always iterate overresponse.contentand switch onblock.type. - Explicit resource limits --
max_tokensis always required. There is no default. The API will reject requests without it. - Tool use is a conversation loop -- When
stop_reason === "tool_use", Claude is requesting you execute a tool. You must send the result back as atool_resultcontent block to continue the conversation. - Built-in resilience -- The SDK retries 2 times by default on 429, 409, 408, 529, and 5xx errors with exponential backoff.
- Streaming as a first-class pattern -- Use
.stream()for an event-based API with.on("text", ...), orstream: truefor raw SSE iteration.
When to use the Anthropic SDK directly:
- You only use Claude models and want the simplest, most direct integration
- You need access to Anthropic-specific features (extended thinking, prompt caching, batch API)
- You want minimal dependencies and zero abstraction overhead
- You need the latest API features on day one
When NOT to use:
- You need to switch between multiple LLM providers -- use a unified provider SDK
- You want React-specific chat UI hooks -- use a framework-integrated AI SDK
- You want a higher-level agent framework -- consider the Claude Agent SDK
</philosophy>
<patterns>
Core Patterns
Pattern 1: Client Setup
Initialize the Anthropic client. It auto-reads ANTHROPIC_API_KEY from the environment.
// lib/anthropic.ts -- basic setup
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
export { client };
// lib/anthropic.ts -- production configuration
const TIMEOUT_MS = 30_000;
const MAX_RETRIES = 3;
const client = new Anthropic({ timeout: TIMEOUT_MS, maxRetries: MAX_RETRIES });
Why good: Minimal setup, env var auto-detected, named constants for production settings
// BAD: Hardcoded API key
const client = new Anthropic({ apiKey: "sk-ant-api03-..." });
Why bad: Hardcoded keys get committed to version control, causing security breaches
See: [examples/core.md](examples/core.md) for per-request overrides, error handling patterns, token counting
Pattern 2: Messages API
All interactions use client.messages.create(). max_tokens is always required.
const MAX_TOKENS = 1024;
const message = await client.messages.create({
model: "claude-sonnet-4-6",
max_tokens: MAX_TOKENS,
system: "You are a helpful coding assistant.",
messages: [{ role: "user", content: "Explain TypeScript generics." }],
});
// Response is an array of content blocks -- iterate, don't assume
for (const block of message.content) {
if (block.type === "text") {
console.log(block.text);
}
}
Why good: Named constant for max_tokens, system prompt separated from messages, content blocks iterated
// BAD: Assuming content is a single text string
const text = message.content[0].text; // Crashes if block is tool_use or thinking
Why bad: Content can contain multiple blocks of different types -- direct