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.
npm install @anthropic-ai/sdkimport Anthropic from '@anthropic-ai/sdk';CommonJS:
const Anthropic = require('@anthropic-ai/sdk');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);The SDK is organized around several key components:
Anthropic class that initializes API access and provides resource endpointsmessages, models, beta)MessageStream helper providing event-based API and message accumulationCreate 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;
}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';
}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;
}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
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;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;
}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;
}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;
}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>;Access experimental and advanced features through the beta namespace.
Beta features include:
// 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
;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 {}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>;
}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>;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();For complete type definitions including all content blocks, tool types, streaming events, and beta-specific types, see: