ai 3.0.17 → 3.0.19

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,964 @@
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({
496
+ provider,
497
+ functionality
498
+ }) {
499
+ super(
500
+ `'${functionality}' functionality not supported by the '${provider}' provider.`
501
+ );
502
+ this.name = "AI_UnsupportedFunctionalityError";
503
+ this.provider = provider;
504
+ this.functionality = functionality;
505
+ }
506
+ static isUnsupportedFunctionalityError(error) {
507
+ return error instanceof Error && error.name === "AI_UnsupportedFunctionalityError" && typeof error.provider === "string" && typeof error.functionality === "string";
508
+ }
509
+ toJSON() {
510
+ return {
511
+ name: this.name,
512
+ message: this.message,
513
+ stack: this.stack,
514
+ provider: this.provider,
515
+ functionality: this.functionality
516
+ };
517
+ }
518
+ };
519
+
520
+ // anthropic/anthropic-messages-language-model.ts
521
+ var import_zod2 = require("zod");
522
+
523
+ // anthropic/anthropic-error.ts
524
+ var import_zod = require("zod");
525
+ var anthropicErrorDataSchema = import_zod.z.object({
526
+ type: import_zod.z.literal("error"),
527
+ error: import_zod.z.object({
528
+ type: import_zod.z.string(),
529
+ message: import_zod.z.string()
530
+ })
531
+ });
532
+ var anthropicFailedResponseHandler = createJsonErrorResponseHandler({
533
+ errorSchema: anthropicErrorDataSchema,
534
+ errorToMessage: (data) => data.error.message
535
+ });
536
+
537
+ // anthropic/convert-to-anthropic-messages-prompt.ts
538
+ function convertToAnthropicMessagesPrompt({
539
+ prompt,
540
+ provider
541
+ }) {
542
+ let system;
543
+ const messages = [];
544
+ for (const { role, content } of prompt) {
545
+ switch (role) {
546
+ case "system": {
547
+ system = content;
548
+ break;
549
+ }
550
+ case "user": {
551
+ messages.push({
552
+ role: "user",
553
+ content: content.map((part) => {
554
+ var _a;
555
+ switch (part.type) {
556
+ case "text": {
557
+ return { type: "text", text: part.text };
558
+ }
559
+ case "image": {
560
+ if (part.image instanceof URL) {
561
+ throw new UnsupportedFunctionalityError({
562
+ provider,
563
+ functionality: "URL image parts"
564
+ });
565
+ } else {
566
+ return {
567
+ type: "image",
568
+ source: {
569
+ type: "base64",
570
+ media_type: (_a = part.mimeType) != null ? _a : "image/jpeg",
571
+ data: convertUint8ArrayToBase64(part.image)
572
+ }
573
+ };
574
+ }
575
+ }
576
+ }
577
+ })
578
+ });
579
+ break;
580
+ }
581
+ case "assistant": {
582
+ messages.push({
583
+ role: "assistant",
584
+ content: content.map((part) => {
585
+ switch (part.type) {
586
+ case "text": {
587
+ return { type: "text", text: part.text };
588
+ }
589
+ case "tool-call": {
590
+ return {
591
+ type: "tool_use",
592
+ id: part.toolCallId,
593
+ name: part.toolName,
594
+ input: part.args
595
+ };
596
+ }
597
+ }
598
+ })
599
+ });
600
+ break;
601
+ }
602
+ case "tool": {
603
+ messages.push({
604
+ role: "user",
605
+ content: content.map((part) => ({
606
+ type: "tool_result",
607
+ tool_use_id: part.toolCallId,
608
+ content: JSON.stringify(part.result)
609
+ }))
610
+ });
611
+ break;
612
+ }
613
+ default: {
614
+ const _exhaustiveCheck = role;
615
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
616
+ }
617
+ }
618
+ }
619
+ return {
620
+ system,
621
+ messages
622
+ };
623
+ }
624
+
625
+ // anthropic/map-anthropic-stop-reason.ts
626
+ function mapAnthropicStopReason(finishReason) {
627
+ switch (finishReason) {
628
+ case "end_turn":
629
+ case "stop_sequence":
630
+ return "stop";
631
+ case "tool_use":
632
+ return "tool-calls";
633
+ case "max_tokens":
634
+ return "length";
635
+ default:
636
+ return "other";
637
+ }
638
+ }
639
+
640
+ // anthropic/anthropic-messages-language-model.ts
641
+ var AnthropicMessagesLanguageModel = class {
642
+ constructor(modelId, settings, config) {
643
+ this.specificationVersion = "v1";
644
+ this.defaultObjectGenerationMode = "tool";
645
+ this.modelId = modelId;
646
+ this.settings = settings;
647
+ this.config = config;
648
+ }
649
+ get provider() {
650
+ return this.config.provider;
651
+ }
652
+ getArgs({
653
+ mode,
654
+ prompt,
655
+ maxTokens,
656
+ temperature,
657
+ topP,
658
+ frequencyPenalty,
659
+ presencePenalty,
660
+ seed
661
+ }) {
662
+ var _a;
663
+ const type = mode.type;
664
+ const warnings = [];
665
+ if (frequencyPenalty != null) {
666
+ warnings.push({
667
+ type: "unsupported-setting",
668
+ setting: "frequencyPenalty"
669
+ });
670
+ }
671
+ if (presencePenalty != null) {
672
+ warnings.push({
673
+ type: "unsupported-setting",
674
+ setting: "presencePenalty"
675
+ });
676
+ }
677
+ if (seed != null) {
678
+ warnings.push({
679
+ type: "unsupported-setting",
680
+ setting: "seed"
681
+ });
682
+ }
683
+ const messagesPrompt = convertToAnthropicMessagesPrompt({
684
+ provider: this.provider,
685
+ prompt
686
+ });
687
+ const baseArgs = {
688
+ // model id:
689
+ model: this.modelId,
690
+ // model specific settings:
691
+ top_k: this.settings.topK,
692
+ // standardized settings:
693
+ max_tokens: maxTokens != null ? maxTokens : 4096,
694
+ // 4096: max model output tokens
695
+ temperature,
696
+ // uses 0..1 scale
697
+ top_p: topP,
698
+ // prompt:
699
+ system: messagesPrompt.system,
700
+ messages: messagesPrompt.messages
701
+ };
702
+ switch (type) {
703
+ case "regular": {
704
+ const tools = ((_a = mode.tools) == null ? void 0 : _a.length) ? mode.tools : void 0;
705
+ return {
706
+ args: {
707
+ ...baseArgs,
708
+ tools: tools == null ? void 0 : tools.map((tool) => ({
709
+ name: tool.name,
710
+ description: tool.description,
711
+ input_schema: tool.parameters
712
+ }))
713
+ },
714
+ warnings
715
+ };
716
+ }
717
+ case "object-json": {
718
+ throw new UnsupportedFunctionalityError({
719
+ functionality: "json-mode object generation",
720
+ provider: this.provider
721
+ });
722
+ }
723
+ case "object-tool": {
724
+ return {
725
+ args: {
726
+ ...baseArgs,
727
+ tools: [
728
+ {
729
+ name: mode.tool.name,
730
+ description: mode.tool.description,
731
+ input_schema: mode.tool.parameters
732
+ }
733
+ ]
734
+ },
735
+ warnings
736
+ };
737
+ }
738
+ case "object-grammar": {
739
+ throw new UnsupportedFunctionalityError({
740
+ functionality: "grammar-mode object generation",
741
+ provider: this.provider
742
+ });
743
+ }
744
+ default: {
745
+ const _exhaustiveCheck = type;
746
+ throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
747
+ }
748
+ }
749
+ }
750
+ async doGenerate(options) {
751
+ const { args, warnings } = this.getArgs(options);
752
+ const response = await postJsonToApi({
753
+ url: `${this.config.baseUrl}/messages`,
754
+ headers: this.config.headers(),
755
+ body: args,
756
+ failedResponseHandler: anthropicFailedResponseHandler,
757
+ successfulResponseHandler: createJsonResponseHandler(
758
+ anthropicMessagesResponseSchema
759
+ ),
760
+ abortSignal: options.abortSignal
761
+ });
762
+ const { messages: rawPrompt, ...rawSettings } = args;
763
+ let text = "";
764
+ for (const content of response.content) {
765
+ if (content.type === "text") {
766
+ text += content.text;
767
+ }
768
+ }
769
+ let toolCalls = void 0;
770
+ if (response.content.some((content) => content.type === "tool_use")) {
771
+ toolCalls = [];
772
+ for (const content of response.content) {
773
+ if (content.type === "tool_use") {
774
+ toolCalls.push({
775
+ toolCallType: "function",
776
+ toolCallId: content.id,
777
+ toolName: content.name,
778
+ args: JSON.stringify(content.input)
779
+ });
780
+ }
781
+ }
782
+ }
783
+ return {
784
+ text,
785
+ toolCalls,
786
+ finishReason: mapAnthropicStopReason(response.stop_reason),
787
+ usage: {
788
+ promptTokens: response.usage.input_tokens,
789
+ completionTokens: response.usage.output_tokens
790
+ },
791
+ rawCall: { rawPrompt, rawSettings },
792
+ warnings
793
+ };
794
+ }
795
+ async doStream(options) {
796
+ const { args, warnings } = this.getArgs(options);
797
+ const response = await postJsonToApi({
798
+ url: `${this.config.baseUrl}/messages`,
799
+ headers: this.config.headers(),
800
+ body: {
801
+ ...args,
802
+ stream: true
803
+ },
804
+ failedResponseHandler: anthropicFailedResponseHandler,
805
+ successfulResponseHandler: createEventSourceResponseHandler(
806
+ anthropicMessagesChunkSchema
807
+ ),
808
+ abortSignal: options.abortSignal
809
+ });
810
+ const { messages: rawPrompt, ...rawSettings } = args;
811
+ let finishReason = "other";
812
+ const usage = {
813
+ promptTokens: Number.NaN,
814
+ completionTokens: Number.NaN
815
+ };
816
+ return {
817
+ stream: response.pipeThrough(
818
+ new TransformStream({
819
+ transform(chunk, controller) {
820
+ if (!chunk.success) {
821
+ controller.enqueue({ type: "error", error: chunk.error });
822
+ return;
823
+ }
824
+ const value = chunk.value;
825
+ switch (value.type) {
826
+ case "ping":
827
+ case "content_block_start":
828
+ case "content_block_stop": {
829
+ return;
830
+ }
831
+ case "content_block_delta": {
832
+ controller.enqueue({
833
+ type: "text-delta",
834
+ textDelta: value.delta.text
835
+ });
836
+ return;
837
+ }
838
+ case "message_start": {
839
+ usage.promptTokens = value.message.usage.input_tokens;
840
+ usage.completionTokens = value.message.usage.output_tokens;
841
+ return;
842
+ }
843
+ case "message_delta": {
844
+ usage.completionTokens = value.usage.output_tokens;
845
+ finishReason = mapAnthropicStopReason(value.delta.stop_reason);
846
+ return;
847
+ }
848
+ case "message_stop": {
849
+ controller.enqueue({ type: "finish", finishReason, usage });
850
+ return;
851
+ }
852
+ default: {
853
+ const _exhaustiveCheck = value;
854
+ throw new Error(`Unsupported chunk type: ${_exhaustiveCheck}`);
855
+ }
856
+ }
857
+ }
858
+ })
859
+ ),
860
+ rawCall: { rawPrompt, rawSettings },
861
+ warnings
862
+ };
863
+ }
864
+ };
865
+ var anthropicMessagesResponseSchema = import_zod2.z.object({
866
+ type: import_zod2.z.literal("message"),
867
+ content: import_zod2.z.array(
868
+ import_zod2.z.discriminatedUnion("type", [
869
+ import_zod2.z.object({
870
+ type: import_zod2.z.literal("text"),
871
+ text: import_zod2.z.string()
872
+ }),
873
+ import_zod2.z.object({
874
+ type: import_zod2.z.literal("tool_use"),
875
+ id: import_zod2.z.string(),
876
+ name: import_zod2.z.string(),
877
+ input: import_zod2.z.unknown()
878
+ })
879
+ ])
880
+ ),
881
+ stop_reason: import_zod2.z.string().optional().nullable(),
882
+ usage: import_zod2.z.object({
883
+ input_tokens: import_zod2.z.number(),
884
+ output_tokens: import_zod2.z.number()
885
+ })
886
+ });
887
+ var anthropicMessagesChunkSchema = import_zod2.z.discriminatedUnion("type", [
888
+ import_zod2.z.object({
889
+ type: import_zod2.z.literal("message_start"),
890
+ message: import_zod2.z.object({
891
+ usage: import_zod2.z.object({
892
+ input_tokens: import_zod2.z.number(),
893
+ output_tokens: import_zod2.z.number()
894
+ })
895
+ })
896
+ }),
897
+ import_zod2.z.object({
898
+ type: import_zod2.z.literal("content_block_start"),
899
+ index: import_zod2.z.number(),
900
+ content_block: import_zod2.z.object({
901
+ type: import_zod2.z.literal("text"),
902
+ text: import_zod2.z.string()
903
+ })
904
+ }),
905
+ import_zod2.z.object({
906
+ type: import_zod2.z.literal("content_block_delta"),
907
+ index: import_zod2.z.number(),
908
+ delta: import_zod2.z.object({
909
+ type: import_zod2.z.literal("text_delta"),
910
+ text: import_zod2.z.string()
911
+ })
912
+ }),
913
+ import_zod2.z.object({
914
+ type: import_zod2.z.literal("content_block_stop"),
915
+ index: import_zod2.z.number()
916
+ }),
917
+ import_zod2.z.object({
918
+ type: import_zod2.z.literal("message_delta"),
919
+ delta: import_zod2.z.object({ stop_reason: import_zod2.z.string().optional().nullable() }),
920
+ usage: import_zod2.z.object({ output_tokens: import_zod2.z.number() })
921
+ }),
922
+ import_zod2.z.object({
923
+ type: import_zod2.z.literal("message_stop")
924
+ }),
925
+ import_zod2.z.object({
926
+ type: import_zod2.z.literal("ping")
927
+ })
928
+ ]);
929
+
930
+ // anthropic/anthropic-facade.ts
931
+ var Anthropic = class {
932
+ constructor(options = {}) {
933
+ this.baseUrl = options.baseUrl;
934
+ this.apiKey = options.apiKey;
935
+ }
936
+ get baseConfig() {
937
+ var _a;
938
+ return {
939
+ baseUrl: (_a = this.baseUrl) != null ? _a : "https://api.anthropic.com/v1",
940
+ headers: () => ({
941
+ "anthropic-version": "2023-06-01",
942
+ "anthropic-beta": "tools-2024-04-04",
943
+ "x-api-key": loadApiKey({
944
+ apiKey: this.apiKey,
945
+ environmentVariableName: "ANTHROPIC_API_KEY",
946
+ description: "Anthropic"
947
+ })
948
+ })
949
+ };
950
+ }
951
+ messages(modelId, settings = {}) {
952
+ return new AnthropicMessagesLanguageModel(modelId, settings, {
953
+ provider: "anthropic.messages",
954
+ ...this.baseConfig
955
+ });
956
+ }
957
+ };
958
+ var anthropic = new Anthropic();
959
+ // Annotate the CommonJS export names for ESM import in node:
960
+ 0 && (module.exports = {
961
+ Anthropic,
962
+ anthropic
963
+ });
964
+ //# sourceMappingURL=index.js.map