or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

batches.mdbeta-features.mdclient.mdcompletions.mderrors.mdfiles.mdindex.mdmessages.mdmodels.mdskills.mdstreaming.mdtools.mdtypes.md
tile.json

tessl/npm-anthropic-ai--sdk

The official TypeScript library for the Anthropic API, providing a comprehensive client for interacting with Claude AI models.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@anthropic-ai/sdk@0.70.x

To install, run

npx @tessl/cli install tessl/npm-anthropic-ai--sdk@0.70.0

index.mddocs/

Anthropic TypeScript SDK

The official TypeScript library for the Anthropic API, providing comprehensive access to Claude AI models. This SDK offers strongly-typed interfaces, streaming support, tool execution helpers, batch processing, and extensive beta features including code execution, computer use, and memory management.

Package Information

  • Package Name: @anthropic-ai/sdk
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @anthropic-ai/sdk

Core Imports

import Anthropic from '@anthropic-ai/sdk';

CommonJS:

const Anthropic = require('@anthropic-ai/sdk');

Basic Usage

import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY, // This is the default
});

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);

Architecture

The SDK is organized around several key components:

  • Client: Main Anthropic class that initializes API access and provides resource endpoints
  • Resources: API endpoint groups (messages, models, beta)
  • Streaming: Enhanced streaming with MessageStream helper providing event-based API and message accumulation
  • Tools: Helper functions for defining and automatically executing tools using Zod or JSON Schema
  • Pagination: Automatic pagination support for list endpoints with async iteration
  • Error Handling: Comprehensive error class hierarchy for different HTTP status codes

Capabilities

Client Initialization

Create and configure the Anthropic API client.

class Anthropic {
  constructor(options?: ClientOptions);
}

interface ClientOptions {
  apiKey?: string | ((req: Request) => string) | null;
  authToken?: string | null;
  baseURL?: string | null;
  timeout?: number; // default: 600000 (10 minutes)
  maxRetries?: number; // default: 2
  fetchOptions?: RequestInit;
  fetch?: typeof fetch;
  defaultHeaders?: Record<string, string>;
  defaultQuery?: Record<string, string>;
  dangerouslyAllowBrowser?: boolean;
  logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'off';
  logger?: Logger;
}

Client Configuration

Text Completions API (Legacy)

Legacy text completion interface using the \n\nHuman: and \n\nAssistant: prompt format. This API is maintained for backwards compatibility, but the Messages API is recommended for new implementations.

client.completions.create(
  params: CompletionCreateParams
): APIPromise<Completion> | APIPromise<Stream<Completion>>;

interface Completion {
  id: string;
  completion: string;
  model: Model;
  stop_reason: string | null;
  type: 'completion';
}

Text Completions API

Messages API

Core conversational interface for interacting with Claude models. Supports both streaming and non-streaming requests, tool use, prompt caching, and extended thinking.

client.messages.create(
  params: MessageCreateParams
): APIPromise<Message> | APIPromise<Stream<MessageStreamEvent>>;

interface MessageCreateParams {
  model: string; // e.g., 'claude-sonnet-4-5-20250929'
  max_tokens: number;
  messages: MessageParam[];
  stream?: boolean;
  system?: string | SystemBlockParam[];
  temperature?: number;
  top_k?: number;
  top_p?: number;
  stop_sequences?: string[];
  metadata?: Metadata;
  tools?: Tool[];
  tool_choice?: ToolChoice;
}

interface MessageParam {
  role: 'user' | 'assistant';
  content: string | ContentBlockParam[];
}

interface Message {
  id: string;
  type: 'message';
  role: 'assistant';
  content: ContentBlock[];
  model: string;
  stop_reason: 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | 'server_tool_use' | null;
  stop_sequence: string | null;
  usage: Usage;
}

Messages API

Streaming

Enhanced streaming capabilities with event-based API, automatic message accumulation, and helper methods.

client.messages.stream(params: MessageStreamParams): MessageStream;

class MessageStream {
  on(event: string, listener: Function): this;
  once(event: string, listener: Function): this;
  off(event: string, listener: Function): this;
  emitted(event: string): Promise<any>;
  done(): Promise<void>;
  finalMessage(): Promise<Message>;
  finalText(): Promise<string>;
  abort(): void;
  toReadableStream(): ReadableStream;
}

Events: connect, streamEvent, text, inputJson, citation, thinking, contentBlock, message, finalMessage, error, abort, end

Streaming

Tool Use

Define and execute tools (function calling) with automatic validation and execution loop.

// Tool definition
interface Tool {
  name: string;
  description: string;
  input_schema: {
    type: 'object';
    properties: Record<string, any>;
    required?: string[];
  };
}

// Tool helpers with Zod
import { betaZodTool } from '@anthropic-ai/sdk/helpers/zod';

function betaZodTool<Schema extends ZodType>(options: {
  name: string;
  inputSchema: Schema;
  description: string;
  run: (input: z.infer<Schema>) => Promise<string | BetaToolResultContentBlockParam[]> | string | BetaToolResultContentBlockParam[];
}): BetaRunnableTool<z.infer<Schema>>;

// Automatic tool execution
client.beta.messages.toolRunner(
  params: BetaToolRunnerParams
): BetaToolRunner;

