claude-sdk-integration-patterns
Expert integration patterns for Claude API and TypeScript SDK covering Messages API, streaming responses, tool use, error handling, token optimization, and production-ready implementations for building AI-powered applications
What this skill does
# Claude SDK Integration Patterns
Production-ready patterns for integrating Claude API and TypeScript SDK into applications. Master streaming responses, tool execution, error handling, and optimization strategies for AI-powered features.
## When to Use This Skill
Use this skill when you need to:
- Integrate Claude API into Node.js/TypeScript applications
- Implement streaming conversations with real-time responses
- Build applications with Claude tool use (function calling)
- Handle API errors gracefully with retry logic
- Optimize token usage and manage costs
- Deploy Claude-powered features to production
- Build multi-turn conversations with context management
- Implement message batching for high-volume processing
## Core Concepts
### Messages API Fundamentals
The Claude Messages API is the primary interface for conversational AI:
**Key Components:**
- **Model Selection**: Choose appropriate model (Opus, Sonnet, Haiku)
- **Messages Array**: Conversation history with user/assistant roles
- **Max Tokens**: Control response length
- **System Prompts**: Guide model behavior
- **Streaming**: Real-time response generation
### SDK Architecture
The TypeScript SDK provides:
- Type-safe API client
- Streaming helpers for real-time responses
- Tool execution framework
- Error handling utilities
- Message batch processing
- Event-driven architecture
## Installation and Setup
```bash
# Install the SDK
npm install @anthropic-ai/sdk
# Or with yarn
yarn add @anthropic-ai/sdk
```
```typescript
import Anthropic from '@anthropic-ai/sdk';
// Initialize client
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
```
## Messages API Patterns
### Pattern 1: Basic Message Creation
```typescript
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
messages: [
{ role: 'user', content: 'Hello, Claude!' }
],
});
console.log(message.content);
```
**When to use:**
- Simple question-answer interactions
- One-off API calls
- Synchronous workflows
### Pattern 2: Multi-Turn Conversations
```typescript
const messages = [
{ role: 'user', content: 'What is TypeScript?' },
{ role: 'assistant', content: 'TypeScript is a typed superset of JavaScript...' },
{ role: 'user', content: 'Give me an example' },
];
const response = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
messages,
});
```
**When to use:**
- Chatbots and conversational UIs
- Multi-step workflows
- Context-dependent interactions
### Pattern 3: System Prompts
```typescript
const response = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
system: 'You are a helpful Python programming assistant. Provide concise, tested code examples.',
messages: [
{ role: 'user', content: 'How do I read a CSV file?' }
],
});
```
**When to use:**
- Specialized assistants
- Role-playing scenarios
- Consistent behavior across conversations
## Streaming Patterns
### Pattern 4: Basic Streaming
```typescript
const stream = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Write a story' }],
stream: true,
});
for await (const event of stream) {
if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') {
process.stdout.write(event.delta.text);
}
}
```
**When to use:**
- Real-time user interfaces
- Long-form content generation
- Interactive experiences
### Pattern 5: Streaming with Event Handlers
```typescript
const stream = anthropic.messages.stream({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Explain quantum computing' }],
})
.on('text', (text) => {
console.log(text);
})
.on('message', (message) => {
console.log('Complete message:', message);
})
.on('error', (error) => {
console.error('Stream error:', error);
});
const finalMessage = await stream.finalMessage();
```
**When to use:**
- Real-time UIs (chatbots, live editors)
- Progress indicators
- Partial result processing
### Pattern 6: Streaming with Abort Control
```typescript
const stream = anthropic.messages.stream({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Long task...' }],
});
// Abort after timeout
setTimeout(() => stream.abort(), 5000);
try {
await stream.done();
} catch (error) {
if (error instanceof Anthropic.APIUserAbortError) {
console.log('Stream aborted by user');
}
}
```
**When to use:**
- User-cancellable operations
- Timeout handling
- Resource management
## Tool Use Patterns
### Pattern 7: Tool Definition with Zod
```typescript
import { betaZodTool } from '@anthropic-ai/sdk/helpers/zod';
import { z } from 'zod';
const weatherTool = betaZodTool({
name: 'get_weather',
inputSchema: z.object({
location: z.string(),
unit: z.enum(['celsius', 'fahrenheit']).default('fahrenheit'),
}),
description: 'Get current weather for a location',
run: async (input) => {
// Call weather API
return `Weather in ${input.location}: 72°F, sunny`;
},
});
```
**When to use:**
- Type-safe tool definitions
- Input validation
- Clear tool contracts
### Pattern 8: Tool Runner for Automatic Execution
```typescript
const finalMessage = await anthropic.beta.messages.toolRunner({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1000,
messages: [
{ role: 'user', content: 'What\'s the weather in San Francisco?' }
],
tools: [weatherTool],
});
console.log(finalMessage.content);
```
**When to use:**
- Automated tool execution
- AI agents with function calling
- Complex multi-step workflows
### Pattern 9: Streaming Tool Execution
```typescript
const runner = anthropic.beta.messages.toolRunner({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1000,
messages: [{ role: 'user', content: 'Check weather and calculate travel time' }],
tools: [weatherTool, travelTimeTool],
stream: true,
});
for await (const messageStream of runner) {
for await (const event of messageStream) {
console.log('Event:', event);
}
console.log('Message:', await messageStream.finalMessage());
}
```
**When to use:**
- Real-time tool execution feedback
- Multi-tool workflows
- Interactive AI agents
## Error Handling Patterns
### Pattern 10: Comprehensive Error Handling
```typescript
async function createMessage(prompt: string) {
try {
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
messages: [{ role: 'user', content: prompt }],
});
return message;
} catch (error) {
if (error instanceof Anthropic.APIError) {
console.error('API Error:', {
status: error.status,
name: error.name,
message: error.message,
headers: error.headers,
});
// Handle specific errors
if (error.status === 429) {
// Rate limit - implement backoff
console.log('Rate limited, waiting...');
await new Promise(resolve => setTimeout(resolve, 60000));
return createMessage(prompt); // Retry
} else if (error.status === 401) {
throw new Error('Invalid API key');
} else if (error.status === 400) {
throw new Error(`Bad request: ${error.message}`);
}
}
throw error;
}
}
```
**When to use:**
- Production applications
- Robust error recovery
- User-facing applications
### Pattern 11: Exponential Backoff Retry
```typescript
async function createWithRetry(
params: Anthropic.MessageCreateParams,
maxRetries = 3,
baseDelay = 1000
): Promise<Anthropic.Message> {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
return await anthropic.messages.create(params);
} catch (error) {
if (error instanceof Anthropic.APIError && error.status === 429) {
// Rate limit - exponential Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.