@ai-sdk/google 2.0.0-canary.0 → 2.0.0-canary.10

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.
package/dist/index.mjs CHANGED
@@ -1,24 +1,137 @@
1
1
  // src/google-provider.ts
2
+ import {
3
+ NoSuchModelError
4
+ } from "@ai-sdk/provider";
2
5
  import {
3
6
  generateId,
4
7
  loadApiKey,
5
8
  withoutTrailingSlash
6
9
  } from "@ai-sdk/provider-utils";
7
10
 
8
- // src/google-generative-ai-language-model.ts
11
+ // src/google-generative-ai-embedding-model.ts
12
+ import {
13
+ TooManyEmbeddingValuesForCallError
14
+ } from "@ai-sdk/provider";
9
15
  import {
10
16
  combineHeaders,
11
- createEventSourceResponseHandler,
12
17
  createJsonResponseHandler,
13
18
  parseProviderOptions,
14
19
  postJsonToApi,
15
20
  resolve
16
21
  } from "@ai-sdk/provider-utils";
22
+ import { z as z3 } from "zod";
23
+
24
+ // src/google-error.ts
25
+ import { createJsonErrorResponseHandler } from "@ai-sdk/provider-utils";
26
+ import { z } from "zod";
27
+ var googleErrorDataSchema = z.object({
28
+ error: z.object({
29
+ code: z.number().nullable(),
30
+ message: z.string(),
31
+ status: z.string()
32
+ })
33
+ });
34
+ var googleFailedResponseHandler = createJsonErrorResponseHandler({
35
+ errorSchema: googleErrorDataSchema,
36
+ errorToMessage: (data) => data.error.message
37
+ });
38
+
39
+ // src/google-generative-ai-embedding-options.ts
17
40
  import { z as z2 } from "zod";
