ai 3.0.20 → 3.0.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/index.d.mts +45 -354
  2. package/dist/index.d.ts +45 -354
  3. package/dist/index.js +161 -460
  4. package/dist/index.js.map +1 -1
  5. package/dist/index.mjs +136 -430
  6. package/dist/index.mjs.map +1 -1
  7. package/package.json +6 -41
  8. package/react/dist/index.d.mts +1 -1
  9. package/react/dist/index.d.ts +1 -1
  10. package/react/dist/index.js +3 -3
  11. package/react/dist/index.js.map +1 -1
  12. package/react/dist/index.mjs +3 -3
  13. package/react/dist/index.mjs.map +1 -1
  14. package/rsc/dist/rsc-server.mjs +3 -3
  15. package/rsc/dist/rsc-server.mjs.map +1 -1
  16. package/solid/dist/index.d.mts +1 -1
  17. package/solid/dist/index.d.ts +1 -1
  18. package/solid/dist/index.js +3 -3
  19. package/solid/dist/index.js.map +1 -1
  20. package/solid/dist/index.mjs +3 -3
  21. package/solid/dist/index.mjs.map +1 -1
  22. package/svelte/dist/index.d.mts +1 -1
  23. package/svelte/dist/index.d.ts +1 -1
  24. package/svelte/dist/index.js +3 -3
  25. package/svelte/dist/index.js.map +1 -1
  26. package/svelte/dist/index.mjs +3 -3
  27. package/svelte/dist/index.mjs.map +1 -1
  28. package/vue/dist/index.d.mts +1 -1
  29. package/vue/dist/index.d.ts +1 -1
  30. package/vue/dist/index.js +3 -3
  31. package/vue/dist/index.js.map +1 -1
  32. package/vue/dist/index.mjs +3 -3
  33. package/vue/dist/index.mjs.map +1 -1
  34. package/anthropic/dist/index.d.mts +0 -403
  35. package/anthropic/dist/index.d.ts +0 -403
  36. package/anthropic/dist/index.js +0 -950
  37. package/anthropic/dist/index.js.map +0 -1
  38. package/anthropic/dist/index.mjs +0 -914
  39. package/anthropic/dist/index.mjs.map +0 -1
  40. package/google/dist/index.d.mts +0 -399
  41. package/google/dist/index.d.ts +0 -399
  42. package/google/dist/index.js +0 -954
  43. package/google/dist/index.js.map +0 -1
  44. package/google/dist/index.mjs +0 -918
  45. package/google/dist/index.mjs.map +0 -1
  46. package/mistral/dist/index.d.mts +0 -404
  47. package/mistral/dist/index.d.ts +0 -404
  48. package/mistral/dist/index.js +0 -921
  49. package/mistral/dist/index.js.map +0 -1
  50. package/mistral/dist/index.mjs +0 -885
  51. package/mistral/dist/index.mjs.map +0 -1
  52. package/openai/dist/index.d.mts +0 -468
  53. package/openai/dist/index.d.ts +0 -468
  54. package/openai/dist/index.js +0 -1334
  55. package/openai/dist/index.js.map +0 -1
  56. package/openai/dist/index.mjs +0 -1298
  57. package/openai/dist/index.mjs.map +0 -1
  58. package/spec/dist/index.d.mts +0 -780
  59. package/spec/dist/index.d.ts +0 -780
  60. package/spec/dist/index.js +0 -863
  61. package/spec/dist/index.js.map +0 -1
  62. package/spec/dist/index.mjs +0 -797
  63. package/spec/dist/index.mjs.map +0 -1
@@ -1,954 +0,0 @@
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
- // google/index.ts
31
- var google_exports = {};
32
- __export(google_exports, {
33
- Google: () => Google,
34
- google: () => google
35
- });
36
- module.exports = __toCommonJS(google_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 = (chunkSchema2) => 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: chunkSchema2
466
- })
467
- );
468
- }
469
- })
470
- );
471
- };
472
- var createJsonResponseHandler = (responseSchema2) => async ({ response, url, requestBodyValues }) => {
473
- const responseBody = await response.text();
474
- const parsedResult = safeParseJSON({
475
- text: responseBody,
476
- schema: responseSchema2
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({ functionality }) {
503
- super(`'${functionality}' functionality not supported.`);
504
- this.name = "AI_UnsupportedFunctionalityError";
505
- this.functionality = functionality;
506
- }
507
- static isUnsupportedFunctionalityError(error) {
508
- return error instanceof Error && error.name === "AI_UnsupportedFunctionalityError" && typeof error.functionality === "string";
509
- }
510
- toJSON() {
511
- return {
512
- name: this.name,
513
- message: this.message,
514
- stack: this.stack,
515
- functionality: this.functionality
516
- };
517
- }
518
- };
519
-
520
- // google/google-generative-ai-language-model.ts
521
- var import_zod2 = require("zod");
522
-
523
- // google/convert-to-google-generative-ai-messages.ts
524
- function convertToGoogleGenerativeAIMessages(prompt) {
525
- const messages = [];
526
- for (const { role, content } of prompt) {
527
- switch (role) {
528
- case "system": {
529
- messages.push({ role: "user", parts: [{ text: content }] });
530
- messages.push({ role: "model", parts: [{ text: "" }] });
531
- break;
532
- }
533
- case "user": {
534
- messages.push({
535
- role: "user",
536
- parts: content.map((part) => {
537
- var _a;
538
- switch (part.type) {
539
- case "text": {
540
- return { text: part.text };
541
- }
542
- case "image": {
543
- if (part.image instanceof URL) {
544
- throw new UnsupportedFunctionalityError({
545
- functionality: "URL image parts"
546
- });
547
- } else {
548
- return {
549
- inlineData: {
550
- mimeType: (_a = part.mimeType) != null ? _a : "image/jpeg",
551
- data: convertUint8ArrayToBase64(part.image)
552
- }
553
- };
554
- }
555
- }
556
- }
557
- })
558
- });
559
- break;
560
- }
561
- case "assistant": {
562
- messages.push({
563
- role: "model",
564
- parts: content.map((part) => {
565
- switch (part.type) {
566
- case "text": {
567
- return part.text.length === 0 ? void 0 : { text: part.text };
568
- }
569
- case "tool-call": {
570
- return {
571
- functionCall: {
572
- name: part.toolName,
573
- args: part.args
574
- }
575
- };
576
- }
577
- }
578
- }).filter(
579
- (part) => part !== void 0
580
- )
581
- });
582
- break;
583
- }
584
- case "tool": {
585
- messages.push({
586
- role: "user",
587
- parts: content.map((part) => ({
588
- functionResponse: {
589
- name: part.toolName,
590
- response: part.result
591
- }
592
- }))
593
- });
594
- break;
595
- }
596
- default: {
597
- const _exhaustiveCheck = role;
598
- throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
599
- }
600
- }
601
- }
602
- return messages;
603
- }
604
-
605
- // google/google-error.ts
606
- var import_zod = require("zod");
607
- var googleErrorDataSchema = import_zod.z.object({
608
- error: import_zod.z.object({
609
- code: import_zod.z.number().nullable(),
610
- message: import_zod.z.string(),
611
- status: import_zod.z.string()
612
- })
613
- });
614
- var googleFailedResponseHandler = createJsonErrorResponseHandler({
615
- errorSchema: googleErrorDataSchema,
616
- errorToMessage: (data) => data.error.message
617
- });
618
-
619
- // google/map-google-generative-ai-finish-reason.ts
620
- function mapGoogleGenerativeAIFinishReason({
621
- finishReason,
622
- hasToolCalls
623
- }) {
624
- switch (finishReason) {
625
- case "STOP":
626
- return hasToolCalls ? "tool-calls" : "stop";
627
- case "MAX_TOKENS":
628
- return "length";
629
- case "RECITATION":
630
- case "SAFETY":
631
- return "content-filter";
632
- case "FINISH_REASON_UNSPECIFIED":
633
- case "OTHER":
634
- default:
635
- return "other";
636
- }
637
- }
638
-
639
- // google/google-generative-ai-language-model.ts
640
- var GoogleGenerativeAILanguageModel = class {
641
- constructor(modelId, settings, config) {
642
- this.specificationVersion = "v1";
643
- this.defaultObjectGenerationMode = void 0;
644
- this.modelId = modelId;
645
- this.settings = settings;
646
- this.config = config;
647
- }
648
- get provider() {
649
- return this.config.provider;
650
- }
651
- getArgs({
652
- mode,
653
- prompt,
654
- maxTokens,
655
- temperature,
656
- topP,
657
- frequencyPenalty,
658
- presencePenalty,
659
- seed
660
- }) {
661
- var _a;
662
- const type = mode.type;
663
- const warnings = [];
664
- if (frequencyPenalty != null) {
665
- warnings.push({
666
- type: "unsupported-setting",
667
- setting: "frequencyPenalty"
668
- });
669
- }
670
- if (presencePenalty != null) {
671
- warnings.push({
672
- type: "unsupported-setting",
673
- setting: "presencePenalty"
674
- });
675
- }
676
- if (seed != null) {
677
- warnings.push({
678
- type: "unsupported-setting",
679
- setting: "seed"
680
- });
681
- }
682
- const baseArgs = {
683
- generationConfig: {
684
- // model specific settings:
685
- topK: this.settings.topK,
686
- // standardized settings:
687
- maxOutputTokens: maxTokens,
688
- temperature,
689
- topP
690
- },
691
- // prompt:
692
- contents: convertToGoogleGenerativeAIMessages(prompt)
693
- };
694
- switch (type) {
695
- case "regular": {
696
- const functionDeclarations = (_a = mode.tools) == null ? void 0 : _a.map((tool) => {
697
- var _a2;
698
- return {
699
- name: tool.name,
700
- description: (_a2 = tool.description) != null ? _a2 : "",
701
- parameters: prepareJsonSchema(tool.parameters)
702
- };
703
- });
704
- return {
705
- args: {
706
- ...baseArgs,
707
- tools: functionDeclarations == null ? void 0 : { functionDeclarations }
708
- },
709
- warnings
710
- };
711
- }
712
- case "object-json": {
713
- throw new UnsupportedFunctionalityError({
714
- functionality: "object-json mode"
715
- });
716
- }
717
- case "object-tool": {
718
- throw new UnsupportedFunctionalityError({
719
- functionality: "object-tool mode"
720
- });
721
- }
722
- case "object-grammar": {
723
- throw new UnsupportedFunctionalityError({
724
- functionality: "object-grammar mode"
725
- });
726
- }
727
- default: {
728
- const _exhaustiveCheck = type;
729
- throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
730
- }
731
- }
732
- }
733
- async doGenerate(options) {
734
- var _a;
735
- const { args, warnings } = this.getArgs(options);
736
- const response = await postJsonToApi({
737
- url: `${this.config.baseUrl}/${this.modelId}:generateContent`,
738
- headers: this.config.headers(),
739
- body: args,
740
- failedResponseHandler: googleFailedResponseHandler,
741
- successfulResponseHandler: createJsonResponseHandler(responseSchema),
742
- abortSignal: options.abortSignal
743
- });
744
- const { contents: rawPrompt, ...rawSettings } = args;
745
- const candidate = response.candidates[0];
746
- const toolCalls = getToolCallsFromParts({
747
- parts: candidate.content.parts,
748
- generateId: this.config.generateId
749
- });
750
- return {
751
- text: getTextFromParts(candidate.content.parts),
752
- toolCalls,
753
- finishReason: mapGoogleGenerativeAIFinishReason({
754
- finishReason: candidate.finishReason,
755
- hasToolCalls: toolCalls != null && toolCalls.length > 0
756
- }),
757
- usage: {
758
- promptTokens: NaN,
759
- completionTokens: (_a = candidate.tokenCount) != null ? _a : NaN
760
- },
761
- rawCall: { rawPrompt, rawSettings },
762
- warnings
763
- };
764
- }
765
- async doStream(options) {
766
- const { args, warnings } = this.getArgs(options);
767
- const response = await postJsonToApi({
768
- url: `${this.config.baseUrl}/${this.modelId}:streamGenerateContent?alt=sse`,
769
- headers: this.config.headers(),
770
- body: args,
771
- failedResponseHandler: googleFailedResponseHandler,
772
- successfulResponseHandler: createEventSourceResponseHandler(chunkSchema),
773
- abortSignal: options.abortSignal
774
- });
775
- const { contents: rawPrompt, ...rawSettings } = args;
776
- let finishReason = "other";
777
- let usage = {
778
- promptTokens: Number.NaN,
779
- completionTokens: Number.NaN
780
- };
781
- const generateId2 = this.config.generateId;
782
- let hasToolCalls = false;
783
- return {
784
- stream: response.pipeThrough(
785
- new TransformStream({
786
- transform(chunk, controller) {
787
- if (!chunk.success) {
788
- controller.enqueue({ type: "error", error: chunk.error });
789
- return;
790
- }
791
- const value = chunk.value;
792
- const candidate = value.candidates[0];
793
- if ((candidate == null ? void 0 : candidate.finishReason) != null) {
794
- finishReason = mapGoogleGenerativeAIFinishReason({
795
- finishReason: candidate.finishReason,
796
- hasToolCalls
797
- });
798
- }
799
- if (candidate.tokenCount != null) {
800
- usage = {
801
- promptTokens: NaN,
802
- completionTokens: candidate.tokenCount
803
- };
804
- }
805
- const content = candidate.content;
806
- if (content == null) {
807
- return;
808
- }
809
- const deltaText = getTextFromParts(content.parts);
810
- if (deltaText != null) {
811
- controller.enqueue({
812
- type: "text-delta",
813
- textDelta: deltaText
814
- });
815
- }
816
- const toolCallDeltas = getToolCallsFromParts({
817
- parts: content.parts,
818
- generateId: generateId2
819
- });
820
- if (toolCallDeltas != null) {
821
- for (const toolCall of toolCallDeltas) {
822
- controller.enqueue({
823
- type: "tool-call-delta",
824
- toolCallType: "function",
825
- toolCallId: toolCall.toolCallId,
826
- toolName: toolCall.toolName,
827
- argsTextDelta: toolCall.args
828
- });
829
- controller.enqueue({
830
- type: "tool-call",
831
- toolCallType: "function",
832
- toolCallId: toolCall.toolCallId,
833
- toolName: toolCall.toolName,
834
- args: toolCall.args
835
- });
836
- hasToolCalls = true;
837
- }
838
- }
839
- },
840
- flush(controller) {
841
- controller.enqueue({ type: "finish", finishReason, usage });
842
- }
843
- })
844
- ),
845
- rawCall: { rawPrompt, rawSettings },
846
- warnings
847
- };
848
- }
849
- };
850
- function prepareJsonSchema(jsonSchema) {
851
- if (typeof jsonSchema !== "object") {
852
- return jsonSchema;
853
- }
854
- if (Array.isArray(jsonSchema)) {
855
- return jsonSchema.map(prepareJsonSchema);
856
- }
857
- const result = {};
858
- for (const [key, value] of Object.entries(jsonSchema)) {
859
- if (key === "additionalProperties" || key === "$schema") {
860
- continue;
861
- }
862
- result[key] = prepareJsonSchema(value);
863
- }
864
- return result;
865
- }
866
- function getToolCallsFromParts({
867
- parts,
868
- generateId: generateId2
869
- }) {
870
- const functionCallParts = parts.filter(
871
- (part) => "functionCall" in part
872
- );
873
- return functionCallParts.length === 0 ? void 0 : functionCallParts.map((part) => ({
874
- toolCallType: "function",
875
- toolCallId: generateId2(),
876
- toolName: part.functionCall.name,
877
- args: JSON.stringify(part.functionCall.args)
878
- }));
879
- }
880
- function getTextFromParts(parts) {
881
- const textParts = parts.filter((part) => "text" in part);
882
- return textParts.length === 0 ? void 0 : textParts.map((part) => part.text).join("");
883
- }
884
- var contentSchema = import_zod2.z.object({
885
- role: import_zod2.z.string(),
886
- parts: import_zod2.z.array(
887
- import_zod2.z.union([
888
- import_zod2.z.object({
889
- text: import_zod2.z.string()
890
- }),
891
- import_zod2.z.object({
892
- functionCall: import_zod2.z.object({
893
- name: import_zod2.z.string(),
894
- args: import_zod2.z.unknown()
895
- })
896
- })
897
- ])
898
- )
899
- });
900
- var responseSchema = import_zod2.z.object({
901
- candidates: import_zod2.z.array(
902
- import_zod2.z.object({
903
- content: contentSchema,
904
- finishReason: import_zod2.z.string().optional(),
905
- tokenCount: import_zod2.z.number().optional()
906
- })
907
- )
908
- });
909
- var chunkSchema = import_zod2.z.object({
910
- candidates: import_zod2.z.array(
911
- import_zod2.z.object({
912
- content: contentSchema.optional(),
913
- finishReason: import_zod2.z.string().optional(),
914
- tokenCount: import_zod2.z.number().optional()
915
- })
916
- )
917
- });
918
-
919
- // google/google-facade.ts
920
- var Google = class {
921
- constructor(options = {}) {
922
- var _a;
923
- this.baseUrl = options.baseUrl;
924
- this.apiKey = options.apiKey;
925
- this.generateId = (_a = options.generateId) != null ? _a : generateId;
926
- }
927
- get baseConfig() {
928
- var _a;
929
- return {
930
- baseUrl: (_a = this.baseUrl) != null ? _a : "https://generativelanguage.googleapis.com/v1beta",
931
- headers: () => ({
932
- "x-goog-api-key": loadApiKey({
933
- apiKey: this.apiKey,
934
- environmentVariableName: "GOOGLE_GENERATIVE_AI_API_KEY",
935
- description: "Google Generative AI"
936
- })
937
- })
938
- };
939
- }
940
- generativeAI(modelId, settings = {}) {
941
- return new GoogleGenerativeAILanguageModel(modelId, settings, {
942
- provider: "google.generative-ai",
943
- ...this.baseConfig,
944
- generateId: this.generateId
945
- });
946
- }
947
- };
948
- var google = new Google();
949
- // Annotate the CommonJS export names for ESM import in node:
950
- 0 && (module.exports = {
951
- Google,
952
- google
953
- });
954
- //# sourceMappingURL=index.js.map