claude-api
Build with Claude Messages API using structured outputs (v0.69.0+, Nov 2025) for guaranteed JSON schema validation. Covers prompt caching (90% savings), streaming SSE, tool use, model deprecations (3.5/3.7 retired Oct 2025). Use when: building chatbots/agents with validated JSON responses, or troubleshooting rate_limit_error, structured output validation, prompt caching not activating, streaming SSE parsing.
What this skill does
# Claude API - Structured Outputs & Error Prevention Guide **Package**: @anthropic-ai/[email protected] (Nov 20, 2025) **Breaking Changes**: Oct 2025 - Claude 3.5/3.7 models retired, Nov 2025 - Structured outputs beta **Last Updated**: 2025-11-22 --- ## What's New in v0.69.0+ (Nov 2025) **Major Features:** ### 1. Structured Outputs (v0.69.0, Nov 14, 2025) - CRITICAL ⭐ **Guaranteed JSON schema conformance** - Claude's responses strictly follow your JSON schema with two modes: **JSON Outputs (`output_format`)** - For data extraction and formatting: ```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: 'Extract contact info: John Doe, [email protected], 555-1234' }], betas: ['structured-outputs-2025-11-13'], output_format: { type: 'json_schema', json_schema: { name: 'Contact', strict: true, schema: { type: 'object', properties: { name: { type: 'string' }, email: { type: 'string' }, phone: { type: 'string' } }, required: ['name', 'email', 'phone'], additionalProperties: false } } } }); // Guaranteed valid JSON matching schema const contact = JSON.parse(message.content[0].text); console.log(contact.name); // "John Doe" ``` **Strict Tool Use (`strict: true`)** - For validated function parameters: ```typescript const message = await anthropic.messages.create({ model: 'claude-sonnet-4-5-20250929', max_tokens: 1024, messages: [{ role: 'user', content: 'Get weather for San Francisco' }], betas: ['structured-outputs-2025-11-13'], tools: [{ name: 'get_weather', description: 'Get current weather', input_schema: { type: 'object', properties: { location: { type: 'string' }, unit: { type: 'string', enum: ['celsius', 'fahrenheit'] } }, required: ['location'], additionalProperties: false }, strict: true // ← Guarantees schema compliance }] }); ``` **Requirements:** - **Beta header**: `structured-outputs-2025-11-13` (via `betas` array) - **Models**: Claude Sonnet 4.5, Claude Opus 4.1 only - **SDK**: v0.69.0+ required **Limitations:** - ❌ No recursive schemas - ❌ No numerical constraints (`minimum`, `maximum`) - ❌ Limited regex support (no backreferences/lookahead) - ❌ Incompatible with citations and message prefilling - ⚠️ Grammar compilation adds latency on first request (cached 24hrs) **When to Use:** - Data extraction from unstructured text - API response formatting - Agentic workflows requiring validated tool inputs - Eliminating JSON parse errors ### 2. Model Changes (Oct 2025) - BREAKING **Retired (return errors):** - ❌ Claude 3.5 Sonnet (all versions) - ❌ Claude 3.7 Sonnet - DEPRECATED (Oct 28, 2025) **Active Models (Nov 2025):** | Model | ID | Context | Best For | Cost (per MTok) | |-------|-----|---------|----------|-----------------| | **Claude Sonnet 4.5** | claude-sonnet-4-5-20250929 | 200k | Balanced performance | $3/$15 (in/out) | | **Claude Opus 4** | claude-opus-4-20250514 | 200k | Highest capability | $15/$75 | | **Claude Haiku 4.5** | claude-3-5-haiku-20241022 | 200k | Near-frontier, fast | $1/$5 | ### 3. Context Management (Oct 28, 2025) **Clear Thinking Blocks** - Automatic thinking block cleanup: ```typescript const message = await anthropic.messages.create({ model: 'claude-sonnet-4-5-20250929', max_tokens: 4096, messages: [{ role: 'user', content: 'Solve complex problem' }], betas: ['clear_thinking_20251015'] }); // Thinking blocks automatically managed ``` ### 4. Agent Skills API (Oct 16, 2025) Pre-built skills for Office files (PowerPoint, Excel, Word, PDF): ```typescript const message = await anthropic.messages.create({ model: 'claude-sonnet-4-5-20250929', max_tokens: 1024, messages: [{ role: 'user', content: 'Analyze this spreadsheet' }], betas: ['skills-2025-10-02'], // Requires code execution tool enabled }); ``` 📚 **Docs**: https://platform.claude.com/docs/en/build-with-claude/structured-outputs --- ## Streaming Responses (SSE) **CRITICAL Error Pattern** - Errors occur AFTER initial 200 response: ```typescript const stream = anthropic.messages.stream({ model: 'claude-sonnet-4-5-20250929', max_tokens: 1024, messages: [{ role: 'user', content: 'Hello' }], }); stream .on('error', (error) => { // Error can occur AFTER stream starts console.error('Stream error:', error); // Implement fallback or retry logic }) .on('abort', (error) => { console.warn('Stream aborted:', error); }); ``` **Why this matters**: Unlike regular HTTP errors, SSE errors happen mid-stream after 200 OK, requiring error event listeners --- ## Prompt Caching (⭐ 90% Cost Savings) **CRITICAL Rule** - `cache_control` MUST be on LAST block: ```typescript const message = await anthropic.messages.create({ model: 'claude-sonnet-4-5-20250929', max_tokens: 1024, system: [ { type: 'text', text: 'System instructions...', }, { type: 'text', text: LARGE_CODEBASE, // 50k tokens cache_control: { type: 'ephemeral' }, // ← MUST be on LAST block }, ], messages: [{ role: 'user', content: 'Explain auth module' }], }); // Monitor cache usage console.log('Cache reads:', message.usage.cache_read_input_tokens); console.log('Cache writes:', message.usage.cache_creation_input_tokens); ``` **Minimum requirements:** - Claude Sonnet 4.5: 1,024 tokens minimum - Claude Haiku 4.5: 2,048 tokens minimum - 5-minute TTL (refreshes on each use) - Cache shared only with IDENTICAL content --- ## Tool Use (Function Calling) **CRITICAL Patterns:** **Strict Tool Use** (with structured outputs): ```typescript const message = await anthropic.messages.create({ model: 'claude-sonnet-4-5-20250929', max_tokens: 1024, betas: ['structured-outputs-2025-11-13'], tools: [{ name: 'get_weather', description: 'Get weather data', input_schema: { type: 'object', properties: { location: { type: 'string' }, unit: { type: 'string', enum: ['celsius', 'fahrenheit'] } }, required: ['location'], additionalProperties: false }, strict: true // ← Guarantees schema compliance }], messages: [{ role: 'user', content: 'Weather in NYC?' }] }); ``` **Tool Result Pattern** - `tool_use_id` MUST match: ```typescript const toolResults = []; for (const block of response.content) { if (block.type === 'tool_use') { const result = await executeToolFunction(block.name, block.input); toolResults.push({ type: 'tool_result', tool_use_id: block.id, // ← MUST match tool_use block id content: JSON.stringify(result), }); } } messages.push({ role: 'user', content: toolResults, }); ``` **Error Handling** - Handle tool execution failures: ```typescript try { const result = await executeToolFunction(block.name, block.input); toolResults.push({ type: 'tool_result', tool_use_id: block.id, content: JSON.stringify(result), }); } catch (error) { // Return error to Claude for handling toolResults.push({ type: 'tool_result', tool_use_id: block.id, is_error: true, content: `Tool execution failed: ${error.message}`, }); } ``` --- ## Vision (Image Understanding) **CRITICAL Rules:** - **Formats**: JPEG, PNG, WebP, GIF (non-animated) - **Max size**: 5MB per image - **Base64 overhead**: ~33% size increase - **Context impact**: Images count toward token limit - **Caching**: Consider for repeated image analysis **Format validation** - Check before encoding: ```typescript const validFormats = ['image/jpeg', 'image/png', 'image/webp', 'image/gif']; if (!validFormats.includes(mimeType)) { throw new Error(`Unsupported format: ${mimeType}`); } ``` --- ## Extended Thinking Mod
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.