claude-api
This skill provides comprehensive knowledge for working with the Anthropic Messages API (Claude API). It should be used when integrating Claude models into applications, implementing streaming responses, enabling prompt caching for cost savings, adding tool use (function calling), processing images with vision capabilities, or using extended thinking mode. Use when building chatbots, AI assistants, content generation tools, or any application requiring Claude's language understanding. Covers both server-side implementations (Node.js, Cloudflare Workers, Next.js) and direct API access. Keywords: claude api, anthropic api, messages api, @anthropic-ai/sdk, claude streaming, prompt caching, tool use, vision, extended thinking, claude 3.5 sonnet, claude 3.7 sonnet, claude sonnet 4, function calling, SSE, rate limits, 429 errors
What this skill does
# Claude API (Anthropic Messages API) **Status**: Production Ready **Last Updated**: 2025-10-25 **Dependencies**: None (standalone API skill) **Latest Versions**: @anthropic-ai/[email protected] --- ## Quick Start (5 Minutes) ### 1. Get API Key ```bash # Sign up at https://console.anthropic.com/ # Navigate to API Keys section # Create new key and save securely export ANTHROPIC_API_KEY="sk-ant-..." ``` **Why this matters:** - API key required for all requests - Keep secure (never commit to git) - Use environment variables ### 2. Install SDK (Node.js) ```bash npm install @anthropic-ai/sdk ``` ```typescript import Anthropic from '@anthropic-ai/sdk'; const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY, }); 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[0].text); ``` **CRITICAL:** - Always use server-side (never expose API key in client code) - Set `max_tokens` (required parameter) - Model names are versioned (use latest stable) ### 3. Or Use Direct API (Cloudflare Workers) ```typescript // No SDK needed - use fetch() const response = await fetch('https://api.anthropic.com/v1/messages', { method: 'POST', headers: { 'x-api-key': env.ANTHROPIC_API_KEY, 'anthropic-version': '2023-06-01', 'content-type': 'application/json', }, body: JSON.stringify({ model: 'claude-sonnet-4-5-20250929', max_tokens: 1024, messages: [{ role: 'user', content: 'Hello!' }], }), }); const data = await response.json(); ``` --- ## The Complete Claude API Reference ## Table of Contents 1. [Core API](#core-api-messages-api) 2. [Streaming Responses](#streaming-responses-sse) 3. [Prompt Caching](#prompt-caching--90-cost-savings) 4. [Tool Use (Function Calling)](#tool-use-function-calling) 5. [Vision (Image Understanding)](#vision-image-understanding) 6. [Extended Thinking Mode](#extended-thinking-mode) 7. [Rate Limits](#rate-limits) 8. [Error Handling](#error-handling) 9. [Platform Integrations](#platform-integrations) 10. [Known Issues](#known-issues-prevention) --- ## Core API (Messages API) ### Available Models (October 2025) | Model | ID | Context | Best For | Cost (per MTok) | |-------|-----|---------|----------|-----------------| | **Claude Sonnet 4.5** | claude-sonnet-4-5-20250929 | 200k tokens | Balanced performance | $3/$15 (in/out) | | **Claude 3.7 Sonnet** | claude-3-7-sonnet-20250228 | 2M tokens | Extended thinking | $3/$15 | | **Claude Opus 4** | claude-opus-4-20250514 | 200k tokens | Highest capability | $15/$75 | | **Claude 3.5 Haiku** | claude-3-5-haiku-20241022 | 200k tokens | Fast, cost-effective | $1/$5 | ### Basic Message Creation ```typescript import Anthropic from '@anthropic-ai/sdk'; const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY, }); const message = await anthropic.messages.create({ model: 'claude-sonnet-4-5-20250929', max_tokens: 1024, messages: [ { role: 'user', content: 'Explain quantum computing in simple terms' } ], }); console.log(message.content[0].text); ``` ### Multi-Turn Conversations ```typescript const 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?' }, ]; const message = await anthropic.messages.create({ model: 'claude-sonnet-4-5-20250929', max_tokens: 1024, messages, }); ``` ### System Prompts ```typescript const message = await anthropic.messages.create({ model: 'claude-sonnet-4-5-20250929', max_tokens: 1024, system: 'You are a helpful Python coding assistant. Always provide type hints and docstrings.', messages: [ { role: 'user', content: 'Write a function to sort a list' } ], }); ``` **CRITICAL:** - System prompt MUST come before messages array - System prompt sets behavior for entire conversation - Can be 1-10k tokens (affects context window) --- ## Streaming Responses (SSE) ### Using SDK Stream Helper ```typescript const stream = anthropic.messages.stream({ model: 'claude-sonnet-4-5-20250929', max_tokens: 1024, messages: [{ role: 'user', content: 'Write a short story' }], }); // Method 1: Event listeners stream .on('text', (text) => { process.stdout.write(text); }) .on('message', (message) => { console.log('\n\nFinal message:', message); }) .on('error', (error) => { console.error('Stream error:', error); }); // Wait for completion await stream.finalMessage(); ``` ### Streaming with Manual Iteration ```typescript const stream = await anthropic.messages.create({ model: 'claude-sonnet-4-5-20250929', max_tokens: 1024, messages: [{ role: 'user', content: 'Explain AI' }], 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); } } ``` ### Streaming Event Types | Event | When | Use Case | |-------|------|----------| | `message_start` | Message begins | Initialize UI | | `content_block_start` | New content block | Track blocks | | `content_block_delta` | Text chunk received | Display text | | `content_block_stop` | Block complete | Format block | | `message_delta` | Metadata update | Update stop reason | | `message_stop` | Message complete | Finalize UI | ### Cloudflare Workers Streaming ```typescript export default { async fetch(request: Request, env: Env): Promise<Response> { const response = await fetch('https://api.anthropic.com/v1/messages', { method: 'POST', headers: { 'x-api-key': env.ANTHROPIC_API_KEY, 'anthropic-version': '2023-06-01', 'content-type': 'application/json', }, body: JSON.stringify({ model: 'claude-sonnet-4-5-20250929', max_tokens: 1024, messages: [{ role: 'user', content: 'Hello!' }], stream: true, }), }); // Return SSE stream directly return new Response(response.body, { headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', }, }); }, }; ``` **CRITICAL:** - Errors can occur AFTER initial 200 response - Always implement error event handlers - Use `stream.abort()` to cancel - Set proper Content-Type headers --- ## Prompt Caching (⭐ 90% Cost Savings) ### Overview Prompt caching allows you to cache frequently used context (system prompts, documents, codebases) to: - **Reduce costs by 90%** (cache reads = 10% of input token price) - **Reduce latency by 85%** (time to first token) - **Cache lifetime**: 5 minutes (default) or 1 hour (configurable) ### Minimum Requirements - **Claude 3.5 Sonnet**: 1,024 tokens minimum - **Claude 3.5 Haiku**: 2,048 tokens minimum ### Basic Prompt Caching ```typescript const message = await anthropic.messages.create({ model: 'claude-sonnet-4-5-20250929', max_tokens: 1024, system: [ { type: 'text', text: 'You are an AI assistant analyzing the following codebase...', }, { type: 'text', text: LARGE_CODEBASE_CONTENT, // 50k tokens cache_control: { type: 'ephemeral' }, }, ], messages: [ { role: 'user', content: 'Explain the auth module' } ], }); // Check cache usage console.log('Cache read tokens:', message.usage.cache_read_input_tokens); console.log('Cache creation tokens:', message.usage.cache_creation_input_tokens); ``` ### Caching in Messages ```typescript const message = await anthropic.messages.create({ model: 'claude-sonnet-4-5-20250929', max_tokens: 1024, messages: [ { role: 'user', content: [ { type: 'text', text: 'Analyze this documentation:', }, { type: 'text', text: LONG_DOCUMENTATION, // 20k tokens cache_control: { type: 'eph
Related in Web Dev
generating-lwc-components
IncludedLightning Web Components with PICKLES methodology and 165-point scoring. Use this skill when the user creates or edits LWC components, builds wire service patterns, or writes Jest tests for LWC. TRIGGER when: user creates/edits LWC components, touches lwc/**/*.js, .html, .css, .js-meta.xml files, or asks about wire service, SLDS, or Jest LWC tests. DO NOT TRIGGER when: Apex classes (use generating-apex), Aura components, or Visualforce.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Set up queries with useQuery, mutations with useMutation, configure QueryClient caching strategies, implement optimistic updates, and handle infinite scroll with useInfiniteQuery. Use when: setting up data fetching in React projects, migrating from v4 to v5, or fixing object syntax required errors, query callbacks removed issues, cacheTime renamed to gcTime, isPending vs isLoading confusion, keepPreviousData removed problems.
document-processor-api
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
nutrient-document-processing
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Covers useMutationState, simplified optimistic updates, throwOnError, network mode (offline/PWA), and infiniteQueryOptions. Use when setting up data fetching, fixing v4→v5 migration errors (object syntax, gcTime, isPending, keepPreviousData), or debugging SSR/hydration issues with streaming server components.
accelint-nextjs-best-practices
IncludedNext.js performance optimization and best practices. Use when writing Next.js code (App Router or Pages Router); implementing Server Components, Server Actions, or API routes; optimizing RSC serialization, data fetching, or server-side rendering; reviewing Next.js code for performance issues; fixing authentication in Server Actions; or implementing Suspense boundaries, parallel data fetching, or request deduplication.