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