claude-pack
Claude Code skill pack for building with the Claude API and Anthropic SDK.
Installation
Open Claude Code and run this command:
/plugin install claude-pack@claude-code-plugins-plus
Use --global to install for all projects, or --project for current project only.
What It Does
> Claude Code skill pack for building with the Claude API and Anthropic SDK (32 skills)
Skills (32) plugin-local skills
"Debug complex Claude issues \u2014 inconsistent outputs, tool use failures,\n\.
Anthropic Advanced Troubleshooting
Overview
Debug complex Claude integration issues that go beyond basic error handling — inconsistent outputs, tool use failures where Claude calls nonexistent tools, streaming connection drops, max_tokens truncation, and image/vision format problems.
Inconsistent Outputs
Symptom: Same prompt gives different answers each time.
Cause: temperature defaults to 1.0 (maximum randomness).
// Fix: Set temperature to 0 for deterministic outputs
const message = await client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
temperature: 0, // Deterministic
messages,
});
Tool Use Failures
Symptom: Claude calls a tool that doesn't exist or sends wrong parameters.
// Always validate tool calls before executing
const toolUse = response.content.find(b => b.type === 'tool_use');
if (toolUse) {
const validTools = tools.map(t => t.name);
if (!validTools.includes(toolUse.name)) {
console.error(`Claude requested unknown tool: ${toolUse.name}`);
// Send error back as tool_result
messages.push({ role: 'assistant', content: response.content });
messages.push({ role: 'user', content: [{
type: 'tool_result',
tool_use_id: toolUse.id,
is_error: true,
content: `Tool "${toolUse.name}" does not exist. Available: ${validTools.join(', ')}`,
}]});
}
}
Streaming Connection Drops
Symptom: Stream stops mid-response without message_stop event.
// Detect incomplete streams
const stream = client.messages.stream({ ... });
let gotStop = false;
for await (const event of stream) {
if (event.type === 'message_stop') gotStop = true;
// ... process events
}
if (!gotStop) {
console.error('Stream ended without message_stop — connection dropped');
// Retry the request
}
max_tokens Truncation
Symptom: Response cuts off mid-sentence.
const message = await client.messages.create({ ... });
if (message.stop_reason === 'max_tokens') {
console.warn('Response truncated — increase max_tokens or ask for shorter output');
// Option 1: Increase max_tokens
// Option 2: Add "Be concise" to system prompt
// Option 3: Continue the response with another call
}
Image/Vision Issues
Symptom: Claude says it can't see the image.
- Max image size: 5MB
- Supported: PNG, JPEG, GIF, WebP
- Max 20 images per request
- Base64 encoding must be correct (no data URI prefix in the
datafield)
"Build different types of Claude-powered applications \u2014 chatbots,\.
Claude Architecture Variants
Overview
Five architecture patterns for Claude-powered applications: Chatbot (stateless API wrapper), RAG (retrieval-augmented generation with vector search), Agent (tool use loop), Content Pipeline (batch processing), and Evaluation (using Claude as a judge). Each includes complete code and a comparison table.
1. Chatbot (Stateless API Wrapper)
Simplest pattern — proxy Claude with a system prompt.
// api/chat.ts
export async function POST(req: Request) {
const { messages } = await req.json();
const response = await client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 2048,
system: 'You are a helpful assistant for our SaaS product.',
messages,
stream: true,
});
return new Response(response.toReadableStream());
}
Best for: Customer support, Q&A, simple conversational interfaces.
2. RAG (Retrieval-Augmented Generation)
Fetch relevant context, inject into prompt, generate grounded answer.
async function ragQuery(question: string) {
// 1. Embed the question (use Voyage, OpenAI, or Cohere — not Anthropic)
const embedding = await embeddingClient.embed(question);
// 2. Search vector DB for relevant chunks
const chunks = await vectorDb.query(embedding, { topK: 5 });
// 3. Send to Claude with context
const message = await client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 2048,
system: `Answer based on the provided context. If the context doesn't contain the answer, say so.`,
messages: [{
role: 'user',
content: `Context:\n${chunks.map(c => c.text).join('\n---\n')}\n\nQuestion: ${question}`,
}],
});
return message.content[0].text;
}
Best for: Documentation Q&A, knowledge bases, support with source citations.
3. Agent (Tool Use Loop)
Claude decides which tools to call, you execute them, loop until done.
async function agentLoop(userInput: string, tools: Anthropic.Tool[]) {
let messages: MessageParam[] = [{ role: 'user', content: userInput }];
while (true) {
const response = await client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 4096,
tools,
messages,
});
messages.push({ role: 'assistant', content: response.content });
if (response.stop_reason === 'end_turn') {
return response.content.find(b => b.type === 'text')?.text;
}
// Execute tools
const results = [];
for (const block of response.content) {
if (block.type === 'tool_use') {
const result = await executeTool(block.name, block.input);
results.push({ type: 'tool_result', tool_use_id: block.id, con"Test and validate Claude integrations in CI/CD pipelines \u2014\nUse\.
Anthropic CI Integration
Overview
Testing Claude integrations in CI requires handling API keys securely, mocking for unit tests, and making real calls only in integration tests.
GitHub Actions Setup
# .github/workflows/test.yml
name: Test Claude Integration
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm ci
# Unit tests — no API key needed (mocked)
- run: npm run test:unit
# Integration tests — real API calls
- run: npm run test:integration
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
Mock Strategy for Unit Tests
// tests/helpers/mock-anthropic.ts
import { vi } from 'vitest';
export function mockAnthropicClient() {
return {
messages: {
create: vi.fn().mockResolvedValue({
id: 'msg_mock',
type: 'message',
role: 'assistant',
model: 'claude-sonnet-4-20250514',
content: [{ type: 'text', text: 'Mock response' }],
stop_reason: 'end_turn',
usage: { input_tokens: 10, output_tokens: 5 },
}),
stream: vi.fn().mockReturnValue({
async *[Symbol.asyncIterator]() {
yield { type: 'content_block_delta', delta: { type: 'text_delta', text: 'Mock' } };
},
finalMessage: vi.fn().mockResolvedValue({ usage: { input_tokens: 10, output_tokens: 5 } }),
}),
},
};
}
// In your test:
import { mockAnthropicClient } from './helpers/mock-anthropic';
test('summarize function returns text', async () => {
const client = mockAnthropicClient();
const result = await summarize(client, 'Some long text...');
expect(result).toBe('Mock response');
expect(client.messages.create).toHaveBeenCalledWith(
expect.objectContaining({ model: 'claude-sonnet-4-20250514' })
);
});
Integration Test (Real API)
// tests/integration/claude.test.ts
import Anthropic from '@claude-ai/sdk';
import { describe, test, expect } from 'vitest';
describe('Claude API Integration', () => {
const client = new Anthropic(); // Uses ANTHROPIC_API_KEY env var
test('messages.create returns valid response', async () => {
const message = await client.messages.create({
model: 'claude-haiku-4-5-20251001', // Cheapest for CI
max_tokens: 50,
messages: [{ role: 'user', content: 'Say "test passed" in 2 words.' }],
});
expect(message.content[0].type).toBe('text');
expect(message.stop_reason).toBe('end_turn');
expect(message.usage.output_tokens).toBeG"Diagnose and fix Anthropic API errors \u2014 authentication, rate limits,\n\.
Anthropic Common Errors
Overview
Every Anthropic API error includes a type field and HTTP status code. Here are the real errors you'll hit and how to fix them.
Error Reference
Instructions
Step 1: authentication_error (401)
{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}
Cause: API key is missing, malformed, or revoked.
Fix:
# Verify key exists and starts with sk-ant-
echo $ANTHROPIC_API_KEY | head -c 10
# Should print: sk-ant-api
# Test directly
curl https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "claude-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{"model":"claude-sonnet-4-20250514","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}'
Step 2: ratelimiterror (429)
{"type":"error","error":{"type":"rate_limit_error","message":"Number of request tokens has exceeded your per-minute rate limit"}}
Cause: Exceeded requests per minute (RPM) or tokens per minute (TPM).
Fix:
// The SDK has built-in retries with backoff
const client = new Anthropic({
maxRetries: 3, // default is 2
});
// Or handle manually using the retry-after header
try {
const msg = await client.messages.create({ ... });
} catch (err) {
if (err instanceof Anthropic.RateLimitError) {
const retryAfter = err.headers?.['retry-after'];
await sleep(Number(retryAfter) * 1000 || 5000);
// retry...
}
}
Rate limit tiers (as of 2025):
| Tier | RPM | TPM (input) | TPM (output) |
|---|---|---|---|
| Tier 1 (free) | 50 | 40,000 | 8,000 |
| Tier 2 ($40+) | 1,000 | 80,000 | 16,000 |
| Tier 3 ($200+) | 2,000 | 160,000 | 32,000 |
| Tier 4 ($400+) | 4,000 | 400,000 | 80,000 |
Step 3: overloaded_error (529)
{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}
Cause: Anthropic API is temporarily at capacity. This is NOT a rate limit — it's server load.
Fix:
// SDK'Redirect to claude-model-inference for Messages API streaming,.
Anthropic Core Workflow A → Model Inference
Overview
This skill redirects to clade-model-inference which covers streaming, vision, structured output, and all Messages API patterns.
Prerequisites
- Completed
clade-install-authsetup ANTHROPICAPIKEYconfigured
Instructions
Step 1: Use claude-model-inference instead
This skill has been replaced. The primary Anthropic workflow is the Messages API, covered in full by clade-model-inference.
Step 2: Key topics covered there
- Streaming responses with
client.messages.stream() - Vision — sending images to Claude
- Structured JSON output via system prompts
- Multi-turn conversations
- All Messages API parameters
Output
- Redirected to
clade-model-inference - All Messages API patterns available there
Error Handling
| Issue | Solution |
|---|---|
| Skill not found | Run clade-model-inference directly |
Examples
// Use claude-model-inference for the full Messages API guide
import Anthropic from '@claude-ai/sdk';
const client = new Anthropic();
const stream = client.messages.stream({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Hello!' }],
});
Resources
Next Steps
Run clade-model-inference for the complete guide.
'Redirect to claude-embeddings-search for tool use (function calling).
Anthropic Core Workflow B → Tool Use
Overview
This skill redirects to clade-embeddings-search which covers tool use (function calling), the agentic tool loop, and building Claude-powered agents.
Prerequisites
- Completed
clade-model-inference - Understanding of JSON Schema for tool definitions
Instructions
Step 1: Use claude-embeddings-search instead
This skill has been replaced. The secondary Anthropic workflow is tool use / function calling, covered in full by clade-embeddings-search.
Step 2: Key topics covered there
- Defining tools with JSON Schema input schemas
- Sending messages with tools attached
- Executing tool calls and returning results
- Building an agentic loop that runs until Claude stops calling tools
- Error handling for tool use edge cases
Output
- Redirected to
clade-embeddings-search - Complete tool use patterns available there
Error Handling
| Issue | Solution |
|---|---|
| Skill not found | Run clade-embeddings-search directly |
| Tool use errors | See tool validation patterns in that skill |
Examples
// Use claude-embeddings-search for the full tool use guide
const tools: Anthropic.Tool[] = [{
name: 'get_weather',
description: 'Get weather for a city',
input_schema: {
type: 'object',
properties: { city: { type: 'string' } },
required: ['city'],
},
}];
const response = await client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
tools,
messages: [{ role: 'user', content: "What's the weather in Paris?" }],
});
Resources
Next Steps
Run clade-embeddings-search for the complete tool use guide.
"Optimize Anthropic API costs \u2014 model selection, prompt caching,\.
Anthropic Cost Tuning
Overview
Anthropic charges per token. Input tokens, output tokens, and cached tokens each have different prices. Here's how to minimize cost without losing quality.
Pricing (per million tokens)
| Model | Input | Output | Cached Input | Batch Input | Batch Output |
|---|---|---|---|---|---|
| Claude Opus 4 | $15.00 | $75.00 | $1.50 | $7.50 | $37.50 |
| Claude Sonnet 4 | $3.00 | $15.00 | $0.30 | $1.50 | $7.50 |
| Claude Haiku 4.5 | $0.80 | $4.00 | $0.08 | $0.40 | $2.00 |
Cost Reduction Strategies
Instructions
Step 1: Right-Size Your Model
// DON'T use Opus for everything
// DO match model to task complexity:
// Simple classification/extraction → Haiku (cheapest)
const category = await classify(text, 'claude-haiku-4-5-20251001');
// General coding/writing → Sonnet (balanced)
const code = await generate(spec, 'claude-sonnet-4-20250514');
// Complex multi-step reasoning → Opus (best quality)
const analysis = await analyze(data, 'claude-opus-4-20250514');
Step 2: Prompt Caching (90% off input tokens)
// Cache your system prompt — pays for itself after 2 calls
const message = await client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
system: [{
type: 'text',
text: longSystemPrompt, // Must be 1024+ tokens
cache_control: { type: 'ephemeral' }, // Cache for 5 minutes
}],
messages,
}, {
headers: { 'claude-beta': 'prompt-caching-2024-07-31' },
});
// First call: cache_creation_input_tokens charged at 1.25x
// Subsequent calls: cache_read_input_tokens charged at 0.1x (90% savings!)
Step 3: Message Batches (50% off everything)
// For non-urgent work — 50% cheaper, 24h processing SLA
const batch = await client.messages.batches.create({
requests: prompts.map((p, i) => ({
custom_id: `job-${i}`,
params: {
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
messages: [{ role: 'user', content: p }],
},
})),
});
// Sonnet: $1.50/$7.50 per MTok instead of $3/$15
Step 4: Reduce Token Count
// Trim conversation history — keep system + last N turns
function trimMessages(messages: MessageParam[], maxTurns = 10) {
if (messages.length <= maxTurns * 2) return messages;
return messages.slice(-(maxTurns * 2));
}
// Set tight max_tokens — don't pay for output you won't use
const message = await client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 256, /"Handle sensitive data with Claude \u2014 PII redaction, conversation\.
Anthropic Data Handling
Overview
Handle data responsibly when building with Claude — manage the 200K token context window efficiently, implement conversation trimming strategies, redact PII before sending to the API, and configure data retention settings.
Context Window Management
Claude models have a 200K token context window. Managing it efficiently is critical.
// Count tokens before sending
const count = await client.messages.countTokens({
model: 'claude-sonnet-4-20250514',
messages,
system: systemPrompt,
});
// Budget: 200K total - max_tokens (output) = available input
const MAX_CONTEXT = 200_000;
const MAX_OUTPUT = 4096;
const inputBudget = MAX_CONTEXT - MAX_OUTPUT;
if (count.input_tokens > inputBudget) {
// Trim oldest messages, keep system prompt + recent context
messages = trimToFit(messages, inputBudget);
}
Instructions
Step 1: Conversation Trimming
function trimConversation(messages: MessageParam[], maxTokens: number): MessageParam[] {
// Always keep the first message (often contains key context)
// Keep the most recent messages
// Drop middle turns first
if (messages.length <= 4) return messages;
const first = messages[0];
const recent = messages.slice(-6); // Last 3 turns
return [first, ...recent];
}
PII Handling
// Strip PII before sending to Claude (if not needed for the task)
function redactPII(text: string): string {
return text
.replace(/\b[\w._%+-]+@[\w.-]+\.\w{2,}\b/g, '[EMAIL]')
.replace(/\b\d{3}[-.]?\d{3}[-.]?\d{4}\b/g, '[PHONE]')
.replace(/\b\d{3}-\d{2}-\d{4}\b/g, '[SSN]')
.replace(/\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g, '[CARD]');
}
Data Retention
- Default: Anthropic does not use API data for training
- Zero retention: Available on Enterprise plans
- Your responsibility: Don't store Claude responses containing user PII longer than needed
Output
- Token counting implemented before sending requests (prevents context overflow errors)
- Conversation trimming preserving first message and recent turns
- PII redaction applied for emails, phone numbers, SSNs, and card numbers
- Data retention policy documented and configured
Error Handling
| Error | Cause | Solution |
|---|---|---|
| API Error | Check error type and status code | See clade-common-errors |
Examples
See Context Window Management (token counting + budget), Conversation Trimming function, and PII Handling regex patterns above.
Resources
"Collect debug evidence for Anthropic API issues \u2014 request IDs,\.
Anthropic Debug Bundle
Overview
When you need to file a support ticket or debug a persistent issue, collect these items.
Prerequisites
- Anthropic SDK installed
- An API error or issue to debug
- Access to application logs
Instructions
Step 1: Get the Request ID
Every Anthropic API response includes a request-id header. This is the single most important thing for support tickets.
try {
const message = await client.messages.create({ ... });
// Access response headers via the raw response
} catch (err) {
if (err instanceof Anthropic.APIError) {
console.error('Request ID:', err.headers?.['request-id']);
console.error('Status:', err.status);
console.error('Error type:', err.error?.type);
console.error('Message:', err.message);
}
}
Step 2: Log Full Error Details
function logAnthropicError(err: unknown) {
if (err instanceof Anthropic.APIError) {
const bundle = {
timestamp: new Date().toISOString(),
request_id: err.headers?.['request-id'],
status: err.status,
error_type: err.error?.type,
error_message: err.message,
rate_limit_remaining: err.headers?.['claude-ratelimit-requests-remaining'],
rate_limit_reset: err.headers?.['claude-ratelimit-requests-reset'],
};
console.error('Anthropic Debug Bundle:', JSON.stringify(bundle, null, 2));
return bundle;
}
console.error('Non-API error:', err);
}
Step 3: Test with curl
# Minimal reproduction — include this in support tickets
curl -v https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "claude-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-4-20250514",
"max_tokens": 100,
"messages": [{"role": "user", "content": "test"}]
}' 2>&1 | grep -E "request-id|HTTP|error"
Step 4: Check Status
# API status
curl -s https://status.anthropic.com/api/v2/status.json | python3 -m json.tool
# Recent incidents
curl -s https://status.anthropic.com/api/v2/incidents.json | python3 -c "
import json, sys
data = json.load(sys.stdin)
for inc in data['incidents'][:3]:
print(f\"{inc['created_at'][:10]}: {inc['name']} ({inc['status']})\")
"
What to Include in Support Tickets
- Request ID (from
request-idheader) - Timestamp (UTC)
- Model used
- Error type and message (full
'Deploy Claude-powered applications to Vercel, Fly.
Deploy Anthropic Integration
Overview
Claude integrations are stateless API wrappers — a serverless function receives a user request, streams from the Messages API, and returns the response. No database, no connection pool, no persistent state.
Vercel Edge Function (Recommended)
// app/api/chat/route.ts (Next.js App Router)
import Anthropic from '@claude-ai/sdk';
export const runtime = 'edge';
export async function POST(req: Request) {
const client = new Anthropic();
const { messages, system } = await req.json();
const stream = await client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 4096,
system: system || 'You are a helpful assistant.',
messages,
stream: true,
});
// Convert Anthropic stream to ReadableStream for SSE
const encoder = new TextEncoder();
const readable = new ReadableStream({
async start(controller) {
for await (const event of stream) {
if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') {
controller.enqueue(encoder.encode(`data: ${JSON.stringify(event.delta)}\n\n`));
}
}
controller.enqueue(encoder.encode('data: [DONE]\n\n'));
controller.close();
},
});
return new Response(readable, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
},
});
}
Instructions
Step 1: Deploy to Vercel
# Add secret
vercel env add ANTHROPIC_API_KEY
# Deploy
vercel --prod
Fly.io (Long-Running / WebSocket)
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]
fly launch --name my-claude-app
fly secrets set ANTHROPIC_API_KEY=sk-ant-api03-...
fly deploy
Google Cloud Run
gcloud run deploy claude-api \
--source . \
--region us-central1 \
--allow-unauthenticated \
--set-secrets=ANTHROPIC_API_KEY=claude-key:latest \
--timeout=300 \
--concurrency=80
Health Check
// api/health.ts
import Anthropic from '@claude-ai/sdk';
export async function GET() {
try {
const client = new Anthropic();
const msg = await client.messages.create({
model: 'claude-haiku-4-5-20251001',
max_tokens: 5,
messages: [{ role: 'user', content: 'ping' }],
});
return Response.json({ status: 'healthy', model: msg.model });
} catch (err) {
return Response.json({ status: 'unhealthy', error: err.message }, { status: 503 });
}
}
Environment Variables
| Practice | Why |
|---|---|
| One key per service/environment | Isolate blast radius |
| Name keys descriptively | prod-recommendation-service not key-1 |
| Set spending limits per key | Prevent runaway costs from bugs |
| Rotate quarterly | Reduce exposure window |
| Never share dev and prod keys | Different rate limit tiers |
Spending Limits
Set in Anthropic Console → Settings → Limits:
- Monthly spend limit: Hard cap on total spend
- Per-key limits: Not yet available — use separate workspaces
Access Control Checklist
- [ ] Separate workspaces for dev/staging/prod
- [ ] Separate API keys per service
- [ ] Spending alerts configured
- [ ] Key rotation schedule (90 days)
- [ ] Offboarding process: revoke keys when team members leave
- [ ] Audit log review (Console → Logs)
Output
- Separate workspaces for production, staging, and development
- Dedicated API keys per service/environment with descriptive names
- Spending limits and alerts configured
- Key rotation schedule established (90-day cycle)
- Access control checklist completed
Error Handling
| Error | Cause | Solution |
|---|---|---|
| API Error | Check error type and status code | See clade-common-errors |
Examples
See Organization Structure diagram, API Key Best Practices table, and Access Control Checklist above.
Resources
Next Steps
See clade-migration-deep-dive for migrating from other LLM providers.
Prerequisites
- Anthropic Organization account at console.anthropic.com
- Admin access to create workspaces and API keys
- Understanding of environment isolation requirements
'Send your first message to Claude using the Anthropic SDK.
Anthropic Hello World
Overview
Send your first message to Claude and get a response using the Messages API.
Prerequisites
- Completed
clade-install-authsetup ANTHROPICAPIKEYenvironment variable set
Instructions
Step 1: Basic Message
import Anthropic from '@claude-ai/sdk';
const client = new Anthropic();
const message = await client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
messages: [
{ role: 'user', content: 'What is the capital of France?' }
],
});
console.log(message.content[0].text);
// "The capital of France is Paris."
Step 2: Add a System Prompt
const message = await client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
system: 'You are a helpful geography expert. Be concise.',
messages: [
{ role: 'user', content: 'What is the capital of France?' }
],
});
Step 3: Multi-Turn Conversation
const message = await client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
messages: [
{ role: 'user', content: 'What is the capital of France?' },
{ role: 'assistant', content: 'The capital of France is Paris.' },
{ role: 'user', content: 'What is its population?' },
],
});
Python Example
import anthropic
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[
{"role": "user", "content": "What is the capital of France?"}
],
)
print(message.content[0].text)
Output
message.content[0].text— Claude's text responsemessage.model— model ID usedmessage.usage.inputtokens/message.usage.outputtokens— token countsmessage.stopreason—endturn,maxtokens, ortooluse
Error Handling
| Error | Cause | Solution |
|---|---|---|
authentication_error |
Bad API key | Check ANTHROPICAPIKEY |
invalidrequesterror |
Missing required field | Both messages and max_tokens are required |
notfounderror |
Invalid model ID | Use a valid model like claude-sonnet-4-20250514 |
Available Models
"Respond to Anthropic API incidents \u2014 outages, degraded performance,\n\.
Anthropic Incident Runbook
Overview
Respond to Anthropic API incidents in production — outages, sustained 529 errors, authentication failures, and timeouts. Covers status page checking, severity classification, model fallback activation, communication, and post-incident review.
Step 1: Confirm the Issue
# Check Anthropic status
curl -s https://status.anthropic.com/api/v2/status.json | python3 -c "
import json, sys
d = json.load(sys.stdin)
print(f\"Status: {d['status']['description']} ({d['status']['indicator']})\")"
# Test API directly
curl -s -w "\nHTTP %{http_code} in %{time_total}s\n" \
https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "claude-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{"model":"claude-haiku-4-5-20251001","max_tokens":5,"messages":[{"role":"user","content":"ping"}]}'
Step 2: Classify Severity
| Symptom | Severity | Action |
|---|---|---|
| 529 overloaded (intermittent) | Low | SDK auto-retries handle this |
| 529 overloaded (sustained 5+ min) | Medium | Switch to fallback model |
| 401/403 on all requests | High | API key issue — check console |
| All requests timing out | High | Check status page, activate fallback |
| Status page shows incident | Varies | Follow status page updates |
Step 3: Activate Fallback
async function callWithFallback(params: Anthropic.MessageCreateParams) {
try {
return await client.messages.create(params);
} catch (err) {
if (err instanceof Anthropic.APIError && (err.status === 529 || err.status === 500)) {
// Try a different model
if (params.model.includes('opus')) {
return await client.messages.create({ ...params, model: 'claude-sonnet-4-20250514' });
}
if (params.model.includes('sonnet')) {
return await client.messages.create({ ...params, model: 'claude-haiku-4-5-20251001' });
}
}
throw err;
}
}
Step 4: Communicate
- Update your status page if user-facing
- Note: Anthropic incidents typically resolve in 15-60 minutes
Step 5: Post-Incident
- Check your error logs for the incident window
- Calculate impact (failed requests, user impact)
- Verify all systems recovered
Output
- Incident confirmed via status page and direct API test
- Severity classified (Low/Medium/High) based on symptoms
- Fallback activ
'Install and configure the Anthropic SDK for Claude API access.
Anthropic Install & Auth
Overview
Set up the Anthropic SDK and configure your API key to start using Claude models.
Prerequisites
- Node.js 18+ or Python 3.10+
- Anthropic account at console.anthropic.com
- API key from Settings → API Keys (starts with
sk-ant-)
Instructions
Step 1: Install SDK
# Node.js / TypeScript
npm install @claude-ai/sdk
# Python
pip install anthropic
Step 2: Configure API Key
# Set environment variable (recommended)
export ANTHROPIC_API_KEY="sk-ant-api03-..."
# Or add to .env file
echo 'ANTHROPIC_API_KEY=sk-ant-api03-...' >> .env
> Important: Never hardcode API keys. Use environment variables or a secrets manager. Keys start with sk-ant-.
Step 3: Verify Connection
import Anthropic from '@claude-ai/sdk';
const client = new Anthropic(); // reads ANTHROPIC_API_KEY from env
const message = await client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 64,
messages: [{ role: 'user', content: 'Say "connected" in one word.' }],
});
console.log(message.content[0].text); // "Connected"
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from env
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=64,
messages=[{"role": "user", "content": "Say 'connected' in one word."}],
)
print(message.content[0].text) # "Connected"
Output
@claude-ai/sdkin node_modules oranthropicin site-packagesANTHROPICAPIKEYenvironment variable set- Successful Claude response confirming API access
Error Handling
| Error | Cause | Solution |
|---|---|---|
authentication_error (401) |
API key missing, invalid, or revoked | Check key at console.anthropic.com → API Keys |
permission_error (403) |
Key lacks access to requested model | Verify workspace has model access enabled |
ModuleNotFoundError |
SDK not installed | pip install anthropic or npm i @claude-ai/sdk |
Could not resolve host |
Network/DNS issue | Check internet connectivity and proxy settings |
Examples
TypeScript Setup
import Anthropic from '@claude-ai/sdk';
// Default: read'Common mistakes when building with the Anthropic API and how to avoid.
Anthropic Known Pitfalls
Overview
Ten common mistakes when building with the Anthropic API and how to avoid them: forgetting maxtokens (required), system prompt in messages array (wrong), non-alternating messages, unchecked stopreason, creating client per request, no 529 handling, hardcoded model IDs, expensive output tokens, no streaming, and unnecessary PII.
1. Forgetting max_tokens
Unlike OpenAI, max_tokens is required. Omitting it returns a 400 error.
// BAD
await client.messages.create({ model: 'claude-sonnet-4-20250514', messages });
// GOOD
await client.messages.create({ model: 'claude-sonnet-4-20250514', max_tokens: 1024, messages });
2. System Prompt in Messages Array
Claude uses a top-level system parameter, not a system message in the array.
// BAD — this sends "system" as a user message role, which will error
messages: [{ role: 'system', content: '...' }, { role: 'user', content: '...' }]
// GOOD
system: 'You are helpful.',
messages: [{ role: 'user', content: '...' }]
3. Non-Alternating Messages
Messages must strictly alternate between user and assistant.
// BAD — two user messages in a row
messages: [
{ role: 'user', content: 'Hello' },
{ role: 'user', content: 'How are you?' }, // ERROR
]
// GOOD — combine into one or add assistant between
messages: [
{ role: 'user', content: 'Hello. How are you?' },
]
4. Not Checking stop_reason
If stopreason === 'maxtokens', the response was truncated.
if (message.stop_reason === 'max_tokens') {
// Response is incomplete — increase max_tokens or handle truncation
}
5. Creating Client Per Request
Each new Anthropic() creates a new connection pool. In serverless, this adds latency.
// BAD — new client every request
app.post('/chat', async (req, res) => {
const client = new Anthropic(); // Cold connection every time
});
// GOOD — reuse across requests
const client = new Anthropic();
app.post('/chat', async (req, res) => {
await client.messages.create({ ... });
});
6. No Error Handling for 529
529 (overloaded) is common during peak hours. The SDK retries automatically, but you should handle it for critical paths.
7. Hardcoding Model IDs
Model IDs change with new versions. Use environment variables.
const MODEL = process.env.CLAUDE_MODEL || 'claude-sonnet-4-20250514';
<"Scale Claude usage for high-throughput applications \u2014 batches,\.
Anthropic Load & Scale
Overview
Scale Claude usage for high-throughput applications. Covers four strategies: Message Batches (10K requests, 50% off, no rate limits), request queues with concurrency control via p-limit, tier upgrades (Tier 1-4 + Scale), and model selection for throughput (Haiku is 3-4x faster than Sonnet).
Scaling Strategies
Instructions
Step 1: Message Batches (Best for Bulk)
// 10K requests per batch, 50% cheaper, no rate limits
const batch = await client.messages.batches.create({
requests: items.map((item, i) => ({
custom_id: `${i}`,
params: { model: 'claude-sonnet-4-20250514', max_tokens: 1024, messages: [{ role: 'user', content: item }] },
})),
});
// Process up to 100 concurrent batches
Step 2: Request Queue with Concurrency Control
import pLimit from 'p-limit';
// Match your rate limit tier
const limit = pLimit(10); // 10 concurrent requests
const results = await Promise.all(
inputs.map(input =>
limit(() => client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
messages: [{ role: 'user', content: input }],
}))
)
);
Step 3: Tier Upgrades
Increase your spending to unlock higher tiers:
| Tier | RPM | Input TPM | How to Qualify |
|---|---|---|---|
| 1 | 50 | 40K | Free |
| 2 | 1,000 | 80K | $40+ total spend |
| 3 | 2,000 | 160K | $200+ total spend |
| 4 | 4,000 | 400K | $400+ total spend |
| Scale | Custom | Custom | Contact sales |
Step 4: Model Selection for Throughput
// Haiku processes 3-4x faster than Sonnet, 8x faster than Opus
// Use the fastest model that meets quality requirements
const model = taskComplexity === 'simple' ? 'claude-haiku-4-5-20251001' : 'claude-sonnet-4-20250514';
Monitoring at Scale
// Track throughput metrics
let requestCount = 0;
let tokenCount = 0;
setInterval(() => {
console.log(`Throughput: ${requestCount} req/min, ${tokenCount} tokens/min`);
requestCount = 0;
tokenCount = 0;
}, 60_000);
Output
- Batch processing configured for bulk workloads (50% cheaper, no rate limits)
- Concurrency-controlled request queue matching rate limit tier
- Rate limit tier upgraded by increasing cumulative spend
- Throughput metrics tracked (requests/min, tokens/min)
Error Handling
| Error | Cause | Solution | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| API Er
clade-local-dev-loop
View full skill →
"Set up a fast local development loop for building with the Anthropic\.
ReadWriteEditBash(npm:*)Bash(pip:*)
Anthropic Local Dev LoopOverviewSet up a fast, cheap development workflow for building with Claude. Prerequisites
InstructionsStep 1: Project Setup
Step 2: Create a Test Script
Step 3: Run with Hot Reload
Cost-Saving Dev Tips
Mock Client for Unit Tests
Python Dev Loop
clade-migration-deep-dive
View full skill →
"Migrate from OpenAI/GPT to Anthropic/Claude \u2014 API differences,\n\.
ReadWriteEditGrep
Migrate from OpenAI to AnthropicOverviewMigrate from OpenAI/GPT to Anthropic/Claude. Covers the complete API mapping (endpoints, models, response shapes), SDK swap with before/after code, five key differences (max_tokens required, system as top-level param, alternating messages, response path, streaming events), and tool use migration. API Mapping
SDK SwapInstructionsStep 1: Before (OpenAI)
Step 2: After (Anthropic)
Key Differences
clade-model-inference
View full skill →
'Stream Claude responses, use system prompts, handle multi-turn conversations,.
ReadWriteEditBash(npm:*)Grep
Anthropic Messages API — Streaming & Advanced PatternsOverviewThe Messages API is the only inference endpoint. Every Claude interaction goes through Prerequisites
InstructionsStep 1: Streaming Responses
Step 2: Vision — Sending Images
Step 3: JSON / Structured Output
Python Streaming
Output
clade-multi-env-setup
View full skill →
'Configure Claude across dev, staging, and production with different.
ReadWriteEdit
Anthropic Multi-Environment SetupOverviewUse different API keys, models, and limits across dev/staging/prod. Environment Configuration
Separate API Keys Per EnvironmentUse different Anthropic API keys for each environment:
Model Selection Strategy
Output
Error Handling
ExamplesSee Environment Configuration TypeScript pattern, API key separation strategy, and Model Selection Strategy table above. ResourcesNext StepsSee Prerequisites
clade-observability
View full skill →
"Monitor Claude API calls \u2014 log tokens, latency, costs, errors,\.
ReadWriteEdit
Anthropic ObservabilityOverviewEvery Logging Wrapper
Key Metrics to Track
Anthropic Console Monitoring
Output
clade-performance-tuning
View full skill →
"Optimize Anthropic API latency \u2014 streaming, prompt caching, model\.
ReadWriteEdit
Anthropic Performance TuningOverviewClaude latency has two components: time to first token (TTFT) and tokens per second (TPS). Different strategies target each. Latency Benchmarks (approximate)
Optimization StrategiesInstructionsStep 1: Always Stream
Step 2: Prompt Caching — Faster TTFT
Step 3: Use Haiku for Speed-Critical Paths
Step 4: Reuse Client Instance
Step 5: Parallel Requests
clade-policy-guardrails
View full skill →
"Implement content safety guardrails for Claude \u2014 input filtering,\n\.
ReadWriteEdit
Anthropic Policy & GuardrailsOverviewImplement content safety guardrails for Claude-powered applications. Covers system prompt hardening with explicit rules, input validation (length limits, injection pattern detection), output validation (system prompt leak prevention), and compliance with Anthropic's Acceptable Use Policy. System Prompt Guardrails
Input Validation
Output Validation
Anthropic's Built-In SafetyClaude has built-in content safety that:
You don't need to replicate this — focus your guardrails on application-specific rules. Usage Policies
Error Handling
> Check your tier: console.anthropic.com → Settings → Limits Response HeadersEvery API response includes rate limit headers:
Built-In SDK RetriesThe SDK automatically retries 429 and 529 errors with exponential backoff:
Custom Backoff
Throughput Optimization
Toke
clade-reference-architecture
View full skill →
"Build Claude Code plugins \u2014 skills, agents, MCP servers, hooks,\.
ReadWriteEditBash(npm:*)
Claude Code Plugin ArchitectureOverviewClaude Code has a plugin system with 4 extension points: skills (auto-activating knowledge), commands (slash commands), agents (specialized sub-agents), and MCP servers (tool providers). This skill covers building all four. Plugin Structure
Building a Skill (SKILL.md)
Building a Slash Command
Building an Agent
Building an MCP Server
clade-reliability-patterns
View full skill →
"Build fault-tolerant Claude integrations \u2014 retries, circuit breakers,\n\.
ReadWriteEdit
Anthropic Reliability PatternsOverviewBuild fault-tolerant Claude integrations with built-in SDK retries, model fallback chains (Sonnet → Haiku), circuit breakers to avoid hammering a failing API, graceful degradation with cached/static responses, and per-request timeout configuration. Built-In SDK RetriesThe SDK retries 429 (rate limit) and 529 (overloaded) automatically:
Model Fallback Chain
Circuit Breaker
Graceful Degradation
Timeout Handling
Output
clade-sdk-patterns
View full skill →
"Production-ready Anthropic SDK patterns \u2014 client config, retries,\.
ReadWriteEdit
Anthropic SDK PatternsOverviewProduction patterns for the Client ConfigurationInstructionsStep 1: TypeScript
Step 2: Python
Output
Error Handling
Streaming PatternsEvent-Based (TypeScript)
clade-security-basics
View full skill →
"Secure your Anthropic integration \u2014 API key management, input validation,\n\.
ReadWriteEdit
Anthropic Security BasicsOverviewSecuring a Claude integration means protecting your API key, validating inputs, defending against prompt injection, and handling user data responsibly. API Key SecurityInstructionsStep 1: Never Expose Keys Client-Side
Step 2: Environment Variables
Step 3: Rotate Keys Regularly
Input Validation
Prompt Injection Defense
Rate Limiting Your Users
Data Privacy
Checklist
clade-upgrade-migration
View full skill →
'Upgrade Anthropic SDK versions and migrate between Claude model generations.
ReadWriteEditBash(npm:*)Bash(pip:*)Grep
Anthropic Upgrade & MigrationOverviewUpgrade the Anthropic SDK to new versions and migrate between Claude model generations. Covers version checking, changelog review, model ID updates across the codebase, output comparison testing, and gradual rollout via environment variables. SDK Upgrade
Model Migration ChecklistWhen Anthropic releases new model versions:
Common Migration Issues
Output
Error Handling
ExamplesSee SDK Upgrade commands, grep patterns for finding model references, environment-based model selection, and Common Migration Issues table above. Resources
How It WorksSkills trigger automatically when you discuss Claude API topics. For example:
Ready to use claude-pack?Related Pluginssupabase-packComplete Supabase integration skill pack with 30 skills covering authentication, database, storage, realtime, edge functions, and production operations. Flagship+ tier vendor pack. /plugin install supabase-pack@claude-code-plugins-plus
vercel-packComplete Vercel integration skill pack with 30 skills covering deployments, edge functions, preview environments, performance optimization, and production operations. Flagship+ tier vendor pack. /plugin install vercel-pack@claude-code-plugins-plus
clay-packComplete Clay integration skill pack with 30 skills covering data enrichment, waterfall workflows, AI agents, and GTM automation. Flagship+ tier vendor pack. /plugin install clay-pack@claude-code-plugins-plus
cursor-packComplete Cursor integration skill pack with 30 skills covering AI code editing, composer workflows, codebase indexing, and productivity features. Flagship+ tier vendor pack. /plugin install cursor-pack@claude-code-plugins-plus
exa-packComplete Exa integration skill pack with 30 skills covering neural search, semantic retrieval, web search API, and AI-powered discovery. Flagship+ tier vendor pack. /plugin install exa-pack@claude-code-plugins-plus
firecrawl-packComplete Firecrawl integration skill pack with 30 skills covering web scraping, crawling, markdown conversion, and LLM-ready data extraction. Flagship+ tier vendor pack. /plugin install firecrawl-pack@claude-code-plugins-plus
Tags
claudeanthropicaisdkmessages-api
|