41
+ var googleGenerativeAIEmbeddingProviderOptions = z2.object({
42
+ /**
43
+ * Optional. Optional reduced dimension for the output embedding.
44
+ * If set, excessive values in the output embedding are truncated from the end.
45
+ */
46
+ outputDimensionality: z2.number().optional()
47
+ });
48
+
49
+ // src/google-generative-ai-embedding-model.ts
50
+ var GoogleGenerativeAIEmbeddingModel = class {
51
+ constructor(modelId, config) {
52
+ this.specificationVersion = "v2";
53
+ this.modelId = modelId;
54
+ this.config = config;
55
+ }
56
+ get provider() {
57
+ return this.config.provider;
58
+ }
59
+ get maxEmbeddingsPerCall() {
60
+ return 2048;
61
+ }
62
+ get supportsParallelCalls() {
63
+ return true;
64
+ }
65
+ async doEmbed({
66
+ values,
67
+ headers,
68
+ abortSignal,
69
+ providerOptions
70
+ }) {
71
+ var _a;
72
+ const googleOptions = (_a = parseProviderOptions({
73
+ provider: "google",
74
+ providerOptions,
75
+ schema: googleGenerativeAIEmbeddingProviderOptions
76
+ })) != null ? _a : {};
77
+ if (values.length > this.maxEmbeddingsPerCall) {
78
+ throw new TooManyEmbeddingValuesForCallError({
79
+ provider: this.provider,
80
+ modelId: this.modelId,
81
+ maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
82
+ values
83
+ });
84
+ }
85
+ const mergedHeaders = combineHeaders(
86
+ await resolve(this.config.headers),
87
+ headers
88
+ );
89
+ const {
90
+ responseHeaders,
91
+ value: response,
92
+ rawValue
93
+ } = await postJsonToApi({
94
+ url: `${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,
95
+ headers: mergedHeaders,
96
+ body: {
97
+ requests: values.map((value) => ({
98
+ model: `models/${this.modelId}`,
99
+ content: { role: "user", parts: [{ text: value }] },
100
+ outputDimensionality: googleOptions.outputDimensionality
101
+ }))
102
+ },
103
+ failedResponseHandler: googleFailedResponseHandler,
104
+ successfulResponseHandler: createJsonResponseHandler(
105
+ googleGenerativeAITextEmbeddingResponseSchema
106
+ ),
107
+ abortSignal,
108
+ fetch: this.config.fetch
109
+ });
110
+ return {
111
+ embeddings: response.embeddings.map((item) => item.values),
112
+ usage: void 0,
113
+ response: { headers: responseHeaders, body: rawValue }
114
+ };
115
+ }
116
+ };
117
+ var googleGenerativeAITextEmbeddingResponseSchema = z3.object({
118
+ embeddings: z3.array(z3.object({ values: z3.array(z3.number()) }))
119
+ });
120
+
121
+ // src/google-generative-ai-language-model.ts
122
+ import {
123
+ combineHeaders as combineHeaders2,
124
+ createEventSourceResponseHandler,
125
+ createJsonResponseHandler as createJsonResponseHandler2,
126
+ parseProviderOptions as parseProviderOptions2,
127
+ postJsonToApi as postJsonToApi2,
128
+ resolve as resolve2
129
+ } from "@ai-sdk/provider-utils";
130
+ import { z as z4 } from "zod";
18
131
 
19
132
  // src/convert-json-schema-to-openapi-schema.ts
20
133
  function convertJSONSchemaToOpenAPISchema(jsonSchema) {
21
- if (isEmptyObjectSchema(jsonSchema)) {
134
+ if (jsonSchema == null || isEmptyObjectSchema(jsonSchema)) {
22
135
  return void 0;
23
136
  }
24
137
  if (typeof jsonSchema === "boolean") {
@@ -117,9 +230,10 @@ function isEmptyObjectSchema(jsonSchema) {
117
230
  import {
118
231
  UnsupportedFunctionalityError
119
232
  } from "@ai-sdk/provider";
120
- import { convertUint8ArrayToBase64 } from "@ai-sdk/provider-utils";
233
+ import {
234
+ convertToBase64
235
+ } from "@ai-sdk/provider-utils";
121
236
  function convertToGoogleGenerativeAIMessages(prompt) {
122
- var _a, _b;
123
237
  const systemInstructionParts = [];
124
238
  const contents = [];
125
239
  let systemMessagesAllowed = true;
@@ -143,33 +257,18 @@ function convertToGoogleGenerativeAIMessages(prompt) {
143
257
  parts.push({ text: part.text });
144
258
  break;
145
259
  }
146
- case "image": {
147
- parts.push(
148
- part.image instanceof URL ? {
149
- fileData: {
150
- mimeType: (_a = part.mimeType) != null ? _a : "image/jpeg",
151
- fileUri: part.image.toString()
152
- }
153
- } : {
154
- inlineData: {
155
- mimeType: (_b = part.mimeType) != null ? _b : "image/jpeg",
156
- data: convertUint8ArrayToBase64(part.image)
157
- }
158
- }
159
- );
160
- break;
161
- }
162
260
  case "file": {
261
+ const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
163
262
  parts.push(
164
263
  part.data instanceof URL ? {
165
264
  fileData: {
166
- mimeType: part.mimeType,
265
+ mimeType: mediaType,
167
266
  fileUri: part.data.toString()
168
267
  }
169
268
  } : {
170
269
  inlineData: {
171
- mimeType: part.mimeType,
172
- data: part.data
270
+ mimeType: mediaType,
271
+ data: convertToBase64(part.data)
173
272
  }
174
273
  }
175
274
  );
@@ -190,7 +289,7 @@ function convertToGoogleGenerativeAIMessages(prompt) {
190
289
  return part.text.length === 0 ? void 0 : { text: part.text };
191
290
  }
192
291
  case "file": {
193
- if (part.mimeType !== "image/png") {
292
+ if (part.mediaType !== "image/png") {
194
293
  throw new UnsupportedFunctionalityError({
195
294
  functionality: "Only PNG images are supported in assistant messages"
196
295
  });
@@ -202,8 +301,8 @@ function convertToGoogleGenerativeAIMessages(prompt) {
202
301
  }
203
302
  return {
204
303
  inlineData: {
205
- mimeType: part.mimeType,
206
- data: part.data
304
+ mimeType: part.mediaType,
305
+ data: convertToBase64(part.data)
207
306
  }
208
307
  };
209
308
  }
@@ -249,28 +348,19 @@ function getModelPath(modelId) {
249
348
  return modelId.includes("/") ? modelId : `models/${modelId}`;
250
349
  }
251
350
 
252
- // src/google-error.ts
253
- import { createJsonErrorResponseHandler } from "@ai-sdk/provider-utils";
254
- import { z } from "zod";
255
- var googleErrorDataSchema = z.object({
256
- error: z.object({
257
- code: z.number().nullable(),
258
- message: z.string(),
259
- status: z.string()
260
- })
261
- });
262
- var googleFailedResponseHandler = createJsonErrorResponseHandler({
263
- errorSchema: googleErrorDataSchema,
264
- errorToMessage: (data) => data.error.message
265
- });
266
-
267
351
  // src/google-prepare-tools.ts
268
352
  import {
269
353
  UnsupportedFunctionalityError as UnsupportedFunctionalityError2
270
354
  } from "@ai-sdk/provider";
271
- function prepareTools(mode, useSearchGrounding, dynamicRetrievalConfig, modelId) {
272
- var _a, _b;
273
- const tools = ((_a = mode.tools) == null ? void 0 : _a.length) ? mode.tools : void 0;
355
+ function prepareTools({
356
+ tools,
357
+ toolChoice,
358
+ useSearchGrounding,
359
+ dynamicRetrievalConfig,
360
+ modelId
361
+ }) {
362
+ var _a;
363
+ tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
274
364
  const toolWarnings = [];
275
365
  const isGemini2 = modelId.includes("gemini-2");
276
366
  const supportsDynamicRetrieval = modelId.includes("gemini-1.5-flash") && !modelId.includes("-8b");
@@ -293,12 +383,11 @@ function prepareTools(mode, useSearchGrounding, dynamicRetrievalConfig, modelId)
293
383
  } else {
294
384
  functionDeclarations.push({
295
385
  name: tool.name,
296
- description: (_b = tool.description) != null ? _b : "",
386
+ description: (_a = tool.description) != null ? _a : "",
297
387
  parameters: convertJSONSchemaToOpenAPISchema(tool.parameters)
298
388
  });
299
389
  }
300
390
  }
301
- const toolChoice = mode.toolChoice;
302
391
  if (toolChoice == null) {
303
392
  return {
304
393
  tools: { functionDeclarations },
@@ -340,7 +429,7 @@ function prepareTools(mode, useSearchGrounding, dynamicRetrievalConfig, modelId)
340
429
  default: {
341
430
  const _exhaustiveCheck = type;
342
431
  throw new UnsupportedFunctionalityError2({
343
- functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
432
+ functionality: `tool choice type: ${_exhaustiveCheck}`
344
433
  });
345
434
  }
346
435
  }
@@ -376,24 +465,21 @@ function mapGoogleGenerativeAIFinishReason({
376
465
  // src/google-generative-ai-language-model.ts
377
466
  var GoogleGenerativeAILanguageModel = class {
378
467
  constructor(modelId, settings, config) {
379
- this.specificationVersion = "v1";
380
- this.defaultObjectGenerationMode = "json";
381
- this.supportsImageUrls = false;
468
+ this.specificationVersion = "v2";
382
469
  this.modelId = modelId;
383
470
  this.settings = settings;
384
471
  this.config = config;
385
472
  }
386
- get supportsStructuredOutputs() {
387
- var _a;
388
- return (_a = this.settings.structuredOutputs) != null ? _a : true;
389
- }
390
473
  get provider() {
391
474
  return this.config.provider;
392
475
  }
476
+ async getSupportedUrls() {
477
+ var _a, _b, _c;
478
+ return (_c = (_b = (_a = this.config).getSupportedUrls) == null ? void 0 : _b.call(_a)) != null ? _c : {};
479
+ }
393
480
  async getArgs({
394
- mode,
395
481
  prompt,
396
- maxTokens,
482
+ maxOutputTokens,
397
483
  temperature,
398
484
  topP,
399
485
  topK,
@@ -402,181 +488,150 @@ var GoogleGenerativeAILanguageModel = class {
402
488
  stopSequences,
403
489
  responseFormat,
404
490
  seed,
405
- providerMetadata
491
+ tools,
492
+ toolChoice,
493
+ providerOptions
406
494
  }) {
407
495
  var _a, _b;
408
- const type = mode.type;
409
496
  const warnings = [];
410
- const googleOptions = parseProviderOptions({
497
+ const googleOptions = parseProviderOptions2({
411
498
  provider: "google",
412
- providerOptions: providerMetadata,
413
- schema: z2.object({
414
- responseModalities: z2.array(z2.enum(["TEXT", "IMAGE"])).nullish()
415
- })
499
+ providerOptions,
500
+ schema: googleGenerativeAIProviderOptionsSchema
416
501
  });
417
- const generationConfig = {
418
- // standardized settings:
419
- maxOutputTokens: maxTokens,
420
- temperature,
421
- topK,
422
- topP,
423
- frequencyPenalty,
424
- presencePenalty,
425
- stopSequences,
426
- seed,
427
- // response format:
428
- responseMimeType: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? "application/json" : void 0,
429
- responseSchema: (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && // Google GenAI does not support all OpenAPI Schema features,
430
- // so this is needed as an escape hatch:
431
- this.supportsStructuredOutputs ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : void 0,
432
- ...this.settings.audioTimestamp && {
433
- audioTimestamp: this.settings.audioTimestamp
434
- },
435
- // provider options:
436
- responseModalities: googleOptions == null ? void 0 : googleOptions.responseModalities
437
- };
438
502
  const { contents, systemInstruction } = convertToGoogleGenerativeAIMessages(prompt);
439
- switch (type) {
440
- case "regular": {
441
- const { tools, toolConfig, toolWarnings } = prepareTools(
442
- mode,
443
- (_a = this.settings.useSearchGrounding) != null ? _a : false,
444
- this.settings.dynamicRetrievalConfig,
445
- this.modelId
446
- );
447
- return {
448
- args: {
449
- generationConfig,
450
- contents,
451
- systemInstruction,
452
- safetySettings: this.settings.safetySettings,
453
- tools,
454
- toolConfig,
455
- cachedContent: this.settings.cachedContent
456
- },
457
- warnings: [...warnings, ...toolWarnings]
458
- };
459
- }
460
- case "object-json": {
461
- return {
462
- args: {
463
- generationConfig: {
464
- ...generationConfig,
465
- responseMimeType: "application/json",
466
- responseSchema: mode.schema != null && // Google GenAI does not support all OpenAPI Schema features,
467
- // so this is needed as an escape hatch:
468
- this.supportsStructuredOutputs ? convertJSONSchemaToOpenAPISchema(mode.schema) : void 0
469
- },
470
- contents,
471
- systemInstruction,
472
- safetySettings: this.settings.safetySettings,
473
- cachedContent: this.settings.cachedContent
474
- },
475
- warnings
476
- };
477
- }
478
- case "object-tool": {
479
- return {
480
- args: {
481
- generationConfig,
482
- contents,
483
- tools: {
484
- functionDeclarations: [
485
- {
486
- name: mode.tool.name,
487
- description: (_b = mode.tool.description) != null ? _b : "",
488
- parameters: convertJSONSchemaToOpenAPISchema(
489
- mode.tool.parameters
490
- )
491
- }
492
- ]
493
- },
494
- toolConfig: { functionCallingConfig: { mode: "ANY" } },
495
- safetySettings: this.settings.safetySettings,
496
- cachedContent: this.settings.cachedContent
503
+ const {
504
+ tools: googleTools,
505
+ toolConfig: googleToolConfig,
506
+ toolWarnings
507
+ } = prepareTools({
508
+ tools,
509
+ toolChoice,
510
+ useSearchGrounding: (_a = this.settings.useSearchGrounding) != null ? _a : false,
511
+ dynamicRetrievalConfig: this.settings.dynamicRetrievalConfig,
512
+ modelId: this.modelId
513
+ });
514
+ return {
515
+ args: {
516
+ generationConfig: {
517
+ // standardized settings:
518
+ maxOutputTokens,
519
+ temperature,
520
+ topK,
521
+ topP,
522
+ frequencyPenalty,
523
+ presencePenalty,
524
+ stopSequences,
525
+ seed,
526
+ // response format:
527
+ responseMimeType: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? "application/json" : void 0,
528
+ responseSchema: (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && // Google GenAI does not support all OpenAPI Schema features,
529
+ // so this is needed as an escape hatch:
530
+ // TODO convert into provider option
531
+ ((_b = this.settings.structuredOutputs) != null ? _b : true) ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : void 0,
532
+ ...this.settings.audioTimestamp && {
533
+ audioTimestamp: this.settings.audioTimestamp
497
534
  },
498
- warnings
499
- };
500
- }
501
- default: {
502
- const _exhaustiveCheck = type;
503
- throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
504
- }
505
- }
506
- }
507
- supportsUrl(url) {
508
- return this.config.isSupportedUrl(url);
535
+ // provider options:
536
+ responseModalities: googleOptions == null ? void 0 : googleOptions.responseModalities,
537
+ thinkingConfig: googleOptions == null ? void 0 : googleOptions.thinkingConfig
538
+ },
539
+ contents,
540
+ systemInstruction,
541
+ safetySettings: this.settings.safetySettings,
542
+ tools: googleTools,
543
+ toolConfig: googleToolConfig,
544
+ cachedContent: this.settings.cachedContent
545
+ },
546
+ warnings: [...warnings, ...toolWarnings]
547
+ };
509
548
  }
510
549
  async doGenerate(options) {
511
- var _a, _b, _c, _d, _e;
550
+ var _a, _b, _c, _d, _e, _f;
512
551
  const { args, warnings } = await this.getArgs(options);
513
552
  const body = JSON.stringify(args);
514
- const mergedHeaders = combineHeaders(
515
- await resolve(this.config.headers),
553
+ const mergedHeaders = combineHeaders2(
554
+ await resolve2(this.config.headers),
516
555
  options.headers
517
556
  );
518
557
  const {
519
558
  responseHeaders,
520
559
  value: response,
521
560
  rawValue: rawResponse
522
- } = await postJsonToApi({
561
+ } = await postJsonToApi2({
523
562
  url: `${this.config.baseURL}/${getModelPath(
524
563
  this.modelId
525
564
  )}:generateContent`,
526
565
  headers: mergedHeaders,
527
566
  body: args,
528
567
  failedResponseHandler: googleFailedResponseHandler,
529
- successfulResponseHandler: createJsonResponseHandler(responseSchema),
568
+ successfulResponseHandler: createJsonResponseHandler2(responseSchema),
530
569
  abortSignal: options.abortSignal,
531
570
  fetch: this.config.fetch
532
571
  });
533
- const { contents: rawPrompt, ...rawSettings } = args;
534
572
  const candidate = response.candidates[0];
535
- const parts = candidate.content == null || typeof candidate.content !== "object" || !("parts" in candidate.content) ? [] : candidate.content.parts;
536
- const toolCalls = getToolCallsFromParts({
537
- parts,
573
+ const content = [];
574
+ const parts = candidate.content == null || typeof candidate.content !== "object" || !("parts" in candidate.content) ? [] : (_a = candidate.content.parts) != null ? _a : [];
575
+ for (const part of parts) {
576
+ if ("text" in part && part.text.length > 0) {
577
+ content.push({ type: "text", text: part.text });
578
+ } else if ("functionCall" in part) {
579
+ content.push({
580
+ type: "tool-call",
581
+ toolCallType: "function",
582
+ toolCallId: this.config.generateId(),
583
+ toolName: part.functionCall.name,
584
+ args: JSON.stringify(part.functionCall.args)
585
+ });
586
+ } else if ("inlineData" in part) {
587
+ content.push({
588
+ type: "file",
589
+ data: part.inlineData.data,
590
+ mediaType: part.inlineData.mimeType
591
+ });
592
+ }
593
+ }
594
+ const sources = (_b = extractSources({
595
+ groundingMetadata: candidate.groundingMetadata,
538
596
  generateId: this.config.generateId
539
- });
597
+ })) != null ? _b : [];
598
+ for (const source of sources) {
599
+ content.push(source);
600
+ }
540
601
  const usageMetadata = response.usageMetadata;
541
602
  return {
542
- text: getTextFromParts(parts),
543
- files: (_a = getInlineDataParts(parts)) == null ? void 0 : _a.map((part) => ({
544
- data: part.inlineData.data,
545
- mimeType: part.inlineData.mimeType
546
- })),
547
- toolCalls,
603
+ content,
548
604
  finishReason: mapGoogleGenerativeAIFinishReason({
549
605
  finishReason: candidate.finishReason,
550
- hasToolCalls: toolCalls != null && toolCalls.length > 0
606
+ hasToolCalls: content.some((part) => part.type === "tool-call")
551
607
  }),
552
608
  usage: {
553
- promptTokens: (_b = usageMetadata == null ? void 0 : usageMetadata.promptTokenCount) != null ? _b : NaN,
554
- completionTokens: (_c = usageMetadata == null ? void 0 : usageMetadata.candidatesTokenCount) != null ? _c : NaN
609
+ inputTokens: (_c = usageMetadata == null ? void 0 : usageMetadata.promptTokenCount) != null ? _c : void 0,
610
+ outputTokens: (_d = usageMetadata == null ? void 0 : usageMetadata.candidatesTokenCount) != null ? _d : void 0
555
611
  },
556
- rawCall: { rawPrompt, rawSettings },
557
- rawResponse: { headers: responseHeaders, body: rawResponse },
558
612
  warnings,
559
613
  providerMetadata: {
560
614
  google: {
561
- groundingMetadata: (_d = candidate.groundingMetadata) != null ? _d : null,
562
- safetyRatings: (_e = candidate.safetyRatings) != null ? _e : null
615
+ groundingMetadata: (_e = candidate.groundingMetadata) != null ? _e : null,
616
+ safetyRatings: (_f = candidate.safetyRatings) != null ? _f : null
563
617
  }
564
618
  },
565
- sources: extractSources({
566
- groundingMetadata: candidate.groundingMetadata,
567
- generateId: this.config.generateId
568
- }),
569
- request: { body }
619
+ request: { body },
620
+ response: {
621
+ // TODO timestamp, model id, id
622
+ headers: responseHeaders,
623
+ body: rawResponse
624
+ }
570
625
  };
571
626
  }
572
627
  async doStream(options) {
573
628
  const { args, warnings } = await this.getArgs(options);
574
629
  const body = JSON.stringify(args);
575
- const headers = combineHeaders(
576
- await resolve(this.config.headers),
630
+ const headers = combineHeaders2(
631
+ await resolve2(this.config.headers),
577
632
  options.headers
578
633
  );
579
- const { responseHeaders, value: response } = await postJsonToApi({
634
+ const { responseHeaders, value: response } = await postJsonToApi2({
580
635
  url: `${this.config.baseURL}/${getModelPath(
581
636
  this.modelId
582
637
  )}:streamGenerateContent?alt=sse`,
@@ -587,11 +642,10 @@ var GoogleGenerativeAILanguageModel = class {
587
642
  abortSignal: options.abortSignal,
588
643
  fetch: this.config.fetch
589
644
  });
590
- const { contents: rawPrompt, ...rawSettings } = args;
591
645
  let finishReason = "unknown";
592
- let usage = {
593
- promptTokens: Number.NaN,
594
- completionTokens: Number.NaN
646
+ const usage = {
647
+ inputTokens: void 0,
648
+ outputTokens: void 0
595
649
  };
596
650
  let providerMetadata = void 0;
597
651
  const generateId2 = this.config.generateId;
@@ -599,6 +653,9 @@ var GoogleGenerativeAILanguageModel = class {
599
653
  return {
600
654
  stream: response.pipeThrough(
601
655
  new TransformStream({
656
+ start(controller) {
657
+ controller.enqueue({ type: "stream-start", warnings });
658
+ },
602
659
  transform(chunk, controller) {
603
660
  var _a, _b, _c, _d, _e, _f;
604
661
  if (!chunk.success) {
@@ -608,10 +665,8 @@ var GoogleGenerativeAILanguageModel = class {
608
665
  const value = chunk.value;
609
666
  const usageMetadata = value.usageMetadata;
610
667
  if (usageMetadata != null) {
611
- usage = {
612
- promptTokens: (_a = usageMetadata.promptTokenCount) != null ? _a : NaN,
613
- completionTokens: (_b = usageMetadata.candidatesTokenCount) != null ? _b : NaN
614
- };
668
+ usage.inputTokens = (_a = usageMetadata.promptTokenCount) != null ? _a : void 0;
669
+ usage.outputTokens = (_b = usageMetadata.candidatesTokenCount) != null ? _b : void 0;
615
670
  }
616
671
  const candidate = (_c = value.candidates) == null ? void 0 : _c[0];
617
672
  if (candidate == null) {
@@ -621,17 +676,14 @@ var GoogleGenerativeAILanguageModel = class {
621
676
  if (content != null) {
622
677
  const deltaText = getTextFromParts(content.parts);
623
678
  if (deltaText != null) {
624
- controller.enqueue({
625
- type: "text-delta",
626
- textDelta: deltaText
627
- });
679
+ controller.enqueue(deltaText);
628
680
  }
629
681
  const inlineDataParts = getInlineDataParts(content.parts);
630
682
  if (inlineDataParts != null) {
631
683
  for (const part of inlineDataParts) {
632
684
  controller.enqueue({
633
685
  type: "file",
634
- mimeType: part.inlineData.mimeType,
686
+ mediaType: part.inlineData.mimeType,
635
687
  data: part.inlineData.data
636
688
  });
637
689
  }
@@ -670,7 +722,7 @@ var GoogleGenerativeAILanguageModel = class {
670
722
  generateId: generateId2
671
723
  })) != null ? _d : [];
672
724
  for (const source of sources) {
673
- controller.enqueue({ type: "source", source });
725
+ controller.enqueue(source);
674
726
  }
675
727
  providerMetadata = {
676
728
  google: {
@@ -690,9 +742,7 @@ var GoogleGenerativeAILanguageModel = class {
690
742
  }
691
743
  })
692
744
  ),
693
- rawCall: { rawPrompt, rawSettings },
694
- rawResponse: { headers: responseHeaders },
695
- warnings,
745
+ response: { headers: responseHeaders },
696
746
  request: { body }
697
747
  };
698
748
  }
@@ -705,6 +755,7 @@ function getToolCallsFromParts({
705
755
  (part) => "functionCall" in part
706
756
  );
707
757
  return functionCallParts == null || functionCallParts.length === 0 ? void 0 : functionCallParts.map((part) => ({
758
+ type: "tool-call",
708
759
  toolCallType: "function",
709
760
  toolCallId: generateId2(),
710
761
  toolName: part.functionCall.name,
@@ -713,7 +764,10 @@ function getToolCallsFromParts({
713
764
  }
714
765
  function getTextFromParts(parts) {
715
766
  const textParts = parts == null ? void 0 : parts.filter((part) => "text" in part);
716
- return textParts == null || textParts.length === 0 ? void 0 : textParts.map((part) => part.text).join("");
767
+ return textParts == null || textParts.length === 0 ? void 0 : {
768
+ type: "text",
769
+ text: textParts.map((part) => part.text).join("")
770
+ };
717
771
  }
718
772
  function getInlineDataParts(parts) {
719
773
  return parts == null ? void 0 : parts.filter(
@@ -728,180 +782,110 @@ function extractSources({
728
782
  return (_a = groundingMetadata == null ? void 0 : groundingMetadata.groundingChunks) == null ? void 0 : _a.filter(
729
783
  (chunk) => chunk.web != null
730
784
  ).map((chunk) => ({
785
+ type: "source",
731
786
  sourceType: "url",
732
787
  id: generateId2(),
733
788
  url: chunk.web.uri,
734
789
  title: chunk.web.title
735
790
  }));
736
791
  }
737
- var contentSchema = z2.object({
738
- role: z2.string(),
739
- parts: z2.array(
740
- z2.union([
741
- z2.object({
742
- text: z2.string()
792
+ var contentSchema = z4.object({
793
+ role: z4.string(),
794
+ parts: z4.array(
795
+ z4.union([
796
+ z4.object({
797
+ text: z4.string()
743
798
  }),
744
- z2.object({
745
- functionCall: z2.object({
746
- name: z2.string(),
747
- args: z2.unknown()
799
+ z4.object({
800
+ functionCall: z4.object({
801
+ name: z4.string(),
802
+ args: z4.unknown()
748
803
  })
749
804
  }),
750
- z2.object({
751
- inlineData: z2.object({
752
- mimeType: z2.string(),
753
- data: z2.string()
805
+ z4.object({
806
+ inlineData: z4.object({
807
+ mimeType: z4.string(),
808
+ data: z4.string()
754
809
  })
755
810
  })
756
811
  ])
757
812
  ).nullish()
758
813
  });
759
- var groundingChunkSchema = z2.object({
760
- web: z2.object({ uri: z2.string(), title: z2.string() }).nullish(),
761
- retrievedContext: z2.object({ uri: z2.string(), title: z2.string() }).nullish()
814
+ var groundingChunkSchema = z4.object({
815
+ web: z4.object({ uri: z4.string(), title: z4.string() }).nullish(),
816
+ retrievedContext: z4.object({ uri: z4.string(), title: z4.string() }).nullish()
762
817
  });
763
- var groundingMetadataSchema = z2.object({
764
- webSearchQueries: z2.array(z2.string()).nullish(),
765
- retrievalQueries: z2.array(z2.string()).nullish(),
766
- searchEntryPoint: z2.object({ renderedContent: z2.string() }).nullish(),
767
- groundingChunks: z2.array(groundingChunkSchema).nullish(),
768
- groundingSupports: z2.array(
769
- z2.object({
770
- segment: z2.object({
771
- startIndex: z2.number().nullish(),
772
- endIndex: z2.number().nullish(),
773
- text: z2.string().nullish()
818
+ var groundingMetadataSchema = z4.object({
819
+ webSearchQueries: z4.array(z4.string()).nullish(),
820
+ retrievalQueries: z4.array(z4.string()).nullish(),
821
+ searchEntryPoint: z4.object({ renderedContent: z4.string() }).nullish(),
822
+ groundingChunks: z4.array(groundingChunkSchema).nullish(),
823
+ groundingSupports: z4.array(
824
+ z4.object({
825
+ segment: z4.object({
826
+ startIndex: z4.number().nullish(),
827
+ endIndex: z4.number().nullish(),
828
+ text: z4.string().nullish()
774
829
  }),
775
- segment_text: z2.string().nullish(),
776
- groundingChunkIndices: z2.array(z2.number()).nullish(),
777
- supportChunkIndices: z2.array(z2.number()).nullish(),
778
- confidenceScores: z2.array(z2.number()).nullish(),
779
- confidenceScore: z2.array(z2.number()).nullish()
830
+ segment_text: z4.string().nullish(),
831
+ groundingChunkIndices: z4.array(z4.number()).nullish(),
832
+ supportChunkIndices: z4.array(z4.number()).nullish(),
833
+ confidenceScores: z4.array(z4.number()).nullish(),
834
+ confidenceScore: z4.array(z4.number()).nullish()
780
835
  })
781
836
  ).nullish(),
782
- retrievalMetadata: z2.union([
783
- z2.object({
784
- webDynamicRetrievalScore: z2.number()
837
+ retrievalMetadata: z4.union([
838
+ z4.object({
839
+ webDynamicRetrievalScore: z4.number()
785
840
  }),
786
- z2.object({})
841
+ z4.object({})
787
842
  ]).nullish()
788
843
  });
789
- var safetyRatingSchema = z2.object({
790
- category: z2.string(),
791
- probability: z2.string(),
792
- probabilityScore: z2.number().nullish(),
793
- severity: z2.string().nullish(),
794
- severityScore: z2.number().nullish(),
795
- blocked: z2.boolean().nullish()
844
+ var safetyRatingSchema = z4.object({
845
+ category: z4.string(),
846
+ probability: z4.string(),
847
+ probabilityScore: z4.number().nullish(),
848
+ severity: z4.string().nullish(),
849
+ severityScore: z4.number().nullish(),
850
+ blocked: z4.boolean().nullish()
796
851
  });
797
- var responseSchema = z2.object({
798
- candidates: z2.array(
799
- z2.object({
800
- content: contentSchema.nullish().or(z2.object({}).strict()),
801
- finishReason: z2.string().nullish(),
802
- safetyRatings: z2.array(safetyRatingSchema).nullish(),
852
+ var responseSchema = z4.object({
853
+ candidates: z4.array(
854
+ z4.object({
855
+ content: contentSchema.nullish().or(z4.object({}).strict()),
856
+ finishReason: z4.string().nullish(),
857
+ safetyRatings: z4.array(safetyRatingSchema).nullish(),
803
858
  groundingMetadata: groundingMetadataSchema.nullish()
804
859
  })
805
860
  ),
806
- usageMetadata: z2.object({
807
- promptTokenCount: z2.number().nullish(),
808
- candidatesTokenCount: z2.number().nullish(),
809
- totalTokenCount: z2.number().nullish()
861
+ usageMetadata: z4.object({
862
+ promptTokenCount: z4.number().nullish(),
863
+ candidatesTokenCount: z4.number().nullish(),
864
+ totalTokenCount: z4.number().nullish()
810
865
  }).nullish()
811
866
  });
812
- var chunkSchema = z2.object({
813
- candidates: z2.array(
814
- z2.object({
867
+ var chunkSchema = z4.object({
868
+ candidates: z4.array(
869
+ z4.object({
815
870
  content: contentSchema.nullish(),
816
- finishReason: z2.string().nullish(),
817
- safetyRatings: z2.array(safetyRatingSchema).nullish(),
871
+ finishReason: z4.string().nullish(),
872
+ safetyRatings: z4.array(safetyRatingSchema).nullish(),
818
873
  groundingMetadata: groundingMetadataSchema.nullish()
819
874
  })
820
875
  ).nullish(),
821
- usageMetadata: z2.object({
822
- promptTokenCount: z2.number().nullish(),
823
- candidatesTokenCount: z2.number().nullish(),
824
- totalTokenCount: z2.number().nullish()
876
+ usageMetadata: z4.object({
877
+ promptTokenCount: z4.number().nullish(),
878
+ candidatesTokenCount: z4.number().nullish(),
879
+ totalTokenCount: z4.number().nullish()
825
880
  }).nullish()
826
881
  });
827
-
828
- // src/google-generative-ai-embedding-model.ts
829
- import {
830
- TooManyEmbeddingValuesForCallError
831
- } from "@ai-sdk/provider";
832
- import {
833
- combineHeaders as combineHeaders2,
834
- createJsonResponseHandler as createJsonResponseHandler2,
835
- postJsonToApi as postJsonToApi2,
836
- resolve as resolve2
837
- } from "@ai-sdk/provider-utils";
838
- import { z as z3 } from "zod";
839
- var GoogleGenerativeAIEmbeddingModel = class {
840
- constructor(modelId, settings, config) {
841
- this.specificationVersion = "v1";
842
- this.modelId = modelId;
843
- this.settings = settings;
844
- this.config = config;
845
- }
846
- get provider() {
847
- return this.config.provider;
848
- }
849
- get maxEmbeddingsPerCall() {
850
- return 2048;
851
- }
852
- get supportsParallelCalls() {
853
- return true;
854
- }
855
- async doEmbed({
856
- values,
857
- headers,
858
- abortSignal
859
- }) {
860
- if (values.length > this.maxEmbeddingsPerCall) {
861
- throw new TooManyEmbeddingValuesForCallError({
862
- provider: this.provider,
863
- modelId: this.modelId,
864
- maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
865
- values
866
- });
867
- }
868
- const mergedHeaders = combineHeaders2(
869
- await resolve2(this.config.headers),
870
- headers
871
- );
872
- const { responseHeaders, value: response } = await postJsonToApi2({
873
- url: `${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,
874
- headers: mergedHeaders,
875
- body: {
876
- requests: values.map((value) => ({
877
- model: `models/${this.modelId}`,
878
- content: { role: "user", parts: [{ text: value }] },
879
- outputDimensionality: this.settings.outputDimensionality
880
- }))
881
- },
882
- failedResponseHandler: googleFailedResponseHandler,
883
- successfulResponseHandler: createJsonResponseHandler2(
884
- googleGenerativeAITextEmbeddingResponseSchema
885
- ),
886
- abortSignal,
887
- fetch: this.config.fetch
888
- });
889
- return {
890
- embeddings: response.embeddings.map((item) => item.values),
891
- usage: void 0,
892
- rawResponse: { headers: responseHeaders }
893
- };
894
- }
895
- };
896
- var googleGenerativeAITextEmbeddingResponseSchema = z3.object({
897
- embeddings: z3.array(z3.object({ values: z3.array(z3.number()) }))
882
+ var googleGenerativeAIProviderOptionsSchema = z4.object({
883
+ responseModalities: z4.array(z4.enum(["TEXT", "IMAGE"])).nullish(),
884
+ thinkingConfig: z4.object({
885
+ thinkingBudget: z4.number().nullish()
886
+ }).nullish()
898
887
  });
899
888
 
900
- // src/google-supported-file-url.ts
901
- function isSupportedFileUrl(url) {
902
- return url.toString().startsWith("https://generativelanguage.googleapis.com/v1beta/files/");
903
- }
904
-
905
889
  // src/google-provider.ts
906
890
  function createGoogleGenerativeAI(options = {}) {
907
891
  var _a;
@@ -921,11 +905,16 @@ function createGoogleGenerativeAI(options = {}) {
921
905
  baseURL,
922
906
  headers: getHeaders,
923
907
  generateId: (_a2 = options.generateId) != null ? _a2 : generateId,
924
- isSupportedUrl: isSupportedFileUrl,
908
+ getSupportedUrls: async () => ({
909
+ "*": [
910
+ // HTTP URLs:
911
+ /^https?:\/\/.*$/
912
+ ]
913
+ }),
925
914
  fetch: options.fetch
926
915
  });
927
916
  };
928
- const createEmbeddingModel = (modelId, settings = {}) => new GoogleGenerativeAIEmbeddingModel(modelId, settings, {
917
+ const createEmbeddingModel = (modelId) => new GoogleGenerativeAIEmbeddingModel(modelId, {
929
918
  provider: "google.generative-ai",
930
919
  baseURL,
931
920
  headers: getHeaders,
@@ -945,6 +934,9 @@ function createGoogleGenerativeAI(options = {}) {
945
934
  provider.embedding = createEmbeddingModel;
946
935
  provider.textEmbedding = createEmbeddingModel;
947
936
  provider.textEmbeddingModel = createEmbeddingModel;
937
+ provider.imageModel = (modelId) => {
938
+ throw new NoSuchModelError({ modelId, modelType: "imageModel" });
939
+ };
948
940
  return provider;
949
941
  }
950
942
  var google = createGoogleGenerativeAI();