Receber por email
← Voltar para o catálogo

ai-provider-anthropic-sdk

Official Anthropic SDK patterns for TypeScript/Node.js — client setup, Messages API, streaming, tool use, vision, extended thinking, structured outputs, prompt caching, batch API, and production best practices

11estrelas
Atualizado há 7 meses

Ver no GitHub ↗ Licença: MIT

Como adicionar

/plugin marketplace add agents-inc/skills

O comando exato pode variar conforme o repositório. Confira o README no GitHub.

Para o autor da skill

Cole no README do seu repo

Mostra que sua skill está catalogada na Skillteca, gera backlink e tráfego rastreável.

[![Skillteca](https://www.skillteca.com.br/api/badge/ai-provider-anthropic-sdk/svg)](https://www.skillteca.com.br/skills/ai-provider-anthropic-sdk)

Alerta por categoria

Receba novas skills de Design e Frontend toda segunda

1 email curto, só com as skills novas de Design e Frontend. 4 minutos de leitura, sem spam, cancela com 1 clique.

Você confirma o email no primeiro envio. Sem spam. Cancela com 1 clique.

Ler descrição completa

Anthropic SDK Patterns

Quick Guide: Use the official @anthropic-ai/sdk package to interact with Claude models directly. Use client.messages.create() for single-turn and multi-turn conversations. Use client.messages.stream() for streaming with event-based consumption. max_tokens is always required. Content blocks are typed unions (text, tool_use, thinking). Use client.messages.parse() with zodOutputFormat() for structured outputs. Tool use requires a tool-result loop -- Claude returns tool_use blocks, you execute the tool and send back tool_result blocks. Extended thinking adds thinking content blocks before the response.

<critical_requirements>

CRITICAL: Before Using This Skill

All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering, import type, named constants)

(You MUST always provide max_tokens in every messages.create() / messages.stream() call -- it is required and has no default)

(You MUST handle the stop_reason field to detect end_turn, max_tokens, tool_use, and stop_sequence -- ignoring it causes silent truncation or broken tool loops)

(You MUST iterate over response.content blocks (not assume a single text block) -- responses can contain text, tool_use, and thinking blocks mixed together)

(You MUST handle errors using Anthropic.APIError and its subclasses -- never use bare catch blocks without error type checking)

(You MUST never hardcode API keys -- always use environment variables via process.env.ANTHROPIC_API_KEY)

</critical_requirements>

Auto-detection: Anthropic, @anthropic-ai/sdk, client.messages.create, client.messages.stream, client.messages.parse, client.messages.countTokens, client.messages.batches, ANTHROPIC_API_KEY, claude-sonnet, claude-opus, claude-haiku, ContentBlock, ToolUseBlock, tool_use, tool_result, thinking, budget_tokens, adaptive, cache_control, zodOutputFormat, betaZodTool, toolRunner

When to use:

  • Building applications that call Claude models directly (Opus, Sonnet, Haiku families)
  • Implementing streaming chat responses with event-based text accumulation
  • Using tool use / function calling where Claude decides which tools to invoke
  • Processing images, PDFs, or documents alongside text prompts
  • Enabling extended thinking for complex reasoning tasks
  • Extracting structured data from responses with Zod schema validation
  • Caching large system prompts or conversation prefixes for cost savings
  • Running batch jobs for high-volume, asynchronous processing
  • Counting tokens before sending requests for cost estimation

Key patterns covered:

  • Client initialization and configuration (retries, timeouts, API key)
  • Messages API (messages.create, system prompts, multi-turn conversations)
  • Streaming with .stream() helper and stream: true low-level SSE
  • Tool use / function calling (tools array, tool_use / tool_result content blocks)
  • Vision (base64 images, URL images, PDFs/documents)
  • Extended thinking (thinking config, budget_tokens, thinking content blocks)
  • Structured outputs (zodOutputFormat, messages.parse, output_config)
  • Prompt caching (cache_control: { type: "ephemeral" })
  • Batch API (messages.batches.create)
  • Token counting (messages.countTokens)
  • Error handling, retries, and production best practices

When NOT to use:

  • Multi-provider applications where you need to switch between multiple LLM providers -- use a unified provider SDK instead
  • React-specific chat UI hooks (useChat, useCompletion) -- use a framework-integrated AI SDK
  • When you need a higher-level agent framework -- consider the Claude Agent SDK (@anthropic-ai/claude-agent-sdk)

Examples Index

  • [Core: Setup & Configuration](examples/core.md) -- Client init, production config, error handling, token counting
  • [Streaming](examples/streaming.md) -- .stream() helper, stream: true SSE, event types, abort
  • [Tool Use / Function Calling](examples/tool-use.md) -- Tool definitions, tool loops, parallel tool calls, automated tool runner
  • [Vision & Documents](examples/vision-documents.md) -- Base64 images, URL images, PDFs, multi-modal
  • [Extended Thinking](examples/extended-thinking.md) -- Thinking config, streaming thinking, thinking with tool use
  • [Quick API Reference](reference.md) -- Model IDs, method signatures, error types, streaming events, content block types

<philosophy>

Philosophy

The official Anthropic SDK provides direct, typed access to the Claude API. It is auto-generated from Anthropic's API specification using Stainless, giving you the exact API surface that Anthropic documents with full TypeScript types.

Core principles:

  1. Content blocks, not strings -- Responses are arrays of typed content blocks (TextBlock, ToolUseBlock, ThinkingBlock), not plain strings. Always iterate over response.content and switch on block.type.
  2. Explicit resource limits -- max_tokens is always required. There is no default. The API will reject requests without it.
  3. Tool use is a conversation loop -- When stop_reason === "tool_use", Claude is requesting you execute a tool. You must send the result back as a tool_result content block to continue the conversation.
  4. Built-in resilience -- The SDK retries 2 times by default on 429, 409, 408, 529, and 5xx errors with exponential backoff.
  5. Streaming as a first-class pattern -- Use .stream() for an event-based API with .on("text", ...), or stream: true for raw SSE iteration.

When to use the Anthropic SDK directly:

  • You only use Claude models and want the simplest, most direct integration
  • You need access to Anthropic-specific features (extended thinking, prompt caching, batch API)
  • You want minimal dependencies and zero abstraction overhead
  • You need the latest API features on day one

When NOT to use:

  • You need to switch between multiple LLM providers -- use a unified provider SDK
  • You want React-specific chat UI hooks -- use a framework-integrated AI SDK
  • You want a higher-level agent framework -- consider the Claude Agent SDK

</philosophy>

<patterns>

Core Patterns

Pattern 1: Client Setup

Initialize the Anthropic client. It auto-reads ANTHROPIC_API_KEY from the environment.

// lib/anthropic.ts -- basic setup
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
export { client };
// lib/anthropic.ts -- production configuration
const TIMEOUT_MS = 30_000;
const MAX_RETRIES = 3;
const client = new Anthropic({ timeout: TIMEOUT_MS, maxRetries: MAX_RETRIES });

Why good: Minimal setup, env var auto-detected, named constants for production settings

// BAD: Hardcoded API key
const client = new Anthropic({ apiKey: "sk-ant-api03-..." });

Why bad: Hardcoded keys get committed to version control, causing security breaches

See: [examples/core.md](examples/core.md) for per-request overrides, error handling patterns, token counting

Pattern 2: Messages API

All interactions use client.messages.create(). max_tokens is always required.

const MAX_TOKENS = 1024;

const message = await client.messages.create({
  model: "claude-sonnet-4-6",
  max_tokens: MAX_TOKENS,
  system: "You are a helpful coding assistant.",
  messages: [{ role: "user", content: "Explain TypeScript generics." }],
});

// Response is an array of content blocks -- iterate, don't assume
for (const block of message.content) {
  if (block.type === "text") {
    console.log(block.text);
  }
}

Why good: Named constant for max_tokens, system prompt separated from messages, content blocks iterated

// BAD: Assuming content is a single text string
const text = message.content[0].text; // Crashes if block is tool_use or thinking

Why bad: Content can contain multiple blocks of different types -- direct

Compartilhar X LinkedIn