ai 3.0.16 → 3.0.18

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