npm-anthropic-ai--sdk

Description
The official TypeScript library for the Anthropic API providing comprehensive client functionality for Claude AI models.
Author
tessl
Last updated

How to use

npx @tessl/cli registry install tessl/npm-anthropic-ai--sdk@0.61.0

client-configuration.md docs/

1
# Client Configuration
2
3
The Anthropic SDK client provides comprehensive configuration options for authentication, request handling, retries, and environment-specific settings.
4
5
## Capabilities
6
7
### Client Initialization
8
9
Create and configure the main Anthropic client with authentication and request options.
10
11
```typescript { .api }
12
/**
13
* Main Anthropic API client
14
*/
15
class Anthropic extends BaseAnthropic {
16
constructor(options?: ClientOptions);
17
18
/** Text completions API (legacy) */
19
completions: Completions;
20
/** Messages API (primary interface) */
21
messages: Messages;
22
/** Models information API */
23
models: Models;
24
/** Beta features API */
25
beta: Beta;
26
}
27
28
interface ClientOptions {
29
/** API key for authentication (defaults to ANTHROPIC_API_KEY env var) */
30
apiKey?: string | null;
31
/** Auth token for authentication (defaults to ANTHROPIC_AUTH_TOKEN env var) */
32
authToken?: string | null;
33
/** Base URL override (defaults to ANTHROPIC_BASE_URL env var) */
34
baseURL?: string | null;
35
/** Request timeout in milliseconds */
36
timeout?: number;
37
/** Maximum number of retry attempts */
38
maxRetries?: number;
39
/** Custom fetch implementation */
40
fetch?: Fetch;
41
/** Additional fetch options for all requests */
42
fetchOptions?: RequestInit;
43
/** Allow usage in browser environments */
44
dangerouslyAllowBrowser?: boolean;
45
/** HTTP agent for Node.js environments */
46
httpAgent?: Agent;
47
/** Custom logger instance */
48
logger?: Logger;
49
/** Logging level */
50
logLevel?: LogLevel;
51
}
52
```
53
54
**Usage Examples:**
55
56
```typescript
57
import Anthropic from "@anthropic-ai/sdk";
58
59
// Basic initialization with API key
60
const client = new Anthropic({
61
apiKey: "your-api-key",
62
});
63
64
// Environment variable (recommended)
65
const client = new Anthropic(); // Uses ANTHROPIC_API_KEY env var
66
67
// Custom configuration
68
const client = new Anthropic({
69
apiKey: process.env.ANTHROPIC_API_KEY,
70
baseURL: "https://api.anthropic.com",
71
timeout: 30000, // 30 seconds
72
maxRetries: 3,
73
});
74
75
// Browser usage (requires explicit opt-in)
76
const browserClient = new Anthropic({
77
apiKey: "your-api-key",
78
dangerouslyAllowBrowser: true,
79
});
80
```
81
82
### Authentication Options
83
84
Configure authentication using API keys or auth tokens.
85
86
```typescript { .api }
87
interface AuthenticationOptions {
88
/** Primary API key authentication */
89
apiKey?: string | null;
90
/** Alternative auth token authentication */
91
authToken?: string | null;
92
}
93
```
94
95
**Usage Examples:**
96
97
```typescript
98
// API key authentication (recommended)
99
const client = new Anthropic({
100
apiKey: process.env.ANTHROPIC_API_KEY,
101
});
102
103
// Auth token authentication
104
const client = new Anthropic({
105
authToken: process.env.ANTHROPIC_AUTH_TOKEN,
106
});
107
108
// Authentication automatically detected from environment
109
const client = new Anthropic(); // Checks ANTHROPIC_API_KEY then ANTHROPIC_AUTH_TOKEN
110
```
111
112
### Request Configuration
113
114
Configure HTTP request behavior including timeouts, retries, and custom fetch options.
115
116
```typescript { .api }
117
interface RequestConfiguration {
118
/** Request timeout in milliseconds (default: 600000) */
119
timeout?: number;
120
/** Maximum retry attempts for failed requests (default: 2) */
121
maxRetries?: number;
122
/** Custom fetch function implementation */
123
fetch?: Fetch;
124
/** Additional RequestInit options for all requests */
125
fetchOptions?: RequestInit;
126
/** HTTP agent for Node.js (for proxy support, etc.) */
127
httpAgent?: Agent;
128
}
129
```
130
131
**Usage Examples:**
132
133
```typescript
134
import https from "https";
135
136
// Custom timeout and retries
137
const client = new Anthropic({
138
timeout: 60000, // 60 seconds
139
maxRetries: 5,
140
});
141
142
// Custom HTTP agent for proxy
143
const agent = new https.Agent({
144
keepAlive: true,
145
timeout: 30000,
146
});
147
148
const client = new Anthropic({
149
httpAgent: agent,
150
});
151
152
// Custom fetch with additional options
153
const client = new Anthropic({
154
fetchOptions: {
155
headers: {
156
"User-Agent": "MyApp/1.0",
157
},
158
},
159
});
160
```
161
162
### Environment Configuration
163
164
Configure the client for different deployment environments and base URLs.
165
166
```typescript { .api }
167
interface EnvironmentConfiguration {
168
/** Custom base URL for API requests */
169
baseURL?: string | null;
170
/** Enable browser usage (disabled by default for security) */
171
dangerouslyAllowBrowser?: boolean;
172
}
173
```
174
175
**Usage Examples:**
176
177
```typescript
178
// Custom API endpoint
179
const client = new Anthropic({
180
baseURL: "https://api.example.com/anthropic/v1",
181
});
182
183
// Browser environment (not recommended for production)
184
const browserClient = new Anthropic({
185
apiKey: publicApiKey, // Use with caution
186
dangerouslyAllowBrowser: true,
187
});
188
189
// Development environment with local proxy
190
const devClient = new Anthropic({
191
baseURL: "http://localhost:3001/api/anthropic",
192
});
193
```
194
195
### Logging Configuration
196
197
Configure logging behavior for debugging and monitoring.
198
199
```typescript { .api }
200
interface LoggingConfiguration {
201
/** Custom logger implementation */
202
logger?: Logger;
203
/** Logging level for SDK messages */
204
logLevel?: LogLevel;
205
}
206
207
interface Logger {
208
info(message: string, ...args: any[]): void;
209
warn(message: string, ...args: any[]): void;
210
error(message: string, ...args: any[]): void;
211
debug(message: string, ...args: any[]): void;
212
}
213
214
type LogLevel = "debug" | "info" | "warn" | "error" | "silent";
215
```
216
217
**Usage Examples:**
218
219
```typescript
220
// Custom logger
221
const customLogger = {
222
info: (msg: string) => console.log(`[INFO] ${msg}`),
223
warn: (msg: string) => console.warn(`[WARN] ${msg}`),
224
error: (msg: string) => console.error(`[ERROR] ${msg}`),
225
debug: (msg: string) => console.log(`[DEBUG] ${msg}`),
226
};
227
228
const client = new Anthropic({
229
logger: customLogger,
230
logLevel: "debug",
231
});
232
233
// Disable logging
234
const silentClient = new Anthropic({
235
logLevel: "silent",
236
});
237
```
238
239
### Request Options
240
241
Configure individual request behavior that overrides client defaults.
242
243
```typescript { .api }
244
interface RequestOptions {
245
/** Override request timeout for this request */
246
timeout?: number;
247
/** Override maximum retries for this request */
248
maxRetries?: number;
249
/** Additional headers for this request */
250
headers?: Record<string, string>;
251
/** Additional query parameters */
252
query?: Record<string, any>;
253
/** Override fetch options for this request */
254
fetchOptions?: RequestInit;
255
}
256
```
257
258
**Usage Examples:**
259
260
```typescript
261
// Override timeout for specific request
262
const message = await client.messages.create(
263
{
264
model: "claude-3-sonnet-20240229",
265
max_tokens: 1024,
266
messages: [{ role: "user", content: "Long processing task..." }],
267
},
268
{
269
timeout: 120000, // 2 minutes for this request
270
headers: {
271
"X-Request-ID": "unique-request-id",
272
},
273
}
274
);
275
```
276
277
## Base Client
278
279
```typescript { .api }
280
/**
281
* Base client class with core HTTP functionality
282
*/
283
class BaseAnthropic {
284
constructor(options?: ClientOptions);
285
286
/** Make a GET request */
287
protected get(url: string, options?: RequestOptions): APIPromise<any>;
288
/** Make a POST request */
289
protected post(url: string, options?: RequestOptions): APIPromise<any>;
290
/** Make a PUT request */
291
protected put(url: string, options?: RequestOptions): APIPromise<any>;
292
/** Make a PATCH request */
293
protected patch(url: string, options?: RequestOptions): APIPromise<any>;
294
/** Make a DELETE request */
295
protected delete(url: string, options?: RequestOptions): APIPromise<any>;
296
}
297
```
298
299
## Error Configuration
300
301
Configure error handling and retry behavior.
302
303
```typescript { .api }
304
interface ErrorConfiguration {
305
/** Custom error handling logic */
306
onError?: (error: AnthropicError) => void;
307
/** Retry predicate function */
308
shouldRetry?: (error: AnthropicError) => boolean;
309
/** Custom retry delay calculation */
310
retryDelay?: (retryCount: number) => number;
311
}
312
```
313
314
## Environment Variables
315
316
The SDK automatically reads configuration from environment variables:
317
318
```bash
319
# Primary authentication (required)
320
ANTHROPIC_API_KEY=your-api-key
321
322
# Alternative authentication
323
ANTHROPIC_AUTH_TOKEN=your-auth-token
324
325
# Custom base URL
326
ANTHROPIC_BASE_URL=https://api.anthropic.com
327
```
328
329
**Priority order for authentication:**
330
1. Explicit `apiKey` in ClientOptions
331
2. Explicit `authToken` in ClientOptions
332
3. `ANTHROPIC_API_KEY` environment variable
333
4. `ANTHROPIC_AUTH_TOKEN` environment variable
334
335
## Default Values
336
337
```typescript { .api }
338
const DEFAULT_CONFIG = {
339
baseURL: "https://api.anthropic.com",
340
timeout: 600000, // 10 minutes
341
maxRetries: 2,
342
dangerouslyAllowBrowser: false,
343
logLevel: "info" as LogLevel,
344
};
345
```