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