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

messages-api.md docs/

1
# Messages API
2
3
The Messages API is the primary interface for conversational AI interactions with Claude models. It provides comprehensive support for multi-turn conversations, tool usage, and both streaming and non-streaming responses.
4
5
## Capabilities
6
7
### Create Message
8
9
Send a structured list of input messages with text and/or image content, and the model will generate the next message in the conversation.
10
11
```typescript { .api }
12
/**
13
* Create a message with Claude models
14
* @param params - Message creation parameters
15
* @returns Promise resolving to Message response or Stream for streaming
16
*/
17
create(params: MessageCreateParamsNonStreaming): APIPromise<Message>;
18
create(params: MessageCreateParamsStreaming): APIPromise<Stream<RawMessageStreamEvent>>;
19
20
interface MessageCreateParams {
21
/** The model to use for generation */
22
model: Model;
23
/** Array of input messages */
24
messages: MessageParam[];
25
/** Maximum number of tokens to generate */
26
max_tokens: number;
27
/** System prompt to set context and behavior */
28
system?: string;
29
/** Available tools for the model to use */
30
tools?: Tool[];
31
/** How the model should choose tools */
32
tool_choice?: ToolChoice;
33
/** Sampling temperature (0.0 to 1.0) */
34
temperature?: number;
35
/** Whether to stream the response */
36
stream?: boolean;
37
/** Message metadata */
38
metadata?: Metadata;
39
/** Stop sequences to halt generation */
40
stop_sequences?: string[];
41
/** Maximum number of tokens in response */
42
max_tokens?: number;
43
}
44
45
interface MessageCreateParamsNonStreaming extends MessageCreateParams {
46
stream?: false;
47
}
48
49
interface MessageCreateParamsStreaming extends MessageCreateParams {
50
stream: true;
51
}
52
```
53
54
**Usage Examples:**
55
56
```typescript
57
import Anthropic from "@anthropic-ai/sdk";
58
59
const client = new Anthropic();
60
61
// Basic message
62
const message = await client.messages.create({
63
model: "claude-3-sonnet-20240229",
64
max_tokens: 1024,
65
messages: [
66
{ role: "user", content: "What is the capital of France?" }
67
],
68
});
69
70
// Multi-turn conversation
71
const conversation = await client.messages.create({
72
model: "claude-3-sonnet-20240229",
73
max_tokens: 1024,
74
messages: [
75
{ role: "user", content: "Hello, I'm learning about astronomy." },
76
{ role: "assistant", content: "That's wonderful! I'd be happy to help you learn about astronomy. What specific topics interest you?" },
77
{ role: "user", content: "Tell me about black holes." }
78
],
79
});
80
81
// With system prompt
82
const guidedMessage = await client.messages.create({
83
model: "claude-3-sonnet-20240229",
84
max_tokens: 1024,
85
system: "You are a helpful astronomy teacher. Explain concepts clearly and encourage questions.",
86
messages: [
87
{ role: "user", content: "What causes the northern lights?" }
88
],
89
});
90
```
91
92
### Stream Message
93
94
Create a streaming message that returns events in real-time as the model generates the response.
95
96
```typescript { .api }
97
/**
98
* Create a streaming message with real-time response events
99
* @param params - Message stream parameters
100
* @returns MessageStream instance for handling events
101
*/
102
stream(params: MessageStreamParams): MessageStream;
103
104
interface MessageStreamParams {
105
model: Model;
106
messages: MessageParam[];
107
max_tokens: number;
108
system?: string;
109
tools?: Tool[];
110
tool_choice?: ToolChoice;
111
temperature?: number;
112
}
113
114
class MessageStream {
115
/** Get the final message once streaming completes */
116
finalMessage(): Promise<Message>;
117
/** Iterate over streaming events */
118
[Symbol.asyncIterator](): AsyncIterableIterator<MessageStreamEvent>;
119
/** Handle specific event types */
120
on(event: "text", handler: (text: string) => void): this;
121
on(event: "message", handler: (message: Message) => void): this;
122
on(event: "error", handler: (error: Error) => void): this;
123
}
124
```
125
126
**Usage Examples:**
127
128
```typescript
129
// Streaming with event handling
130
const stream = client.messages.stream({
131
model: "claude-3-sonnet-20240229",
132
max_tokens: 1024,
133
messages: [{ role: "user", content: "Write a short story about a robot." }],
134
});
135
136
stream.on("text", (text) => {
137
process.stdout.write(text);
138
});
139
140
stream.on("message", (message) => {
141
console.log("Final message:", message);
142
});
143
144
// Async iteration over events
145
for await (const event of stream) {
146
if (event.type === "content_block_delta") {
147
process.stdout.write(event.delta.text);
148
}
149
}
150
```
151
152
### Count Tokens
153
154
Count the number of tokens in a message without creating it, useful for managing token limits and costs.
155
156
```typescript { .api }
157
/**
158
* Count tokens in a message without creating it
159
* @param params - Token counting parameters
160
* @returns Promise resolving to token count information
161
*/
162
countTokens(params: MessageCountTokensParams): APIPromise<MessageTokensCount>;
163
164
interface MessageCountTokensParams {
165
model: Model;
166
messages: MessageParam[];
167
system?: string;
168
tools?: MessageCountTokensTool[];
169
}
170
171
interface MessageTokensCount {
172
input_tokens: number;
173
cache_creation_input_tokens?: number;
174
cache_read_input_tokens?: number;
175
}
176
```
177
178
**Usage Examples:**
179
180
```typescript
181
const tokenCount = await client.messages.countTokens({
182
model: "claude-3-sonnet-20240229",
183
messages: [
184
{ role: "user", content: "Explain quantum computing in simple terms." }
185
],
186
});
187
188
console.log(`This message would use ${tokenCount.input_tokens} input tokens`);
189
```
190
191
### Message Batches
192
193
Process multiple messages efficiently using the batching API.
194
195
```typescript { .api }
196
class Batches extends APIResource {
197
create(params: BatchCreateParams): APIPromise<MessageBatch>;
198
retrieve(batchId: string): APIPromise<MessageBatch>;
199
list(params?: BatchListParams): PagePromise<MessageBatchesPage, MessageBatch>;
200
cancel(batchId: string): APIPromise<MessageBatch>;
201
delete(batchId: string): APIPromise<DeletedMessageBatch>;
202
}
203
204
interface BatchCreateParams {
205
requests: MessageBatchRequest[];
206
}
207
208
interface MessageBatchRequest {
209
custom_id: string;
210
params: MessageCreateParams;
211
}
212
```
213
214
## Message Types
215
216
```typescript { .api }
217
interface Message {
218
id: string;
219
type: "message";
220
role: "assistant";
221
content: ContentBlock[];
222
model: Model;
223
stop_reason: StopReason | null;
224
stop_sequence: string | null;
225
usage: Usage;
226
}
227
228
interface MessageParam {
229
role: "user" | "assistant";
230
content: string | ContentBlockParam[];
231
}
232
233
type ContentBlock = TextBlock | ToolUseBlock;
234
235
interface TextBlock {
236
type: "text";
237
text: string;
238
}
239
240
interface ToolUseBlock {
241
type: "tool_use";
242
id: string;
243
name: string;
244
input: Record<string, any>;
245
}
246
247
type ContentBlockParam =
248
| TextBlockParam
249
| ImageBlockParam
250
| ToolUseBlockParam
251
| ToolResultBlockParam;
252
253
interface TextBlockParam {
254
type: "text";
255
text: string;
256
cache_control?: CacheControlEphemeral;
257
}
258
259
interface ImageBlockParam {
260
type: "image";
261
source: Base64ImageSource | URLImageSource;
262
cache_control?: CacheControlEphemeral;
263
}
264
265
interface ToolUseBlockParam {
266
type: "tool_use";
267
id: string;
268
name: string;
269
input: Record<string, any>;
270
cache_control?: CacheControlEphemeral;
271
}
272
273
interface ToolResultBlockParam {
274
type: "tool_result";
275
tool_use_id: string;
276
content?: string | ContentBlockParam[];
277
is_error?: boolean;
278
cache_control?: CacheControlEphemeral;
279
}
280
```
281
282
## Tool Usage
283
284
```typescript { .api }
285
interface Tool {
286
type: "function";
287
function: {
288
name: string;
289
description?: string;
290
parameters?: Record<string, any>;
291
};
292
}
293
294
type ToolChoice = ToolChoiceAuto | ToolChoiceAny | ToolChoiceNone | ToolChoiceTool;
295
296
interface ToolChoiceAuto {
297
type: "auto";
298
}
299
300
interface ToolChoiceAny {
301
type: "any";
302
}
303
304
interface ToolChoiceNone {
305
type: "none";
306
}
307
308
interface ToolChoiceTool {
309
type: "tool";
310
name: string;
311
}
312
```
313
314
## Streaming Events
315
316
```typescript { .api }
317
type MessageStreamEvent =
318
| MessageStartEvent
319
| MessageDeltaEvent
320
| MessageStopEvent
321
| ContentBlockStartEvent
322
| ContentBlockDeltaEvent
323
| ContentBlockStopEvent;
324
325
interface MessageStartEvent {
326
type: "message_start";
327
message: Message;
328
}
329
330
interface MessageDeltaEvent {
331
type: "message_delta";
332
delta: {
333
stop_reason?: StopReason;
334
stop_sequence?: string;
335
};
336
usage: MessageDeltaUsage;
337
}
338
339
interface MessageStopEvent {
340
type: "message_stop";
341
}
342
343
interface ContentBlockStartEvent {
344
type: "content_block_start";
345
index: number;
346
content_block: ContentBlock;
347
}
348
349
interface ContentBlockDeltaEvent {
350
type: "content_block_delta";
351
index: number;
352
delta: TextDelta | InputJSONDelta;
353
}
354
355
interface ContentBlockStopEvent {
356
type: "content_block_stop";
357
index: number;
358
}
359
360
interface TextDelta {
361
type: "text_delta";
362
text: string;
363
}
364
365
interface InputJSONDelta {
366
type: "input_json_delta";
367
partial_json: string;
368
}
369
```
370
371
## Image Support
372
373
```typescript { .api }
374
interface Base64ImageSource {
375
type: "base64";
376
media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp";
377
data: string;
378
}
379
380
interface URLImageSource {
381
type: "url";
382
url: string;
383
}
384
```
385
386
**Usage Examples:**
387
388
```typescript
389
// Send image with message
390
const imageMessage = await client.messages.create({
391
model: "claude-3-sonnet-20240229",
392
max_tokens: 1024,
393
messages: [
394
{
395
role: "user",
396
content: [
397
{ type: "text", text: "What do you see in this image?" },
398
{
399
type: "image",
400
source: {
401
type: "base64",
402
media_type: "image/jpeg",
403
data: "base64-encoded-image-data...",
404
},
405
},
406
],
407
},
408
],
409
});
410
```
411
412
## Usage Information
413
414
```typescript { .api }
415
interface Usage {
416
input_tokens: number;
417
output_tokens: number;
418
cache_creation_input_tokens?: number;
419
cache_read_input_tokens?: number;
420
}
421
422
interface MessageDeltaUsage {
423
output_tokens: number;
424
}
425
```