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…
Об этом скилле
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
# Install the SDK
npm install @anthropic-ai/sdk
# Or with yarn
yarn add @anthropic-ai/sdk
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
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
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
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
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
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
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
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',
Установить claude-sdk-integration-patterns в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл 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
Как установить скилл claude-sdk-integration-patterns?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл claude-sdk-integration-patterns запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic