ai 3.0.20 → 3.0.22

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 (63) hide show
  1. package/dist/index.d.mts +45 -354
  2. package/dist/index.d.ts +45 -354
  3. package/dist/index.js +161 -460
  4. package/dist/index.js.map +1 -1
  5. package/dist/index.mjs +136 -430
  6. package/dist/index.mjs.map +1 -1
  7. package/package.json +6 -41
  8. package/react/dist/index.d.mts +1 -1
  9. package/react/dist/index.d.ts +1 -1
  10. package/react/dist/index.js +3 -3
  11. package/react/dist/index.js.map +1 -1
  12. package/react/dist/index.mjs +3 -3
  13. package/react/dist/index.mjs.map +1 -1
  14. package/rsc/dist/rsc-server.mjs +3 -3
  15. package/rsc/dist/rsc-server.mjs.map +1 -1
  16. package/solid/dist/index.d.mts +1 -1
  17. package/solid/dist/index.d.ts +1 -1
  18. package/solid/dist/index.js +3 -3
  19. package/solid/dist/index.js.map +1 -1
  20. package/solid/dist/index.mjs +3 -3
  21. package/solid/dist/index.mjs.map +1 -1
  22. package/svelte/dist/index.d.mts +1 -1
  23. package/svelte/dist/index.d.ts +1 -1
  24. package/svelte/dist/index.js +3 -3
  25. package/svelte/dist/index.js.map +1 -1
  26. package/svelte/dist/index.mjs +3 -3
  27. package/svelte/dist/index.mjs.map +1 -1
  28. package/vue/dist/index.d.mts +1 -1
  29. package/vue/dist/index.d.ts +1 -1
  30. package/vue/dist/index.js +3 -3
  31. package/vue/dist/index.js.map +1 -1
  32. package/vue/dist/index.mjs +3 -3
  33. package/vue/dist/index.mjs.map +1 -1
  34. package/anthropic/dist/index.d.mts +0 -403
  35. package/anthropic/dist/index.d.ts +0 -403
  36. package/anthropic/dist/index.js +0 -950
  37. package/anthropic/dist/index.js.map +0 -1
  38. package/anthropic/dist/index.mjs +0 -914
  39. package/anthropic/dist/index.mjs.map +0 -1
  40. package/google/dist/index.d.mts +0 -399
  41. package/google/dist/index.d.ts +0 -399
  42. package/google/dist/index.js +0 -954
  43. package/google/dist/index.js.map +0 -1
  44. package/google/dist/index.mjs +0 -918
  45. package/google/dist/index.mjs.map +0 -1
  46. package/mistral/dist/index.d.mts +0 -404
  47. package/mistral/dist/index.d.ts +0 -404
  48. package/mistral/dist/index.js +0 -921
  49. package/mistral/dist/index.js.map +0 -1
  50. package/mistral/dist/index.mjs +0 -885
  51. package/mistral/dist/index.mjs.map +0 -1
  52. package/openai/dist/index.d.mts +0 -468
  53. package/openai/dist/index.d.ts +0 -468
  54. package/openai/dist/index.js +0 -1334
  55. package/openai/dist/index.js.map +0 -1
  56. package/openai/dist/index.mjs +0 -1298
  57. package/openai/dist/index.mjs.map +0 -1
  58. package/spec/dist/index.d.mts +0 -780
  59. package/spec/dist/index.d.ts +0 -780
  60. package/spec/dist/index.js +0 -863
  61. package/spec/dist/index.js.map +0 -1
  62. package/spec/dist/index.mjs +0 -797
  63. package/spec/dist/index.mjs.map +0 -1
@@ -1,950 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // anthropic/index.ts
31
- var anthropic_exports = {};
32
- __export(anthropic_exports, {
33
- Anthropic: () => Anthropic,
34
- anthropic: () => anthropic
35
- });
36
- module.exports = __toCommonJS(anthropic_exports);
37
-
38
- // spec/errors/api-call-error.ts
39
- var APICallError = class extends Error {
40
- constructor({
41
- message,
42
- url,
43
- requestBodyValues,
44
- statusCode,
45
- responseBody,
46
- cause,
47
- isRetryable = statusCode != null && (statusCode === 408 || // request timeout
48
- statusCode === 409 || // conflict
49
- statusCode === 429 || // too many requests
50
- statusCode >= 500),
51
- // server error
52
- data
53
- }) {
54
- super(message);
55
- this.name = "AI_APICallError";
56
- this.url = url;
57
- this.requestBodyValues = requestBodyValues;
58
- this.statusCode = statusCode;
59
- this.responseBody = responseBody;
60
- this.cause = cause;
61
- this.isRetryable = isRetryable;
62
- this.data = data;
63
- }
64
- static isAPICallError(error) {
65
- return error instanceof Error && error.name === "AI_APICallError" && typeof error.url === "string" && typeof error.requestBodyValues === "object" && (error.statusCode == null || typeof error.statusCode === "number") && (error.responseBody == null || typeof error.responseBody === "string") && (error.cause == null || typeof error.cause === "object") && typeof error.isRetryable === "boolean" && (error.data == null || typeof error.data === "object");
66
- }
67
- toJSON() {
68
- return {
69
- name: this.name,
70
- message: this.message,
71
- url: this.url,
72
- requestBodyValues: this.requestBodyValues,
73
- statusCode: this.statusCode,
74
- responseBody: this.responseBody,
75
- cause: this.cause,
76
- isRetryable: this.isRetryable,
77
- data: this.data
78
- };
79
- }
80
- };
81
-
82
- // spec/util/get-error-message.ts
83
- function getErrorMessage(error) {
84
- if (error == null) {
85
- return "unknown error";
86
- }
87
- if (typeof error === "string") {
88
- return error;
89
- }
90
- if (error instanceof Error) {
91
- return error.message;
92
- }
93
- return JSON.stringify(error);
94
- }
95
-
96
- // spec/errors/load-api-key-error.ts
97
- var LoadAPIKeyError = class extends Error {
98
- constructor({ message }) {
99
- super(message);
100
- this.name = "AI_LoadAPIKeyError";
101
- }
102
- static isLoadAPIKeyError(error) {
103
- return error instanceof Error && error.name === "AI_LoadAPIKeyError";
104
- }
105
- toJSON() {
106
- return {
107
- name: this.name,
108
- message: this.message
109
- };
110
- }
111
- };
112
-
113
- // spec/util/load-api-key.ts
114
- function loadApiKey({
115
- apiKey,
116
- environmentVariableName,
117
- apiKeyParameterName = "apiKey",
118
- description
119
- }) {
120
- if (typeof apiKey === "string") {
121
- return apiKey;
122
- }
123
- if (apiKey != null) {
124
- throw new LoadAPIKeyError({
125
- message: `${description} API key must be a string.`
126
- });
127
- }
128
- if (typeof process === "undefined") {
129
- throw new LoadAPIKeyError({
130
- message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
131
- });
132
- }
133
- apiKey = process.env[environmentVariableName];
134
- if (apiKey == null) {
135
- throw new LoadAPIKeyError({
136
- message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
137
- });
138
- }
139
- if (typeof apiKey !== "string") {
140
- throw new LoadAPIKeyError({
141
- message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
142
- });
143
- }
144
- return apiKey;
145
- }
146
-
147
- // spec/util/parse-json.ts
148
- var import_secure_json_parse = __toESM(require("secure-json-parse"));
149
-
150
- // spec/errors/json-parse-error.ts
151
- var JSONParseError = class extends Error {
152
- constructor({ text, cause }) {
153
- super(
154
- `JSON parsing failed: Text: ${text}.
155
- Error message: ${getErrorMessage(cause)}`
156
- );
157
- this.name = "AI_JSONParseError";
158
- this.cause = cause;
159
- this.text = text;
160
- }
161
- static isJSONParseError(error) {
162
- return error instanceof Error && error.name === "AI_JSONParseError" && typeof error.text === "string" && typeof error.cause === "string";
163
- }
164
- toJSON() {
165
- return {
166
- name: this.name,
167
- message: this.message,
168
- cause: this.cause,
169
- stack: this.stack,
170
- valueText: this.text
171
- };
172
- }
173
- };
174
-
175
- // spec/errors/type-validation-error.ts
176
- var TypeValidationError = class extends Error {
177
- constructor({ value, cause }) {
178
- super(
179
- `Type validation failed: Value: ${JSON.stringify(value)}.
180
- Error message: ${getErrorMessage(cause)}`
181
- );
182
- this.name = "AI_TypeValidationError";
183
- this.cause = cause;
184
- this.value = value;
185
- }
186
- static isTypeValidationError(error) {
187
- return error instanceof Error && error.name === "AI_TypeValidationError" && typeof error.value === "string" && typeof error.cause === "string";
188
- }
189
- toJSON() {
190
- return {
191
- name: this.name,
192
- message: this.message,
193
- cause: this.cause,
194
- stack: this.stack,
195
- value: this.value
196
- };
197
- }
198
- };
199
-
200
- // spec/util/validate-types.ts
201
- function validateTypes({
202
- value,
203
- schema
204
- }) {
205
- try {
206
- return schema.parse(value);
207
- } catch (error) {
208
- throw new TypeValidationError({ value, cause: error });
209
- }
210
- }
211
- function safeValidateTypes({
212
- value,
213
- schema
214
- }) {
215
- try {
216
- const validationResult = schema.safeParse(value);
217
- if (validationResult.success) {
218
- return {
219
- success: true,
220
- value: validationResult.data
221
- };
222
- }
223
- return {
224
- success: false,
225
- error: new TypeValidationError({
226
- value,
227
- cause: validationResult.error
228
- })
229
- };
230
- } catch (error) {
231
- return {
232
- success: false,
233
- error: TypeValidationError.isTypeValidationError(error) ? error : new TypeValidationError({ value, cause: error })
234
- };
235
- }
236
- }
237
-
238
- // spec/util/parse-json.ts
239
- function parseJSON({
240
- text,
241
- schema
242
- }) {
243
- try {
244
- const value = import_secure_json_parse.default.parse(text);
245
- if (schema == null) {
246
- return value;
247
- }
248
- return validateTypes({ value, schema });
249
- } catch (error) {
250
- if (JSONParseError.isJSONParseError(error) || TypeValidationError.isTypeValidationError(error)) {
251
- throw error;
252
- }
253
- throw new JSONParseError({ text, cause: error });
254
- }
255
- }
256
- function safeParseJSON({
257
- text,
258
- schema
259
- }) {
260
- try {
261
- const value = import_secure_json_parse.default.parse(text);
262
- if (schema == null) {
263
- return {
264
- success: true,
265
- value
266
- };
267
- }
268
- return safeValidateTypes({ value, schema });
269
- } catch (error) {
270
- return {
271
- success: false,
272
- error: JSONParseError.isJSONParseError(error) ? error : new JSONParseError({ text, cause: error })
273
- };
274
- }
275
- }
276
-
277
- // spec/util/post-to-api.ts
278
- var postJsonToApi = async ({
279
- url,
280
- headers,
281
- body,
282
- failedResponseHandler,
283
- successfulResponseHandler,
284
- abortSignal
285
- }) => postToApi({
286
- url,
287
- headers: {
288
- ...headers,
289
- "Content-Type": "application/json"
290
- },
291
- body: {
292
- content: JSON.stringify(body),
293
- values: body
294
- },
295
- failedResponseHandler,
296
- successfulResponseHandler,
297
- abortSignal
298
- });
299
- var postToApi = async ({
300
- url,
301
- headers = {},
302
- body,
303
- successfulResponseHandler,
304
- failedResponseHandler,
305
- abortSignal
306
- }) => {
307
- try {
308
- const definedHeaders = Object.fromEntries(
309
- Object.entries(headers).filter(([_key, value]) => value != null)
310
- );
311
- const response = await fetch(url, {
312
- method: "POST",
313
- headers: definedHeaders,
314
- body: body.content,
315
- signal: abortSignal
316
- });
317
- if (!response.ok) {
318
- try {
319
- throw await failedResponseHandler({
320
- response,
321
- url,
322
- requestBodyValues: body.values
323
- });
324
- } catch (error) {
325
- if (error instanceof Error) {
326
- if (error.name === "AbortError" || APICallError.isAPICallError(error)) {
327
- throw error;
328
- }
329
- }
330
- throw new APICallError({
331
- message: "Failed to process error response",
332
- cause: error,
333
- statusCode: response.status,
334
- url,
335
- requestBodyValues: body.values
336
- });
337
- }
338
- }
339
- try {
340
- return await successfulResponseHandler({
341
- response,
342
- url,
343
- requestBodyValues: body.values
344
- });
345
- } catch (error) {
346
- if (error instanceof Error) {
347
- if (error.name === "AbortError" || APICallError.isAPICallError(error)) {
348
- throw error;
349
- }
350
- }
351
- throw new APICallError({
352
- message: "Failed to process successful response",
353
- cause: error,
354
- statusCode: response.status,
355
- url,
356
- requestBodyValues: body.values
357
- });
358
- }
359
- } catch (error) {
360
- if (error instanceof Error) {
361
- if (error.name === "AbortError") {
362
- throw error;
363
- }
364
- }
365
- if (error instanceof TypeError && error.message === "fetch failed") {
366
- const cause = error.cause;
367
- if (cause != null) {
368
- throw new APICallError({
369
- message: `Cannot connect to API: ${cause.message}`,
370
- cause,
371
- url,
372
- requestBodyValues: body.values,
373
- isRetryable: true
374
- // retry when network error
375
- });
376
- }
377
- }
378
- throw error;
379
- }
380
- };
381
-
382
- // spec/util/response-handler.ts
383
- var import_stream = require("eventsource-parser/stream");
384
-
385
- // spec/errors/no-response-body-error.ts
386
- var NoResponseBodyError = class extends Error {
387
- constructor({ message = "No response body" } = {}) {
388
- super(message);
389
- this.name = "AI_NoResponseBodyError";
390
- }
391
- static isNoResponseBodyError(error) {
392
- return error instanceof Error && error.name === "AI_NoResponseBodyError";
393
- }
394
- toJSON() {
395
- return {
396
- name: this.name,
397
- message: this.message,
398
- stack: this.stack
399
- };
400
- }
401
- };
402
-
403
- // spec/util/response-handler.ts
404
- var createJsonErrorResponseHandler = ({
405
- errorSchema,
406
- errorToMessage,
407
- isRetryable
408
- }) => async ({ response, url, requestBodyValues }) => {
409
- const responseBody = await response.text();
410
- if (responseBody.trim() === "") {
411
- return new APICallError({
412
- message: response.statusText,
413
- url,
414
- requestBodyValues,
415
- statusCode: response.status,
416
- responseBody,
417
- isRetryable: isRetryable == null ? void 0 : isRetryable(response)
418
- });
419
- }
420
- try {
421
- const parsedError = parseJSON({
422
- text: responseBody,
423
- schema: errorSchema
424
- });
425
- return new APICallError({
426
- message: errorToMessage(parsedError),
427
- url,
428
- requestBodyValues,
429
- statusCode: response.status,
430
- responseBody,
431
- data: parsedError,
432
- isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
433
- });
434
- } catch (parseError) {
435
- return new APICallError({
436
- message: response.statusText,
437
- url,
438
- requestBodyValues,
439
- statusCode: response.status,
440
- responseBody,
441
- isRetryable: isRetryable == null ? void 0 : isRetryable(response)
442
- });
443
- }
444
- };
445
- var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
446
- if (response.body == null) {
447
- throw new NoResponseBodyError();
448
- }
449
- return response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new import_stream.EventSourceParserStream()).pipeThrough(
450
- new TransformStream({
451
- transform({ data }, controller) {
452
- if (data === "[DONE]") {
453
- return;
454
- }
455
- controller.enqueue(
456
- safeParseJSON({
457
- text: data,
458
- schema: chunkSchema
459
- })
460
- );
461
- }
462
- })
463
- );
464
- };
465
- var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
466
- const responseBody = await response.text();
467
- const parsedResult = safeParseJSON({
468
- text: responseBody,
469
- schema: responseSchema
470
- });
471
- if (!parsedResult.success) {
472
- throw new APICallError({
473
- message: "Invalid JSON response",
474
- cause: parsedResult.error,
475
- statusCode: response.status,
476
- responseBody,
477
- url,
478
- requestBodyValues
479
- });
480
- }
481
- return parsedResult.value;
482
- };
483
-
484
- // spec/util/uint8-utils.ts
485
- function convertUint8ArrayToBase64(array) {
486
- let latin1string = "";
487
- for (let i = 0; i < array.length; i++) {
488
- latin1string += String.fromCodePoint(array[i]);
489
- }
490
- return globalThis.btoa(latin1string);
491
- }
492
-
493
- // spec/errors/unsupported-functionality-error.ts
494
- var UnsupportedFunctionalityError = class extends Error {
495
- constructor({ functionality }) {
496
- super(`'${functionality}' functionality not supported.`);
497
- this.name = "AI_UnsupportedFunctionalityError";
498
- this.functionality = functionality;
499
- }
500
- static isUnsupportedFunctionalityError(error) {
501
- return error instanceof Error && error.name === "AI_UnsupportedFunctionalityError" && typeof error.functionality === "string";
502
- }
503
- toJSON() {
504
- return {
505
- name: this.name,
506
- message: this.message,
507
- stack: this.stack,
508
- functionality: this.functionality
509
- };
510
- }
511
- };
512
-
513
- // anthropic/anthropic-messages-language-model.ts
514
- var import_zod2 = require("zod");
515
-
516
- // anthropic/anthropic-error.ts
517
- var import_zod = require("zod");
518
- var anthropicErrorDataSchema = import_zod.z.object({
519
- type: import_zod.z.literal("error"),
520
- error: import_zod.z.object({
521
- type: import_zod.z.string(),
522
- message: import_zod.z.string()
523
- })
524
- });
525
- var anthropicFailedResponseHandler = createJsonErrorResponseHandler({
526
- errorSchema: anthropicErrorDataSchema,
527
- errorToMessage: (data) => data.error.message
528
- });
529
-
530
- // anthropic/convert-to-anthropic-messages-prompt.ts
531
- function convertToAnthropicMessagesPrompt(prompt) {
532
- let system;
533
- const messages = [];
534
- for (const { role, content } of prompt) {
535
- switch (role) {
536
- case "system": {
537
- system = content;
538
- break;
539
- }
540
- case "user": {
541
- messages.push({
542
- role: "user",
543
- content: content.map((part) => {
544
- var _a;
545
- switch (part.type) {
546
- case "text": {
547
- return { type: "text", text: part.text };
548
- }
549
- case "image": {
550
- if (part.image instanceof URL) {
551
- throw new UnsupportedFunctionalityError({
552
- functionality: "URL image parts"
553
- });
554
- } else {
555
- return {
556
- type: "image",
557
- source: {
558
- type: "base64",
559
- media_type: (_a = part.mimeType) != null ? _a : "image/jpeg",
560
- data: convertUint8ArrayToBase64(part.image)
561
- }
562
- };
563
- }
564
- }
565
- }
566
- })
567
- });
568
- break;
569
- }
570
- case "assistant": {
571
- messages.push({
572
- role: "assistant",
573
- content: content.map((part) => {
574
- switch (part.type) {
575
- case "text": {
576
- return { type: "text", text: part.text };
577
- }
578
- case "tool-call": {
579
- return {
580
- type: "tool_use",
581
- id: part.toolCallId,
582
- name: part.toolName,
583
- input: part.args
584
- };
585
- }
586
- }
587
- })
588
- });
589
- break;
590
- }
591
- case "tool": {
592
- messages.push({
593
- role: "user",
594
- content: content.map((part) => ({
595
- type: "tool_result",
596
- tool_use_id: part.toolCallId,
597
- content: JSON.stringify(part.result),
598
- is_error: part.isError
599
- }))
600
- });
601
- break;
602
- }
603
- default: {
604
- const _exhaustiveCheck = role;
605
- throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
606
- }
607
- }
608
- }
609
- return {
610
- system,
611
- messages
612
- };
613
- }
614
-
615
- // anthropic/map-anthropic-stop-reason.ts
616
- function mapAnthropicStopReason(finishReason) {
617
- switch (finishReason) {
618
- case "end_turn":
619
- case "stop_sequence":
620
- return "stop";
621
- case "tool_use":
622
- return "tool-calls";
623
- case "max_tokens":
624
- return "length";
625
- default:
626
- return "other";
627
- }
628
- }
629
-
630
- // anthropic/anthropic-messages-language-model.ts
631
- var AnthropicMessagesLanguageModel = class {
632
- constructor(modelId, settings, config) {
633
- this.specificationVersion = "v1";
634
- this.defaultObjectGenerationMode = "tool";
635
- this.modelId = modelId;
636
- this.settings = settings;
637
- this.config = config;
638
- }
639
- get provider() {
640
- return this.config.provider;
641
- }
642
- getArgs({
643
- mode,
644
- prompt,
645
- maxTokens,
646
- temperature,
647
- topP,
648
- frequencyPenalty,
649
- presencePenalty,
650
- seed
651
- }) {
652
- var _a;
653
- const type = mode.type;
654
- const warnings = [];
655
- if (frequencyPenalty != null) {
656
- warnings.push({
657
- type: "unsupported-setting",
658
- setting: "frequencyPenalty"
659
- });
660
- }
661
- if (presencePenalty != null) {
662
- warnings.push({
663
- type: "unsupported-setting",
664
- setting: "presencePenalty"
665
- });
666
- }
667
- if (seed != null) {
668
- warnings.push({
669
- type: "unsupported-setting",
670
- setting: "seed"
671
- });
672
- }
673
- const messagesPrompt = convertToAnthropicMessagesPrompt(prompt);
674
- const baseArgs = {
675
- // model id:
676
- model: this.modelId,
677
- // model specific settings:
678
- top_k: this.settings.topK,
679
- // standardized settings:
680
- max_tokens: maxTokens != null ? maxTokens : 4096,
681
- // 4096: max model output tokens
682
- temperature,
683
- // uses 0..1 scale
684
- top_p: topP,
685
- // prompt:
686
- system: messagesPrompt.system,
687
- messages: messagesPrompt.messages
688
- };
689
- switch (type) {
690
- case "regular": {
691
- const tools = ((_a = mode.tools) == null ? void 0 : _a.length) ? mode.tools : void 0;
692
- return {
693
- args: {
694
- ...baseArgs,
695
- tools: tools == null ? void 0 : tools.map((tool) => ({
696
- name: tool.name,
697
- description: tool.description,
698
- input_schema: tool.parameters
699
- }))
700
- },
701
- warnings
702
- };
703
- }
704
- case "object-json": {
705
- throw new UnsupportedFunctionalityError({
706
- functionality: "json-mode object generation"
707
- });
708
- }
709
- case "object-tool": {
710
- const { name, description, parameters } = mode.tool;
711
- baseArgs.messages[baseArgs.messages.length - 1].content.push({
712
- type: "text",
713
- text: `
714
-
715
- Use the '${name}' tool.`
716
- });
717
- return {
718
- args: {
719
- ...baseArgs,
720
- tools: [{ name, description, input_schema: parameters }]
721
- },
722
- warnings
723
- };
724
- }
725
- case "object-grammar": {
726
- throw new UnsupportedFunctionalityError({
727
- functionality: "grammar-mode object generation"
728
- });
729
- }
730
- default: {
731
- const _exhaustiveCheck = type;
732
- throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
733
- }
734
- }
735
- }
736
- async doGenerate(options) {
737
- const { args, warnings } = this.getArgs(options);
738
- const response = await postJsonToApi({
739
- url: `${this.config.baseUrl}/messages`,
740
- headers: this.config.headers(),
741
- body: args,
742
- failedResponseHandler: anthropicFailedResponseHandler,
743
- successfulResponseHandler: createJsonResponseHandler(
744
- anthropicMessagesResponseSchema
745
- ),
746
- abortSignal: options.abortSignal
747
- });
748
- const { messages: rawPrompt, ...rawSettings } = args;
749
- let text = "";
750
- for (const content of response.content) {
751
- if (content.type === "text") {
752
- text += content.text;
753
- }
754
- }
755
- let toolCalls = void 0;
756
- if (response.content.some((content) => content.type === "tool_use")) {
757
- toolCalls = [];
758
- for (const content of response.content) {
759
- if (content.type === "tool_use") {
760
- toolCalls.push({
761
- toolCallType: "function",
762
- toolCallId: content.id,
763
- toolName: content.name,
764
- args: JSON.stringify(content.input)
765
- });
766
- }
767
- }
768
- }
769
- return {
770
- text,
771
- toolCalls,
772
- finishReason: mapAnthropicStopReason(response.stop_reason),
773
- usage: {
774
- promptTokens: response.usage.input_tokens,
775
- completionTokens: response.usage.output_tokens
776
- },
777
- rawCall: { rawPrompt, rawSettings },
778
- warnings
779
- };
780
- }
781
- async doStream(options) {
782
- const { args, warnings } = this.getArgs(options);
783
- const response = await postJsonToApi({
784
- url: `${this.config.baseUrl}/messages`,
785
- headers: this.config.headers(),
786
- body: {
787
- ...args,
788
- stream: true
789
- },
790
- failedResponseHandler: anthropicFailedResponseHandler,
791
- successfulResponseHandler: createEventSourceResponseHandler(
792
- anthropicMessagesChunkSchema
793
- ),
794
- abortSignal: options.abortSignal
795
- });
796
- const { messages: rawPrompt, ...rawSettings } = args;
797
- let finishReason = "other";
798
- const usage = {
799
- promptTokens: Number.NaN,
800
- completionTokens: Number.NaN
801
- };
802
- return {
803
- stream: response.pipeThrough(
804
- new TransformStream({
805
- transform(chunk, controller) {
806
- if (!chunk.success) {
807
- controller.enqueue({ type: "error", error: chunk.error });
808
- return;
809
- }
810
- const value = chunk.value;
811
- switch (value.type) {
812
- case "ping":
813
- case "content_block_start":
814
- case "content_block_stop": {
815
- return;
816
- }
817
- case "content_block_delta": {
818
- controller.enqueue({
819
- type: "text-delta",
820
- textDelta: value.delta.text
821
- });
822
- return;
823
- }
824
- case "message_start": {
825
- usage.promptTokens = value.message.usage.input_tokens;
826
- usage.completionTokens = value.message.usage.output_tokens;
827
- return;
828
- }
829
- case "message_delta": {
830
- usage.completionTokens = value.usage.output_tokens;
831
- finishReason = mapAnthropicStopReason(value.delta.stop_reason);
832
- return;
833
- }
834
- case "message_stop": {
835
- controller.enqueue({ type: "finish", finishReason, usage });
836
- return;
837
- }
838
- default: {
839
- const _exhaustiveCheck = value;
840
- throw new Error(`Unsupported chunk type: ${_exhaustiveCheck}`);
841
- }
842
- }
843
- }
844
- })
845
- ),
846
- rawCall: { rawPrompt, rawSettings },
847
- warnings
848
- };
849
- }
850
- };
851
- var anthropicMessagesResponseSchema = import_zod2.z.object({
852
- type: import_zod2.z.literal("message"),
853
- content: import_zod2.z.array(
854
- import_zod2.z.discriminatedUnion("type", [
855
- import_zod2.z.object({
856
- type: import_zod2.z.literal("text"),
857
- text: import_zod2.z.string()
858
- }),
859
- import_zod2.z.object({
860
- type: import_zod2.z.literal("tool_use"),
861
- id: import_zod2.z.string(),
862
- name: import_zod2.z.string(),
863
- input: import_zod2.z.unknown()
864
- })
865
- ])
866
- ),
867
- stop_reason: import_zod2.z.string().optional().nullable(),
868
- usage: import_zod2.z.object({
869
- input_tokens: import_zod2.z.number(),
870
- output_tokens: import_zod2.z.number()
871
- })
872
- });
873
- var anthropicMessagesChunkSchema = import_zod2.z.discriminatedUnion("type", [
874
- import_zod2.z.object({
875
- type: import_zod2.z.literal("message_start"),
876
- message: import_zod2.z.object({
877
- usage: import_zod2.z.object({
878
- input_tokens: import_zod2.z.number(),
879
- output_tokens: import_zod2.z.number()
880
- })
881
- })
882
- }),
883
- import_zod2.z.object({
884
- type: import_zod2.z.literal("content_block_start"),
885
- index: import_zod2.z.number(),
886
- content_block: import_zod2.z.object({
887
- type: import_zod2.z.literal("text"),
888
- text: import_zod2.z.string()
889
- })
890
- }),
891
- import_zod2.z.object({
892
- type: import_zod2.z.literal("content_block_delta"),
893
- index: import_zod2.z.number(),
894
- delta: import_zod2.z.object({
895
- type: import_zod2.z.literal("text_delta"),
896
- text: import_zod2.z.string()
897
- })
898
- }),
899
- import_zod2.z.object({
900
- type: import_zod2.z.literal("content_block_stop"),
901
- index: import_zod2.z.number()
902
- }),
903
- import_zod2.z.object({
904
- type: import_zod2.z.literal("message_delta"),
905
- delta: import_zod2.z.object({ stop_reason: import_zod2.z.string().optional().nullable() }),
906
- usage: import_zod2.z.object({ output_tokens: import_zod2.z.number() })
907
- }),
908
- import_zod2.z.object({
909
- type: import_zod2.z.literal("message_stop")
910
- }),
911
- import_zod2.z.object({
912
- type: import_zod2.z.literal("ping")
913
- })
914
- ]);
915
-
916
- // anthropic/anthropic-facade.ts
917
- var Anthropic = class {
918
- constructor(options = {}) {
919
- this.baseUrl = options.baseUrl;
920
- this.apiKey = options.apiKey;
921
- }
922
- get baseConfig() {
923
- var _a;
924
- return {
925
- baseUrl: (_a = this.baseUrl) != null ? _a : "https://api.anthropic.com/v1",
926
- headers: () => ({
927
- "anthropic-version": "2023-06-01",
928
- "anthropic-beta": "tools-2024-04-04",
929
- "x-api-key": loadApiKey({
930
- apiKey: this.apiKey,
931
- environmentVariableName: "ANTHROPIC_API_KEY",
932
- description: "Anthropic"
933
- })
934
- })
935
- };
936
- }
937
- messages(modelId, settings = {}) {
938
- return new AnthropicMessagesLanguageModel(modelId, settings, {
939
- provider: "anthropic.messages",
940
- ...this.baseConfig
941
- });
942
- }
943
- };
944
- var anthropic = new Anthropic();
945
- // Annotate the CommonJS export names for ESM import in node:
946
- 0 && (module.exports = {
947
- Anthropic,
948
- anthropic
949
- });
950
- //# sourceMappingURL=index.js.map