Tool Use and Tool Helpers

Message Batches

Batch processing for multiple messages with asynchronous result retrieval.

client.messages.batches.create(
  params: MessageBatchCreateParams
): APIPromise<MessageBatch>;

client.messages.batches.list(
  params?: MessageBatchListParams
): MessageBatchesPage;

client.messages.batches.results(
  messageBatchID: string
): AsyncIterable<MessageBatchIndividualResponse>;

interface MessageBatch {
  id: string;
  type: 'message_batch';
  processing_status: 'in_progress' | 'canceling' | 'ended';
  request_counts: MessageBatchRequestCounts;
  ended_at: string | null;
  created_at: string;
  expires_at: string;
  archived_at: string | null;
  cancel_initiated_at: string | null;
  results_url: string | null;
}

Message Batches

Models API

Retrieve information about available Claude models.

client.models.retrieve(
  modelID: string,
  params?: ModelRetrieveParams
): APIPromise<ModelInfo>;

client.models.list(
  params?: ModelListParams
): ModelInfosPage;

interface ModelInfo {
  type: 'model';
  id: string;
  display_name: string;
  created_at: string;
}

Models API

Files API (Beta)

Upload, manage, and download files for use with file-based tools and document processing.

client.beta.files.upload(
  params: FileUploadParams
): APIPromise<FileMetadata>;

client.beta.files.list(
  params?: FileListParams
): FileMetadataPage;

client.beta.files.download(
  fileID: string,
  params?: FileDownloadParams
): APIPromise<Response>;

interface FileMetadata {
  id: string;
  type: 'file';
  filename: string;
  size: number;
  created_at: string;
}

Files API

Skills API (Beta)

Create and manage custom skills for extended capabilities.

client.beta.skills.create(
  params: SkillCreateParams
): APIPromise<SkillCreateResponse>;

client.beta.skills.list(
  params?: SkillListParams
): SkillListResponsesPageCursor;

client.beta.skills.retrieve(
  skillID: string,
  params?: SkillRetrieveParams
): APIPromise<SkillRetrieveResponse>;

Skills API

Beta Features

Access experimental and advanced features through the beta namespace.

Beta features include:

  • Code Execution: Execute Python code in sandboxed environments
  • Computer Use: Control computer interactions (bash, text editor, computer use tools)
  • Extended Thinking: Access full thinking traces from Claude
  • MCP (Model Context Protocol): External tool integration
  • Memory Tools: Persistent memory across conversations
  • Web Search & Fetch: Search the web and fetch content
  • Context Management: Advanced context window management
  • Structured Outputs: JSON output with automatic parsing
// Access beta features
client.beta.messages.create(params: {
  ...MessageCreateParams,
  betas: AnthropicBeta[];
});

type AnthropicBeta =
  | 'message-batches-2024-09-24'
  | 'prompt-caching-2024-07-31'
  | 'computer-use-2025-01-24'
  | 'code-execution-2025-05-22'
  | 'files-api-2025-04-14'
  | 'mcp-client-2025-04-04'
  | 'skills-2025-10-02'
  | 'context-management-2025-06-27'
  // ... and more
  ;

Beta Features

Error Handling

Comprehensive error classes for different failure scenarios.

class AnthropicError extends Error {}
class APIError extends AnthropicError {
  readonly status: number;
  readonly headers: Headers;
  readonly error: any;
  readonly requestID: string | null;
}
class BadRequestError extends APIError {} // 400
class AuthenticationError extends APIError {} // 401
class PermissionDeniedError extends APIError {} // 403
class NotFoundError extends APIError {} // 404
class UnprocessableEntityError extends APIError {} // 422
class RateLimitError extends APIError {} // 429
class InternalServerError extends APIError {} // 5xx
class APIConnectionError extends AnthropicError {}
class APIConnectionTimeoutError extends APIConnectionError {}
class APIUserAbortError extends AnthropicError {}

Error Handling

Pagination

Automatic pagination support for list endpoints with async iteration.

// Auto-pagination with async iteration
for await (const item of client.messages.batches.list({ limit: 20 })) {
  console.log(item);
}

// Manual pagination
let page = await client.messages.batches.list({ limit: 20 });
while (page.hasNextPage()) {
  page = await page.getNextPage();
  // process page.data
}

// Page interface
interface Page<Item> {
  data: Item[];
  has_more: boolean;
  first_id: string | null;
  last_id: string | null;
  hasNextPage(): boolean;
  getNextPage(): Promise<this>;
}

File Uploads

Convert various input types to uploadable files.

import { toFile } from '@anthropic-ai/sdk';

function toFile(
  value: File | Blob | Response | ReadStream | Buffer | Uint8Array | ArrayBuffer,
  name?: string,
  options?: { type?: string }
): Promise<FileLike>;

Request Metadata

Access response headers and request IDs for debugging.

// Get response metadata
const { data, response, request_id } = await client.messages
  .create(params)
  .withResponse();

console.log(request_id); // For support requests

// Get raw response
const response = await client.messages.create(params).asResponse();

Types Reference

For complete type definitions including all content blocks, tool types, streaming events, and beta-specific types, see:

Types Reference