@anthropic-ai/sdk 0.62.0 → 0.63.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +47 -12
  3. package/helpers/beta/json-schema.d.mts +19 -0
  4. package/helpers/beta/json-schema.d.mts.map +1 -0
  5. package/helpers/beta/json-schema.d.ts +19 -0
  6. package/helpers/beta/json-schema.d.ts.map +1 -0
  7. package/helpers/beta/json-schema.js +22 -0
  8. package/helpers/beta/json-schema.js.map +1 -0
  9. package/helpers/beta/json-schema.mjs +19 -0
  10. package/helpers/beta/json-schema.mjs.map +1 -0
  11. package/helpers/beta/zod.d.mts +16 -0
  12. package/helpers/beta/zod.d.mts.map +1 -0
  13. package/helpers/beta/zod.d.ts +16 -0
  14. package/helpers/beta/zod.d.ts.map +1 -0
  15. package/helpers/beta/zod.js +28 -0
  16. package/helpers/beta/zod.js.map +1 -0
  17. package/helpers/beta/zod.mjs +24 -0
  18. package/helpers/beta/zod.mjs.map +1 -0
  19. package/internal/utils/values.js +3 -3
  20. package/internal/utils/values.js.map +1 -1
  21. package/internal/utils/values.mjs +3 -3
  22. package/internal/utils/values.mjs.map +1 -1
  23. package/lib/tools/BetaRunnableTool.d.mts +7 -0
  24. package/lib/tools/BetaRunnableTool.d.mts.map +1 -0
  25. package/lib/tools/BetaRunnableTool.d.ts +7 -0
  26. package/lib/tools/BetaRunnableTool.d.ts.map +1 -0
  27. package/lib/tools/BetaRunnableTool.js +3 -0
  28. package/lib/tools/BetaRunnableTool.js.map +1 -0
  29. package/lib/tools/BetaRunnableTool.mjs +2 -0
  30. package/lib/tools/BetaRunnableTool.mjs.map +1 -0
  31. package/lib/tools/BetaToolRunner.d.mts +132 -0
  32. package/lib/tools/BetaToolRunner.d.mts.map +1 -0
  33. package/lib/tools/BetaToolRunner.d.ts +132 -0
  34. package/lib/tools/BetaToolRunner.d.ts.map +1 -0
  35. package/lib/tools/BetaToolRunner.js +288 -0
  36. package/lib/tools/BetaToolRunner.js.map +1 -0
  37. package/lib/tools/BetaToolRunner.mjs +284 -0
  38. package/lib/tools/BetaToolRunner.mjs.map +1 -0
  39. package/lib/tools/ToolRunner.d.mts +132 -0
  40. package/lib/tools/ToolRunner.d.mts.map +1 -0
  41. package/lib/tools/ToolRunner.d.ts +132 -0
  42. package/lib/tools/ToolRunner.d.ts.map +1 -0
  43. package/lib/tools/ToolRunner.js +288 -0
  44. package/lib/tools/ToolRunner.js.map +1 -0
  45. package/lib/tools/ToolRunner.mjs +284 -0
  46. package/lib/tools/ToolRunner.mjs.map +1 -0
  47. package/package.json +22 -2
  48. package/resources/beta/beta.d.mts +2 -2
  49. package/resources/beta/beta.d.mts.map +1 -1
  50. package/resources/beta/beta.d.ts +2 -2
  51. package/resources/beta/beta.d.ts.map +1 -1
  52. package/resources/beta/beta.js.map +1 -1
  53. package/resources/beta/beta.mjs.map +1 -1
  54. package/resources/beta/index.d.mts +1 -1
  55. package/resources/beta/index.d.mts.map +1 -1
  56. package/resources/beta/index.d.ts +1 -1
  57. package/resources/beta/index.d.ts.map +1 -1
  58. package/resources/beta/index.js.map +1 -1
  59. package/resources/beta/index.mjs.map +1 -1
  60. package/resources/beta/messages/index.d.mts +2 -1
  61. package/resources/beta/messages/index.d.mts.map +1 -1
  62. package/resources/beta/messages/index.d.ts +2 -1
  63. package/resources/beta/messages/index.d.ts.map +1 -1
  64. package/resources/beta/messages/index.js +3 -1
  65. package/resources/beta/messages/index.js.map +1 -1
  66. package/resources/beta/messages/index.mjs +1 -0
  67. package/resources/beta/messages/index.mjs.map +1 -1
  68. package/resources/beta/messages/messages.d.mts +13 -2
  69. package/resources/beta/messages/messages.d.mts.map +1 -1
  70. package/resources/beta/messages/messages.d.ts +13 -2
  71. package/resources/beta/messages/messages.d.ts.map +1 -1
  72. package/resources/beta/messages/messages.js +9 -2
  73. package/resources/beta/messages/messages.js.map +1 -1
  74. package/resources/beta/messages/messages.mjs +7 -1
  75. package/resources/beta/messages/messages.mjs.map +1 -1
  76. package/src/helpers/beta/json-schema.ts +32 -0
  77. package/src/helpers/beta/zod.ts +35 -0
  78. package/src/internal/utils/values.ts +3 -3
  79. package/src/lib/tools/BetaRunnableTool.ts +10 -0
  80. package/src/lib/tools/BetaToolRunner.ts +374 -0
  81. package/src/lib/tools/ToolRunner.ts +374 -0
  82. package/src/resources/beta/beta.ts +2 -0
  83. package/src/resources/beta/index.ts +1 -0
  84. package/src/resources/beta/messages/index.ts +2 -0
  85. package/src/resources/beta/messages/messages.ts +20 -2
  86. package/src/version.ts +1 -1
  87. package/version.d.mts +1 -1
  88. package/version.d.ts +1 -1
  89. package/version.js +1 -1
  90. package/version.mjs +1 -1
