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