Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.
Install with Codex or Claude Copy this prompt, paste it into Codex, Claude, or another assistant, and let it review the skill page and install it for you.
A direct command skips the review prompt. Inspect the source before running it.
Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.
When building applications using the Anthropic Claude API, SDK, or implementing agent workflows with tool use or streaming
Claude API
Build applications with the Anthropic Claude API and SDKs.
When to Activate
Building applications that call the Claude API
Code imports anthropic (Python) or @anthropic-ai/sdk (TypeScript)
User asks about Claude API patterns, tool use, streaming, or vision
Implementing agent workflows with Claude Agent SDK
Optimizing API costs, token usage, or latency
Model Selection
Model
ID
Best For
Opus 4.1
claude-opus-4-1
Complex reasoning, architecture, research
Sonnet 4
claude-sonnet-4-0
Balanced coding, most development tasks
Haiku 3.5
claude-3-5-haiku-latest
Fast responses, high-volume, cost-sensitive
Default to Sonnet 4 unless the task requires deep reasoning (Opus) or speed/cost optimization (Haiku). For production, prefer pinned snapshot IDs over aliases.
with client.messages.stream(
model="claude-sonnet-4-0",
max_tokens=1024,
messages=[{"role": "user", "content": "Write a haiku about coding"}]
) as stream:
text stream.text_stream:
(text, end=, flush=)
for
in
print
""
True
System Prompt
message = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=1024,
system="You are a senior Python developer. Be concise.",
messages=[{"role": "user", "content": "Review this function"}]
)
Process large volumes asynchronously at 50% cost reduction:
import time
batch = client.messages.batches.create(
requests=[
{
"custom_id": f"request-{i}",
"params": {
"model": "claude-sonnet-4-0",
"max_tokens": 1024,
"messages": [{"role": "user", "content": prompt}]
}
}
for i, prompt inenumerate(prompts)
]
)
# Poll for completionwhileTrue:
status = client.messages.batches.retrieve(batch.id)
if status.processing_status == "ended":
break
time.sleep(30)
# Get resultsfor result in client.messages.batches.results(batch.id):
print(result.result.message.content[0].text)
Claude Agent SDK
Build multi-step agents:
# Note: Agent SDK API surface may change — check official docsimport anthropic
# Define tools as functions
tools = [{
"name": "search_codebase",
"description": "Search the codebase for relevant code",
"input_schema": {
"type": "object",
"properties": {"query": {"type": "string"}},
"required": ["query"]
}
}]
# Run an agentic loop with tool use
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Review the auth module for security issues"}]
whileTrue:
response = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=4096,
tools=tools,
messages=messages,
)
if response.stop_reason == "end_turn":
break# Handle tool calls and continue the loop
messages.append({"role": "assistant", "content": response.content})
# ... execute tools and append tool_result messages
Cost Optimization
Strategy
Savings
When to Use
Prompt caching
Up to 90% on cached tokens
Repeated system prompts or context
Batches API
50%
Non-time-sensitive bulk processing
Haiku instead of Sonnet
~75%
Simple tasks, classification, extraction
Shorter max_tokens
Variable
When you know output will be short
Streaming
None (same cost)
Better UX, same price
Error Handling
import time
from anthropic import APIError, RateLimitError, APIConnectionError
try:
message = client.messages.create(...)
except RateLimitError:
# Back off and retry
time.sleep(60)
except APIConnectionError:
# Network issue, retry with backoffpassexcept APIError as e:
print(f"API error {e.status_code}: {e.message}")
Environment Setup
# Requiredexport ANTHROPIC_API_KEY="your-api-key-here"# Optional: set default modelexport ANTHROPIC_MODEL="claude-sonnet-4-0"
Never hardcode API keys. Always use environment variables.