@@ -0,0 +1,35 @@
1
+ import type { infer as zodInfer, ZodType } from 'zod/v4';
2
+ import * as z from 'zod/v4';
3
+ import { Promisable, BetaRunnableTool } from '../../lib/tools/BetaRunnableTool';
4
+ import { BetaToolResultContentBlockParam } from '../../resources/beta';
5
+
6
+ /**
7
+ * Creates a tool using the provided Zod schema that can be passed
8
+ * into the `.toolRunner()` method. The Zod schema will automatically be
9
+ * converted into JSON Schema when passed to the API. The provided function's
10
+ * input arguments will also be validated against the provided schema.
11
+ */
12
+ export function betaZodTool<InputSchema extends ZodType>(options: {
13
+ name: string;
14
+ inputSchema: InputSchema;
15
+ description: string;
16
+ run: (args: zodInfer<InputSchema>) => Promisable<string | Array<BetaToolResultContentBlockParam>>;
17
+ }): BetaRunnableTool<zodInfer<InputSchema>> {
18
+ const jsonSchema = z.toJSONSchema(options.inputSchema, { reused: 'ref' });
19
+
20
+ if (jsonSchema.type !== 'object') {
21
+ throw new Error(`Zod schema for tool "${options.name}" must be an object, but got ${jsonSchema.type}`);
22
+ }
23
+
24
+ // TypeScript doesn't narrow the type after the runtime check, so we need to assert it
25
+ const objectSchema = jsonSchema as typeof jsonSchema & { type: 'object' };
26
+
27
+ return {
28
+ type: 'custom',
29
+ name: options.name,
30
+ input_schema: objectSchema,
31
+ description: options.description,
32
+ run: options.run,
33
+ parse: (args: unknown) => options.inputSchema.parse(args) as zodInfer<InputSchema>,
34
+ };
35
+ }
@@ -76,21 +76,21 @@ export const coerceBoolean = (value: unknown): boolean => {
76
76
  };
77
77
 
