- Spec files
npm-anthropic-ai--sdk
Describes: pkg:npm/@anthropic-ai/sdk@0.61.x
- Description
- The official TypeScript library for the Anthropic API providing comprehensive client functionality for Claude AI models.
- Author
- tessl
- Last updated
client-configuration.md docs/
1# Client Configuration23The Anthropic SDK client provides comprehensive configuration options for authentication, request handling, retries, and environment-specific settings.45## Capabilities67### Client Initialization89Create and configure the main Anthropic client with authentication and request options.1011```typescript { .api }12/**13* Main Anthropic API client14*/15class Anthropic extends BaseAnthropic {16constructor(options?: ClientOptions);1718/** Text completions API (legacy) */19completions: Completions;20/** Messages API (primary interface) */21messages: Messages;22/** Models information API */23models: Models;24/** Beta features API */25beta: Beta;26}2728interface ClientOptions {29/** API key for authentication (defaults to ANTHROPIC_API_KEY env var) */30apiKey?: string | null;31/** Auth token for authentication (defaults to ANTHROPIC_AUTH_TOKEN env var) */32authToken?: string | null;33/** Base URL override (defaults to ANTHROPIC_BASE_URL env var) */34baseURL?: string | null;35/** Request timeout in milliseconds */36timeout?: number;37/** Maximum number of retry attempts */38maxRetries?: number;39/** Custom fetch implementation */40fetch?: Fetch;41/** Additional fetch options for all requests */42fetchOptions?: RequestInit;43/** Allow usage in browser environments */44dangerouslyAllowBrowser?: boolean;45/** HTTP agent for Node.js environments */46httpAgent?: Agent;47/** Custom logger instance */48logger?: Logger;49/** Logging level */50logLevel?: LogLevel;51}52```5354**Usage Examples:**5556```typescript57import Anthropic from "@anthropic-ai/sdk";5859// Basic initialization with API key60const client = new Anthropic({61apiKey: "your-api-key",62});6364// Environment variable (recommended)65const client = new Anthropic(); // Uses ANTHROPIC_API_KEY env var6667// Custom configuration68const client = new Anthropic({69apiKey: process.env.ANTHROPIC_API_KEY,70baseURL: "https://api.anthropic.com",71timeout: 30000, // 30 seconds72maxRetries: 3,73});7475// Browser usage (requires explicit opt-in)76const browserClient = new Anthropic({77apiKey: "your-api-key",78dangerouslyAllowBrowser: true,79});80```8182### Authentication Options8384Configure authentication using API keys or auth tokens.8586```typescript { .api }87interface AuthenticationOptions {88/** Primary API key authentication */89apiKey?: string | null;90/** Alternative auth token authentication */91authToken?: string | null;92}93```9495**Usage Examples:**9697```typescript98// API key authentication (recommended)99const client = new Anthropic({100apiKey: process.env.ANTHROPIC_API_KEY,101});102103// Auth token authentication104const client = new Anthropic({105authToken: process.env.ANTHROPIC_AUTH_TOKEN,106});107108// Authentication automatically detected from environment109const client = new Anthropic(); // Checks ANTHROPIC_API_KEY then ANTHROPIC_AUTH_TOKEN110```111112### Request Configuration113114Configure HTTP request behavior including timeouts, retries, and custom fetch options.115116```typescript { .api }117interface RequestConfiguration {118/** Request timeout in milliseconds (default: 600000) */119timeout?: number;120/** Maximum retry attempts for failed requests (default: 2) */121maxRetries?: number;122/** Custom fetch function implementation */123fetch?: Fetch;124/** Additional RequestInit options for all requests */125fetchOptions?: RequestInit;126/** HTTP agent for Node.js (for proxy support, etc.) */127httpAgent?: Agent;128}129```130131**Usage Examples:**132133```typescript134import https from "https";135136// Custom timeout and retries137const client = new Anthropic({138timeout: 60000, // 60 seconds139maxRetries: 5,140});141142// Custom HTTP agent for proxy143const agent = new https.Agent({144keepAlive: true,145timeout: 30000,146});147148const client = new Anthropic({149httpAgent: agent,150});151152// Custom fetch with additional options153const client = new Anthropic({154fetchOptions: {155headers: {156"User-Agent": "MyApp/1.0",157},158},159});160```161162### Environment Configuration163164Configure the client for different deployment environments and base URLs.165166```typescript { .api }167interface EnvironmentConfiguration {168/** Custom base URL for API requests */169baseURL?: string | null;170/** Enable browser usage (disabled by default for security) */171dangerouslyAllowBrowser?: boolean;172}173```174175**Usage Examples:**176177```typescript178// Custom API endpoint179const client = new Anthropic({180baseURL: "https://api.example.com/anthropic/v1",181});182183// Browser environment (not recommended for production)184const browserClient = new Anthropic({185apiKey: publicApiKey, // Use with caution186dangerouslyAllowBrowser: true,187});188189// Development environment with local proxy190const devClient = new Anthropic({191baseURL: "http://localhost:3001/api/anthropic",192});193```194195### Logging Configuration196197Configure logging behavior for debugging and monitoring.198199```typescript { .api }200interface LoggingConfiguration {201/** Custom logger implementation */202logger?: Logger;203/** Logging level for SDK messages */204logLevel?: LogLevel;205}206207interface Logger {208info(message: string, ...args: any[]): void;209warn(message: string, ...args: any[]): void;210error(message: string, ...args: any[]): void;211debug(message: string, ...args: any[]): void;212}213214type LogLevel = "debug" | "info" | "warn" | "error" | "silent";215```216217**Usage Examples:**218219```typescript220// Custom logger221const customLogger = {222info: (msg: string) => console.log(`[INFO] ${msg}`),223warn: (msg: string) => console.warn(`[WARN] ${msg}`),224error: (msg: string) => console.error(`[ERROR] ${msg}`),225debug: (msg: string) => console.log(`[DEBUG] ${msg}`),226};227228const client = new Anthropic({229logger: customLogger,230logLevel: "debug",231});232233// Disable logging234const silentClient = new Anthropic({235logLevel: "silent",236});237```238239### Request Options240241Configure individual request behavior that overrides client defaults.242243```typescript { .api }244interface RequestOptions {245/** Override request timeout for this request */246timeout?: number;247/** Override maximum retries for this request */248maxRetries?: number;249/** Additional headers for this request */250headers?: Record<string, string>;251/** Additional query parameters */252query?: Record<string, any>;253/** Override fetch options for this request */254fetchOptions?: RequestInit;255}256```257258**Usage Examples:**259260```typescript261// Override timeout for specific request262const message = await client.messages.create(263{264model: "claude-3-sonnet-20240229",265max_tokens: 1024,266messages: [{ role: "user", content: "Long processing task..." }],267},268{269timeout: 120000, // 2 minutes for this request270headers: {271"X-Request-ID": "unique-request-id",272},273}274);275```276277## Base Client278279```typescript { .api }280/**281* Base client class with core HTTP functionality282*/283class BaseAnthropic {284constructor(options?: ClientOptions);285286/** Make a GET request */287protected get(url: string, options?: RequestOptions): APIPromise<any>;288/** Make a POST request */289protected post(url: string, options?: RequestOptions): APIPromise<any>;290/** Make a PUT request */291protected put(url: string, options?: RequestOptions): APIPromise<any>;292/** Make a PATCH request */293protected patch(url: string, options?: RequestOptions): APIPromise<any>;294/** Make a DELETE request */295protected delete(url: string, options?: RequestOptions): APIPromise<any>;296}297```298299## Error Configuration300301Configure error handling and retry behavior.302303```typescript { .api }304interface ErrorConfiguration {305/** Custom error handling logic */306onError?: (error: AnthropicError) => void;307/** Retry predicate function */308shouldRetry?: (error: AnthropicError) => boolean;309/** Custom retry delay calculation */310retryDelay?: (retryCount: number) => number;311}312```313314## Environment Variables315316The SDK automatically reads configuration from environment variables:317318```bash319# Primary authentication (required)320ANTHROPIC_API_KEY=your-api-key321322# Alternative authentication323ANTHROPIC_AUTH_TOKEN=your-auth-token324325# Custom base URL326ANTHROPIC_BASE_URL=https://api.anthropic.com327```328329**Priority order for authentication:**3301. Explicit `apiKey` in ClientOptions3312. Explicit `authToken` in ClientOptions3323. `ANTHROPIC_API_KEY` environment variable3334. `ANTHROPIC_AUTH_TOKEN` environment variable334335## Default Values336337```typescript { .api }338const DEFAULT_CONFIG = {339baseURL: "https://api.anthropic.com",340timeout: 600000, // 10 minutes341maxRetries: 2,342dangerouslyAllowBrowser: false,343logLevel: "info" as LogLevel,344};345```