claude-api
Anthropic Messages API (Claude API) for integrations, streaming, prompt caching, tool use, vision. Use for chatbots, assistants, or encountering rate limits, 429 errors.
What this skill does
# Claude API (Anthropic Messages API) **Status**: Production Ready | **SDK**: @anthropic-ai/[email protected] --- ## Quick Start (5 Minutes) ### Node.js ```typescript import Anthropic from '@anthropic-ai/sdk'; const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY, }); const message = await client.messages.create({ model: 'claude-sonnet-4-5-20250929', max_tokens: 1024, messages: [ { role: 'user', content: 'Hello, Claude!' }, ], }); console.log(message.content[0].text); ``` ### Cloudflare Workers ```typescript 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(); console.log(data.content[0].text); ``` **Load `references/setup-guide.md` for complete setup with streaming, caching, and tools.** --- ## Critical Rules ### Always Do ✅ 1. **Use environment variables** for API keys (NEVER hardcode) 2. **Set max_tokens** explicitly (required parameter) 3. **Pin model version** (`claude-sonnet-4-5-20250929`, not `claude-3-5-sonnet-latest`) 4. **Enable prompt caching** for repeated content (90% cost savings) 5. **Stream long responses** (`stream: true`) for better UX 6. **Handle errors** - Implement retry logic for 429, 529 errors 7. **Validate inputs** - Sanitize user messages before sending 8. **Monitor costs** - Track token usage 9. **Set timeouts** - Prevent hanging requests 10. **Use tool use properly** - Return tool_result in follow-up message ### Never Do ❌ 1. **Never expose API key** in client-side code 2. **Never skip max_tokens** - API will error without it 3. **Never ignore stop_reason** - Check for `tool_use`, `end_turn`, `max_tokens` 4. **Never assume single content block** - `content` is an array 5. **Never use outdated models** - Pin to specific version 6. **Never skip error handling** - API calls can fail 7. **Never mix message roles** - Alternate user/assistant correctly 8. **Never ignore rate limits** - Implement exponential backoff 9. **Never store API keys** in logs or databases 10. **Never skip input validation** - Prevent injection attacks --- ## Top 3 Errors (Prevent 80% of Issues) ### Error #1: Rate Limit 429 **Symptom**: `429 Too Many Requests: Number of request tokens has exceeded your per-minute rate limit` **Solution**: Implement exponential backoff with retry-after header ```typescript async function handleRateLimit(requestFn, maxRetries = 3) { for (let attempt = 0; attempt < maxRetries; attempt++) { try { return await requestFn(); } catch (error) { if (error.status === 429) { const retryAfter = error.response?.headers?.['retry-after']; const delay = retryAfter ? parseInt(retryAfter) * 1000 : 1000 * Math.pow(2, attempt); await new Promise(resolve => setTimeout(resolve, delay)); } else { throw error; } } } } ``` **Prevention**: Monitor rate limit headers, upgrade tier, implement backoff --- ### Error #2: Prompt Caching Not Activating **Symptom**: High costs despite `cache_control` blocks, `cache_read_input_tokens: 0` **Solution**: Place `cache_control` on LAST block with >= 1024 tokens ```typescript // ❌ Wrong - cache_control not at end { type: 'text', text: DOCUMENT, cache_control: { type: 'ephemeral' }, // Wrong position }, { type: 'text', text: 'Additional text', } // ✅ Correct - cache_control at end { type: 'text', text: DOCUMENT + '\n\nAdditional text', cache_control: { type: 'ephemeral' }, // Correct position } ``` **Prevention**: Ensure content >= 1024 tokens, keep cached content identical, monitor usage **Load `references/prompt-caching-guide.md` for complete caching strategy.** --- ### Error #3: Tool Use Response Format Errors **Symptom**: `invalid_request_error: tools[0].input_schema is invalid` **Solution**: Valid tool schema with proper JSON Schema ```typescript // ✅ Valid tool schema { name: 'get_weather', description: 'Get current weather', input_schema: { type: 'object', // Must be 'object' properties: { location: { type: 'string', // Valid JSON Schema types description: 'City' // Optional but recommended } }, required: ['location'] // List required fields } } // ✅ Valid tool result { type: 'tool_result', tool_use_id: block.id, // Must match tool_use id content: JSON.stringify(result) // Convert to string } ``` **Prevention**: Validate schemas, match tool_use_id exactly, stringify results **Load `references/tool-use-patterns.md` + `references/top-errors.md` for all 12 errors.** --- ## Common Use Cases (Quick Patterns) ### Streaming Responses ```typescript const stream = await client.messages.stream({ model: 'claude-sonnet-4-5-20250929', max_tokens: 1024, messages: [{ role: 'user', content: 'Write a story.' }], }); for await (const event of stream) { if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') { process.stdout.write(event.delta.text); } } ``` **Load**: `templates/streaming-chat.ts` --- ### Prompt Caching (90% Cost Savings) ```typescript const message = await client.messages.create({ model: 'claude-sonnet-4-5-20250929', max_tokens: 1024, system: [ { type: 'text', text: 'Long system prompt...', cache_control: { type: 'ephemeral' }, }, ], messages: [{ role: 'user', content: 'Question?' }], }); ``` **Cache lasts 5 minutes, 90% savings on cached tokens** **Load**: `references/prompt-caching-guide.md` + `templates/prompt-caching.ts` --- ### Tool Use (Function Calling) ```typescript const message = await client.messages.create({ model: 'claude-sonnet-4-5-20250929', max_tokens: 1024, tools: [{ name: 'get_weather', description: 'Get weather for a location', input_schema: { type: 'object', properties: { location: { type: 'string' } }, required: ['location'], }, }], messages: [{ role: 'user', content: 'Weather in SF?' }], }); if (message.stop_reason === 'tool_use') { const toolUse = message.content.find(b => b.type === 'tool_use'); // Execute tool and send result back... } ``` **Load**: `references/tool-use-patterns.md` + `templates/tool-use-basic.ts` --- ### Vision (Image Understanding) ```typescript const message = await client.messages.create({ model: 'claude-sonnet-4-5-20250929', max_tokens: 1024, messages: [{ role: 'user', content: [ { type: 'image', source: { type: 'base64', media_type: 'image/jpeg', data: base64Image, }, }, { type: 'text', text: 'What is in this image?' }, ], }], }); ``` **Supports**: JPEG, PNG, WebP, GIF (max 5MB) **Load**: `references/vision-capabilities.md` + `templates/vision-image.ts` --- ### Extended Thinking Mode ```typescript const message = await client.messages.create({ model: 'claude-sonnet-4-5-20250929', max_tokens: 4096, thinking: { type: 'enabled', budget_tokens: 2000, }, messages: [{ role: 'user', content: 'Solve complex problem...' }], }); const thinking = message.content.find(b => b.type === 'thinking')?.thinking; const answer = message.content.find(b => b.type === 'text')?.text; ``` **Load**: `templates/extended-thinking.ts` --- ## Model Versions (Current) **Latest models:** - `claude-sonnet-4-5-20250929` - Recommended (best performance) - `claude-sonnet-4-20250514` - Stable version - `claude-3-7-sonnet-20250219` - Previous generation - `claude-3-5-sonnet-20241022` - Legacy **Always pin to specific version** (not `-latest` suffix) --- ## When to Load References ### Load `references/setup-guide.md` when: - First-time Claude API user
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.