78
78
  export const maybeCoerceInteger = (value: unknown): number | undefined => {
79
- if (value === undefined) {
79
+ if (value == null) {
80
80
  return undefined;
81
81
  }
82
82
  return coerceInteger(value);
83
83
  };
84
84
 
85
85
  export const maybeCoerceFloat = (value: unknown): number | undefined => {
86
- if (value === undefined) {
86
+ if (value == null) {
87
87
  return undefined;
88
88
  }
89
89
  return coerceFloat(value);
90
90
  };
91
91
 
92
92
  export const maybeCoerceBoolean = (value: unknown): boolean | undefined => {
93
- if (value === undefined) {
93
+ if (value == null) {
94
94
  return undefined;
95
95
  }
96
96
  return coerceBoolean(value);
@@ -0,0 +1,10 @@
1
+ import { BetaTool, BetaToolResultContentBlockParam } from '../../resources/beta';
2
+
3
+ export type Promisable<T> = T | Promise<T>;
4
+
5
+ // this type is just an extension of BetaTool with a run and parse method
6
+ // that will be called by `toolRunner()` helpers
7
+ export interface BetaRunnableTool<Input = any> extends BetaTool {
8
+ run: (args: Input) => Promisable<string | Array<BetaToolResultContentBlockParam>>;
9
+ parse: (content: unknown) => Input;
10
+ }
@@ -0,0 +1,374 @@
1
+ import { BetaRunnableTool } from './BetaRunnableTool';
2
+ import { Anthropic } from '../..';
3
+ import { AnthropicError } from '../../core/error';
4
+ import { BetaMessage, BetaMessageParam, BetaToolUnion, MessageCreateParams } from '../../resources/beta';
5
+ import { BetaMessageStream } from '../BetaMessageStream';
6
+
7
+ /**
8
+ * Just Promise.withResolvers(), which is not available in all environments.
9
+ */
10
+ function promiseWithResolvers<T>(): {
11
+ promise: Promise<T>;
12
+ resolve: (value: T) => void;
13
+ reject: (reason?: any) => void;
14
+ } {
15
+ let resolve: (value: T) => void;
16
+ let reject: (reason?: any) => void;
17
+ const promise = new Promise<T>((res, rej) => {
18
+ resolve = res;
19
+ reject = rej;
20
+ });
21
+ return { promise, resolve: resolve!, reject: reject! };
22
+ }
23
+
24
+ /**
25
+ * A ToolRunner handles the automatic conversation loop between the assistant and tools.
26
+ *
27
+ * A ToolRunner is an async iterable that yields either BetaMessage or BetaMessageStream objects
28
+ * depending on the streaming configuration.
29
+ */
30
+ export class BetaToolRunner<Stream extends boolean> {
31
+ /** Whether the async iterator has been consumed */
32
+ #consumed = false;
33
+ /** Whether parameters have been mutated since the last API call */
34
+ #mutated = false;
35
+ /** Current state containing the request parameters */
36
+ #state: { params: BetaToolRunnerParams };
37
+ /** Promise for the last message received from the assistant */
38
+ #message?: Promise<BetaMessage> | undefined;
39
+ /** Cached tool response to avoid redundant executions */
40
+ #toolResponse?: Promise<BetaMessageParam | null> | undefined;
41
+ /** Promise resolvers for waiting on completion */
42
+ #completion: {
43
+ promise: Promise<BetaMessage>;
44
+ resolve: (value: BetaMessage) => void;
45
+ reject: (reason?: any) => void;
46
+ };
47
+ /** Number of iterations (API requests) made so far */
48
+ #iterationCount = 0;
49
+
50
+ constructor(
51
+ private client: Anthropic,
52
+ params: BetaToolRunnerParams,
53
+ ) {
54
+ this.#state = {
55
+ params: {
56
+ // You can't clone the entire params since there are functions as handlers.
57
+ // You also don't really need to clone params.messages, but it probably will prevent a foot gun
58
+ // somewhere.
59
+ ...params,
60
+ messages: structuredClone(params.messages),
61
+ },
62
+ };
63
+
64
+ this.#completion = promiseWithResolvers();
65
+ }
66
+
67
+ async *[Symbol.asyncIterator](): AsyncIterator<
68
+ Stream extends true ? BetaMessageStream
69
+ : Stream extends false ? BetaMessage
70
+ : BetaMessage | BetaMessageStream
71
+ > {
72
+ if (this.#consumed) {
73
+ throw new AnthropicError('Cannot iterate over a consumed stream');
74
+ }
75
+
76
+ this.#consumed = true;
77
+ this.#mutated = true;
78
+ this.#toolResponse = undefined;
79
+
80
+ try {
81
+ while (true) {
82
+ let stream;
83
+ try {
84
+ if (
85
+ this.#state.params.max_iterations &&
86
+ this.#iterationCount >= this.#state.params.max_iterations
87
+ ) {
88
+ break;
89
+ }
90
+
91
+ this.#mutated = false;
92
+ this.#message = undefined;
93
+ this.#toolResponse = undefined;
94
+ this.#iterationCount++;
95
+
96
+ const { max_iterations, ...params } = this.#state.params;
97
+ if (params.stream) {
98
+ stream = this.client.beta.messages.stream({ ...params });
99
+ this.#message = stream.finalMessage();
100
+ yield stream as any;
101
+ } else {
102
+ this.#message = this.client.beta.messages.create({ ...params, stream: false });
103
+ yield this.#message as any;
104
+ }
105
+
106
+ if (!this.#mutated) {
107
+ const { role, content } = await this.#message;
108
+ this.#state.params.messages.push({ role, content });
109
+ }
110
+
111
+ const toolMessage = await this.#generateToolResponse(this.#state.params.messages.at(-1)!);
112
+ if (toolMessage) {
113
+ this.#state.params.messages.push(toolMessage);
114
+ }
115
+
116
+ if (!toolMessage && !this.#mutated) {
117
+ break;
118
+ }
119
+ } finally {
120
+ if (stream) {
121
+ stream.abort();
122
+ }
123
+ }
124
+ }
125
+
126
+ if (!this.#message) {
127
+ throw new AnthropicError('ToolRunner concluded without a message from the server');
128
+ }
129
+
130
+ this.#completion.resolve(await this.#message);
131
+ } catch (error) {
132
+ this.#consumed = false;
133
+ // Silence unhandled promise errors
134
+ this.#completion.promise.catch(() => {});
135
+ this.#completion.reject(error);
136
+ this.#completion = promiseWithResolvers();
137
+ throw error;
138
+ }
139
+ }
140
+
141
+ /**
142
+ * Update the parameters for the next API call. This invalidates any cached tool responses.
143
+ *
144
+ * @param paramsOrMutator - Either new parameters or a function to mutate existing parameters
145
+ *
146
+ * @example
147
+ * // Direct parameter update
148
+ * runner.setMessagesParams({
149
+ * model: 'claude-3-5-haiku-latest',
150
+ * max_tokens: 500,
151
+ * });
152
+ *
153
+ * @example
154
+ * // Using a mutator function
155
+ * runner.setMessagesParams((params) => ({
156
+ * ...params,
157
+ * max_tokens: 100,
158
+ * }));
159
+ */
160
+ setMessagesParams(params: BetaToolRunnerParams): void;
161
+ setMessagesParams(mutator: (prevParams: BetaToolRunnerParams) => BetaToolRunnerParams): void;
162
+ setMessagesParams(
163
+ paramsOrMutator: BetaToolRunnerParams | ((prevParams: BetaToolRunnerParams) => BetaToolRunnerParams),
164
+ ) {
165
+ if (typeof paramsOrMutator === 'function') {
166
+ this.#state.params = paramsOrMutator(this.#state.params);
167
+ } else {
168
+ this.#state.params = paramsOrMutator;
169
+ }
170
+ this.#mutated = true;
171
+ // Invalidate cached tool response since parameters changed
172
+ this.#toolResponse = undefined;
173
+ }
174
+
175
+ /**
176
+ * Get the tool response for the last message from the assistant.
177
+ * Avoids redundant tool executions by caching results.
178
+ *
179
+ * @returns A promise that resolves to a BetaMessageParam containing tool results, or null if no tools need to be executed
180
+ *
181
+ * @example
182
+ * const toolResponse = await runner.generateToolResponse();
183
+ * if (toolResponse) {
184
+ * console.log('Tool results:', toolResponse.content);
185
+ * }
186
+ */
187
+ async generateToolResponse() {
188
+ const message = (await this.#message) ?? this.params.messages.at(-1);
189
+ if (!message) {
190
+ return null;
191
+ }
192
+ return this.#generateToolResponse(message);
193
+ }
194
+
195
+ async #generateToolResponse(lastMessage: BetaMessageParam) {
196
+ if (this.#toolResponse !== undefined) {
197
+ return this.#toolResponse;
198
+ }
199
+ this.#toolResponse = generateToolResponse(this.#state.params, lastMessage);
200
+ return this.#toolResponse;
201
+ }
202
+
203
+ /**
204
+ * Wait for the async iterator to complete. This works even if the async iterator hasn't yet started, and
205
+ * will wait for an instance to start and go to completion.
206
+ *
207
+ * @returns A promise that resolves to the final BetaMessage when the iterator completes
208
+ *
209
+ * @example
210
+ * // Start consuming the iterator
211
+ * for await (const message of runner) {
212
+ * console.log('Message:', message.content);
213
+ * }
214
+ *
215
+ * // Meanwhile, wait for completion from another part of the code
216
+ * const finalMessage = await runner.done();
217
+ * console.log('Final response:', finalMessage.content);
218
+ */
219
+ done(): Promise<BetaMessage> {
220
+ return this.#completion.promise;
221
+ }
222
+
223
+ /**
224
+ * Returns a promise indicating that the stream is done. Unlike .done(), this will eagerly read the stream:
225
+ * * If the iterator has not been consumed, consume the entire iterator and return the final message from the
226
+ * assistant.
227
+ * * If the iterator has been consumed, waits for it to complete and returns the final message.
228
+ *
229
+ * @returns A promise that resolves to the final BetaMessage from the conversation
230
+ * @throws {AnthropicError} If no messages were processed during the conversation
231
+ *
232
+ * @example
233
+ * const finalMessage = await runner.runUntilDone();
234
+ * console.log('Final response:', finalMessage.content);
235
+ */
236
+ async runUntilDone(): Promise<BetaMessage> {
237
+ // If not yet consumed, start consuming and wait for completion
238
+ if (!this.#consumed) {
239
+ for await (const _ of this) {
240
+ // Iterator naturally populates this.#message
241
+ }
242
+ }
243
+
244
+ // If consumed but not completed, wait for completion
245
+ return this.done();
246
+ }
247
+
248
+ /**
249
+ * Get the current parameters being used by the ToolRunner.
250
+ *
251
+ * @returns A readonly view of the current ToolRunnerParams
252
+ *
253
+ * @example
254
+ * const currentParams = runner.params;
255
+ * console.log('Current model:', currentParams.model);
256
+ * console.log('Message count:', currentParams.messages.length);
257
+ */
258
+ get params(): Readonly<BetaToolRunnerParams> {
259
+ return this.#state.params as Readonly<BetaToolRunnerParams>;
260
+ }
261
+
262
+ /**
263
+ * Add one or more messages to the conversation history.
264
+ *
265
+ * @param messages - One or more BetaMessageParam objects to add to the conversation
266
+ *
267
+ * @example
268
+ * runner.pushMessages(
269
+ * { role: 'user', content: 'Also, what about the weather in NYC?' }
270
+ * );
271
+ *
272
+ * @example
273
+ * // Adding multiple messages
274
+ * runner.pushMessages(
275
+ * { role: 'user', content: 'What about NYC?' },
276
+ * { role: 'user', content: 'And Boston?' }
277
+ * );
278
+ */
279
+ pushMessages(...messages: BetaMessageParam[]) {
280
+ this.setMessagesParams((params) => ({
281
+ ...params,
282
+ messages: [...params.messages, ...messages],
283
+ }));
284
+ }
285
+
286
+ /**
287
+ * Makes the ToolRunner directly awaitable, equivalent to calling .runUntilDone()
288
+ * This allows using `await runner` instead of `await runner.runUntilDone()`
289
+ */
290
+ then<TResult1 = BetaMessage, TResult2 = never>(
291
+ onfulfilled?: ((value: BetaMessage) => TResult1 | PromiseLike<TResult1>) | undefined | null,
292
+ onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null,
293
+ ): Promise<TResult1 | TResult2> {
294
+ return this.runUntilDone().then(onfulfilled, onrejected);
295
+ }
296
+ }
297
+
298
+ async function generateToolResponse(
299
+ params: BetaToolRunnerParams,
300
+ lastMessage = params.messages.at(-1),
301
+ ): Promise<BetaMessageParam | null> {
302
+ // Only process if the last message is from the assistant and has tool use blocks
303
+ if (
304
+ !lastMessage ||
305
+ lastMessage.role !== 'assistant' ||
306
+ !lastMessage.content ||
307
+ typeof lastMessage.content === 'string'
308
+ ) {
309
+ return null;
310
+ }
311
+
312
+ const toolUseBlocks = lastMessage.content.filter((content) => content.type === 'tool_use');
313
+ if (toolUseBlocks.length === 0) {
314
+ return null;
315
+ }
316
+
317
+ const toolResults = await Promise.all(
318
+ toolUseBlocks.map(async (toolUse) => {
319
+ const tool = params.tools.find((t) => t.name === toolUse.name);
320
+ if (!tool || !('run' in tool)) {
321
+ return {
322
+ type: 'tool_result' as const,
323
+ tool_use_id: toolUse.id,
324
+ content: `Error: Tool '${toolUse.name}' not found`,
325
+ is_error: true,
326
+ };
327
+ }
328
+
329
+ try {
330
+ let input = toolUse.input;
331
+ if ('parse' in tool && tool.parse) {
332
+ input = tool.parse(input);
333
+ }
334
+
335
+ const result = await tool.run(input);
336
+ return {
337
+ type: 'tool_result' as const,
338
+ tool_use_id: toolUse.id,
339
+ content: result,
340
+ };
341
+ } catch (error) {
342
+ return {
343
+ type: 'tool_result' as const,
344
+ tool_use_id: toolUse.id,
345
+ content: `Error: ${error instanceof Error ? error.message : String(error)}`,
346
+ is_error: true,
347
+ };
348
+ }
349
+ }),
350
+ );
351
+
352
+ return {
353
+ role: 'user' as const,
354
+ content: toolResults,
355
+ };
356
+ }
357
+
358
+ // vendored from typefest just to make things look a bit nicer on hover
359
+ type Simplify<T> = { [KeyType in keyof T]: T[KeyType] } & {};
360
+
361
+ /**
362
+ * Parameters for creating a ToolRunner, extending MessageCreateParams with runnable tools.
363
+ */
364
+ export type BetaToolRunnerParams = Simplify<
365
+ Omit<MessageCreateParams, 'tools'> & {
366
+ tools: (BetaToolUnion | BetaRunnableTool<any>)[];
367
+ /**
368
+ * Maximum number of iterations (API requests) to make in the tool execution loop.
369
+ * Each iteration consists of: assistant response → tool execution → tool results.
370
+ * When exceeded, the loop will terminate even if tools are still being requested.
371
+ */
372
+ max_iterations?: number;
373
+ }
374
+ >;