ai 3.0.16 → 3.0.17

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