@ai-sdk/google 2.0.0-beta.1 → 2.0.0-beta.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.js CHANGED
@@ -26,22 +26,21 @@ __export(src_exports, {
26
26
  module.exports = __toCommonJS(src_exports);
27
27
 
28
28
  // src/google-provider.ts
29
- var import_provider4 = require("@ai-sdk/provider");
30
- var import_provider_utils5 = require("@ai-sdk/provider-utils");
29
+ var import_provider_utils8 = require("@ai-sdk/provider-utils");
31
30
 
32
31
  // src/google-generative-ai-embedding-model.ts
33
32
  var import_provider = require("@ai-sdk/provider");
34
33
  var import_provider_utils2 = require("@ai-sdk/provider-utils");
35
- var import_zod3 = require("zod");
34
+ var import_v43 = require("zod/v4");
36
35
 
37
36
  // src/google-error.ts
38
37
  var import_provider_utils = require("@ai-sdk/provider-utils");
39
- var import_zod = require("zod");
40
- var googleErrorDataSchema = import_zod.z.object({
41
- error: import_zod.z.object({
42
- code: import_zod.z.number().nullable(),
43
- message: import_zod.z.string(),
44
- status: import_zod.z.string()
38
+ var import_v4 = require("zod/v4");
39
+ var googleErrorDataSchema = import_v4.z.object({
40
+ error: import_v4.z.object({
41
+ code: import_v4.z.number().nullable(),
42
+ message: import_v4.z.string(),
43
+ status: import_v4.z.string()
45
44
  })
46
45
  });
47
46
  var googleFailedResponseHandler = (0, import_provider_utils.createJsonErrorResponseHandler)({
@@ -50,13 +49,13 @@ var googleFailedResponseHandler = (0, import_provider_utils.createJsonErrorRespo
50
49
  });
51
50
 
52
51
  // src/google-generative-ai-embedding-options.ts
53
- var import_zod2 = require("zod");
54
- var googleGenerativeAIEmbeddingProviderOptions = import_zod2.z.object({
52
+ var import_v42 = require("zod/v4");
53
+ var googleGenerativeAIEmbeddingProviderOptions = import_v42.z.object({
55
54
  /**
56
55
  * Optional. Optional reduced dimension for the output embedding.
57
56
  * If set, excessive values in the output embedding are truncated from the end.
58
57
  */
59
- outputDimensionality: import_zod2.z.number().optional(),
58
+ outputDimensionality: import_v42.z.number().optional(),
60
59
  /**
61
60
  * Optional. Specifies the task type for generating embeddings.
62
61
  * Supported task types:
@@ -69,7 +68,7 @@ var googleGenerativeAIEmbeddingProviderOptions = import_zod2.z.object({
69
68
  * - FACT_VERIFICATION: Optimized for verifying factual information.
70
69
  * - CODE_RETRIEVAL_QUERY: Optimized for retrieving code blocks based on natural language queries.
71
70
  */
72
- taskType: import_zod2.z.enum([
71
+ taskType: import_v42.z.enum([
73
72
  "SEMANTIC_SIMILARITY",
74
73
  "CLASSIFICATION",
75
74
  "CLUSTERING",
@@ -145,13 +144,13 @@ var GoogleGenerativeAIEmbeddingModel = class {
145
144
  };
146
145
  }
147
146
  };
148
- var googleGenerativeAITextEmbeddingResponseSchema = import_zod3.z.object({
149
- embeddings: import_zod3.z.array(import_zod3.z.object({ values: import_zod3.z.array(import_zod3.z.number()) }))
147
+ var googleGenerativeAITextEmbeddingResponseSchema = import_v43.z.object({
148
+ embeddings: import_v43.z.array(import_v43.z.object({ values: import_v43.z.array(import_v43.z.number()) }))
150
149
  });
151
150
 
152
151
  // src/google-generative-ai-language-model.ts
153
- var import_provider_utils4 = require("@ai-sdk/provider-utils");
154
- var import_zod5 = require("zod");
152
+ var import_provider_utils6 = require("@ai-sdk/provider-utils");
153
+ var import_v47 = require("zod/v4");
155
154
 
156
155
  // src/convert-json-schema-to-openapi-schema.ts
157
156
  function convertJSONSchemaToOpenAPISchema(jsonSchema) {
@@ -247,16 +246,18 @@ function convertJSONSchemaToOpenAPISchema(jsonSchema) {
247
246
  return result;
248
247
  }
249
248
  function isEmptyObjectSchema(jsonSchema) {
250
- return jsonSchema != null && typeof jsonSchema === "object" && jsonSchema.type === "object" && (jsonSchema.properties == null || Object.keys(jsonSchema.properties).length === 0);
249
+ return jsonSchema != null && typeof jsonSchema === "object" && jsonSchema.type === "object" && (jsonSchema.properties == null || Object.keys(jsonSchema.properties).length === 0) && !jsonSchema.additionalProperties;
251
250
  }
252
251
 
253
252
  // src/convert-to-google-generative-ai-messages.ts
254
253
  var import_provider2 = require("@ai-sdk/provider");
255
254
  var import_provider_utils3 = require("@ai-sdk/provider-utils");
256
- function convertToGoogleGenerativeAIMessages(prompt) {
255
+ function convertToGoogleGenerativeAIMessages(prompt, options) {
256
+ var _a;
257
257
  const systemInstructionParts = [];
258
258
  const contents = [];
259
259
  let systemMessagesAllowed = true;
260
+ const isGemmaModel = (_a = options == null ? void 0 : options.isGemmaModel) != null ? _a : false;
260
261
  for (const { role, content } of prompt) {
261
262
  switch (role) {
262
263
  case "system": {
@@ -357,8 +358,12 @@ function convertToGoogleGenerativeAIMessages(prompt) {
357
358
  }
358
359
  }
359
360
  }
361
+ if (isGemmaModel && systemInstructionParts.length > 0 && contents.length > 0 && contents[0].role === "user") {
362
+ const systemText = systemInstructionParts.map((part) => part.text).join("\n\n");
363
+ contents[0].parts.unshift({ text: systemText + "\n\n" });
364
+ }
360
365
  return {
361
- systemInstruction: systemInstructionParts.length > 0 ? { parts: systemInstructionParts } : void 0,
366
+ systemInstruction: systemInstructionParts.length > 0 && !isGemmaModel ? { parts: systemInstructionParts } : void 0,
362
367
  contents
363
368
  };
364
369
  }
@@ -369,30 +374,19 @@ function getModelPath(modelId) {
369
374
  }
370
375
 
371
376
  // src/google-generative-ai-options.ts
372
- var import_zod4 = require("zod");
373
- var dynamicRetrievalConfig = import_zod4.z.object({
374
- /**
375
- * The mode of the predictor to be used in dynamic retrieval.
376
- */
377
- mode: import_zod4.z.enum(["MODE_UNSPECIFIED", "MODE_DYNAMIC"]).optional(),
378
- /**
379
- * The threshold to be used in dynamic retrieval. If not set, a system default
380
- * value is used.
381
- */
382
- dynamicThreshold: import_zod4.z.number().optional()
383
- });
384
- var googleGenerativeAIProviderOptions = import_zod4.z.object({
385
- responseModalities: import_zod4.z.array(import_zod4.z.enum(["TEXT", "IMAGE"])).optional(),
386
- thinkingConfig: import_zod4.z.object({
387
- thinkingBudget: import_zod4.z.number().optional(),
388
- includeThoughts: import_zod4.z.boolean().optional()
377
+ var import_v44 = require("zod/v4");
378
+ var googleGenerativeAIProviderOptions = import_v44.z.object({
379
+ responseModalities: import_v44.z.array(import_v44.z.enum(["TEXT", "IMAGE"])).optional(),
380
+ thinkingConfig: import_v44.z.object({
381
+ thinkingBudget: import_v44.z.number().optional(),
382
+ includeThoughts: import_v44.z.boolean().optional()
389
383
  }).optional(),
390
384
  /**
391
385
  Optional.
392
386
  The name of the cached content used as context to serve the prediction.
393
387
  Format: cachedContents/{cachedContent}
394
388
  */
395
- cachedContent: import_zod4.z.string().optional(),
389
+ cachedContent: import_v44.z.string().optional(),
396
390
  /**
397
391
  * Optional. Enable structured output. Default is true.
398
392
  *
@@ -401,13 +395,13 @@ var googleGenerativeAIProviderOptions = import_zod4.z.object({
401
395
  * Google Generative AI uses. You can use this to disable
402
396
  * structured outputs if you need to.
403
397
  */
404
- structuredOutputs: import_zod4.z.boolean().optional(),
398
+ structuredOutputs: import_v44.z.boolean().optional(),
405
399
  /**
406
400
  Optional. A list of unique safety settings for blocking unsafe content.
407
401
  */
408
- safetySettings: import_zod4.z.array(
409
- import_zod4.z.object({
410
- category: import_zod4.z.enum([
402
+ safetySettings: import_v44.z.array(
403
+ import_v44.z.object({
404
+ category: import_v44.z.enum([
411
405
  "HARM_CATEGORY_UNSPECIFIED",
412
406
  "HARM_CATEGORY_HATE_SPEECH",
413
407
  "HARM_CATEGORY_DANGEROUS_CONTENT",
@@ -415,7 +409,7 @@ var googleGenerativeAIProviderOptions = import_zod4.z.object({
415
409
  "HARM_CATEGORY_SEXUALLY_EXPLICIT",
416
410
  "HARM_CATEGORY_CIVIC_INTEGRITY"
417
411
  ]),
418
- threshold: import_zod4.z.enum([
412
+ threshold: import_v44.z.enum([
419
413
  "HARM_BLOCK_THRESHOLD_UNSPECIFIED",
420
414
  "BLOCK_LOW_AND_ABOVE",
421
415
  "BLOCK_MEDIUM_AND_ABOVE",
@@ -425,7 +419,7 @@ var googleGenerativeAIProviderOptions = import_zod4.z.object({
425
419
  ])
426
420
  })
427
421
  ).optional(),
428
- threshold: import_zod4.z.enum([
422
+ threshold: import_v44.z.enum([
429
423
  "HARM_BLOCK_THRESHOLD_UNSPECIFIED",
430
424
  "BLOCK_LOW_AND_ABOVE",
431
425
  "BLOCK_MEDIUM_AND_ABOVE",
@@ -438,21 +432,7 @@ var googleGenerativeAIProviderOptions = import_zod4.z.object({
438
432
  *
439
433
  * https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/audio-understanding
440
434
  */
441
- audioTimestamp: import_zod4.z.boolean().optional(),
442
- /**
443
- Optional. When enabled, the model will use Google search to ground the response.
444
-
445
- @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/overview
446
- */
447
- useSearchGrounding: import_zod4.z.boolean().optional(),
448
- /**
449
- Optional. Specifies the dynamic retrieval configuration.
450
-
451
- @note Dynamic retrieval is only compatible with Gemini 1.5 Flash.
452
-
453
- @see https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/ground-with-google-search#dynamic-retrieval
454
- */
455
- dynamicRetrievalConfig: dynamicRetrievalConfig.optional()
435
+ audioTimestamp: import_v44.z.boolean().optional()
456
436
  });
457
437
 
458
438
  // src/google-prepare-tools.ts
@@ -460,8 +440,6 @@ var import_provider3 = require("@ai-sdk/provider");
460
440
  function prepareTools({
461
441
  tools,
462
442
  toolChoice,
463
- useSearchGrounding,
464
- dynamicRetrievalConfig: dynamicRetrievalConfig2,
465
443
  modelId
466
444
  }) {
467
445
  var _a;
@@ -469,28 +447,76 @@ function prepareTools({
469
447
  const toolWarnings = [];
470
448
  const isGemini2 = modelId.includes("gemini-2");
471
449
  const supportsDynamicRetrieval = modelId.includes("gemini-1.5-flash") && !modelId.includes("-8b");
472
- if (useSearchGrounding) {
450
+ if (tools == null) {
451
+ return { tools: void 0, toolConfig: void 0, toolWarnings };
452
+ }
453
+ const hasFunctionTools = tools.some((tool) => tool.type === "function");
454
+ const hasProviderDefinedTools = tools.some(
455
+ (tool) => tool.type === "provider-defined"
456
+ );
457
+ if (hasFunctionTools && hasProviderDefinedTools) {
458
+ toolWarnings.push({
459
+ type: "unsupported-tool",
460
+ tool: tools.find((tool) => tool.type === "function"),
461
+ details: "Cannot mix function tools with provider-defined tools in the same request. Please use either function tools or provider-defined tools, but not both."
462
+ });
463
+ }
464
+ if (hasProviderDefinedTools) {
465
+ const googleTools2 = {};
466
+ const providerDefinedTools = tools.filter(
467
+ (tool) => tool.type === "provider-defined"
468
+ );
469
+ providerDefinedTools.forEach((tool) => {
470
+ switch (tool.id) {
471
+ case "google.google_search":
472
+ if (isGemini2) {
473
+ googleTools2.googleSearch = {};
474
+ } else if (supportsDynamicRetrieval) {
475
+ googleTools2.googleSearchRetrieval = {
476
+ dynamicRetrievalConfig: {
477
+ mode: tool.args.mode,
478
+ dynamicThreshold: tool.args.dynamicThreshold
479
+ }
480
+ };
481
+ } else {
482
+ googleTools2.googleSearchRetrieval = {};
483
+ }
484
+ break;
485
+ case "google.url_context":
486
+ if (isGemini2) {
487
+ googleTools2.urlContext = {};
488
+ } else {
489
+ toolWarnings.push({
490
+ type: "unsupported-tool",
491
+ tool,
492
+ details: "The URL context tool is not supported with other Gemini models than Gemini 2."
493
+ });
494
+ }
495
+ break;
496
+ default:
497
+ toolWarnings.push({ type: "unsupported-tool", tool });
498
+ break;
499
+ }
500
+ });
473
501
  return {
474
- tools: isGemini2 ? { googleSearch: {} } : {
475
- googleSearchRetrieval: !supportsDynamicRetrieval || !dynamicRetrievalConfig2 ? {} : { dynamicRetrievalConfig: dynamicRetrievalConfig2 }
476
- },
502
+ tools: Object.keys(googleTools2).length > 0 ? googleTools2 : void 0,
477
503
  toolConfig: void 0,
478
504
  toolWarnings
479
505
  };
480
506
  }
481
- if (tools == null) {
482
- return { tools: void 0, toolConfig: void 0, toolWarnings };
483
- }
484
507
  const functionDeclarations = [];
485
508
  for (const tool of tools) {
486
- if (tool.type === "provider-defined") {
487
- toolWarnings.push({ type: "unsupported-tool", tool });
488
- } else {
489
- functionDeclarations.push({
490
- name: tool.name,
491
- description: (_a = tool.description) != null ? _a : "",
492
- parameters: convertJSONSchemaToOpenAPISchema(tool.inputSchema)
493
- });
509
+ switch (tool.type) {
510
+ case "function":
511
+ functionDeclarations.push({
512
+ name: tool.name,
513
+ description: (_a = tool.description) != null ? _a : "",
514
+ parameters: convertJSONSchemaToOpenAPISchema(tool.inputSchema)
515
+ });
516
+ break;
517
+ default:
518
+ toolWarnings.push({ type: "unsupported-tool", tool });
519
+ break;
494
520
  }
495
521
  }
496
522
  if (toolChoice == null) {
@@ -567,12 +593,72 @@ function mapGoogleGenerativeAIFinishReason({
567
593
  }
568
594
  }
569
595
 
596
+ // src/tool/google-search.ts
597
+ var import_provider_utils4 = require("@ai-sdk/provider-utils");
598
+ var import_v45 = require("zod/v4");
599
+ var groundingChunkSchema = import_v45.z.object({
600
+ web: import_v45.z.object({ uri: import_v45.z.string(), title: import_v45.z.string() }).nullish(),
601
+ retrievedContext: import_v45.z.object({ uri: import_v45.z.string(), title: import_v45.z.string() }).nullish()
602
+ });
603
+ var groundingMetadataSchema = import_v45.z.object({
604
+ webSearchQueries: import_v45.z.array(import_v45.z.string()).nullish(),
605
+ retrievalQueries: import_v45.z.array(import_v45.z.string()).nullish(),
606
+ searchEntryPoint: import_v45.z.object({ renderedContent: import_v45.z.string() }).nullish(),
607
+ groundingChunks: import_v45.z.array(groundingChunkSchema).nullish(),
608
+ groundingSupports: import_v45.z.array(
609
+ import_v45.z.object({
610
+ segment: import_v45.z.object({
611
+ startIndex: import_v45.z.number().nullish(),
612
+ endIndex: import_v45.z.number().nullish(),
613
+ text: import_v45.z.string().nullish()
614
+ }),
615
+ segment_text: import_v45.z.string().nullish(),
616
+ groundingChunkIndices: import_v45.z.array(import_v45.z.number()).nullish(),
617
+ supportChunkIndices: import_v45.z.array(import_v45.z.number()).nullish(),
618
+ confidenceScores: import_v45.z.array(import_v45.z.number()).nullish(),
619
+ confidenceScore: import_v45.z.array(import_v45.z.number()).nullish()
620
+ })
621
+ ).nullish(),
622
+ retrievalMetadata: import_v45.z.union([
623
+ import_v45.z.object({
624
+ webDynamicRetrievalScore: import_v45.z.number()
625
+ }),
626
+ import_v45.z.object({})
627
+ ]).nullish()
628
+ });
629
+ var googleSearch = (0, import_provider_utils4.createProviderDefinedToolFactory)({
630
+ id: "google.google_search",
631
+ name: "google_search",
632
+ inputSchema: import_v45.z.object({
633
+ mode: import_v45.z.enum(["MODE_DYNAMIC", "MODE_UNSPECIFIED"]).default("MODE_UNSPECIFIED"),
634
+ dynamicThreshold: import_v45.z.number().default(1)
635
+ })
636
+ });
637
+
638
+ // src/tool/url-context.ts
639
+ var import_provider_utils5 = require("@ai-sdk/provider-utils");
640
+ var import_v46 = require("zod/v4");
641
+ var urlMetadataSchema = import_v46.z.object({
642
+ retrievedUrl: import_v46.z.string(),
643
+ urlRetrievalStatus: import_v46.z.string()
644
+ });
645
+ var urlContextMetadataSchema = import_v46.z.object({
646
+ urlMetadata: import_v46.z.array(urlMetadataSchema)
647
+ });
648
+ var urlContext = (0, import_provider_utils5.createProviderDefinedToolFactory)({
649
+ id: "google.url_context",
650
+ name: "url_context",
651
+ inputSchema: import_v46.z.object({})
652
+ });
653
+
570
654
  // src/google-generative-ai-language-model.ts
571
655
  var GoogleGenerativeAILanguageModel = class {
572
656
  constructor(modelId, config) {
573
657
  this.specificationVersion = "v2";
658
+ var _a;
574
659
  this.modelId = modelId;
575
660
  this.config = config;
661
+ this.generateId = (_a = config.generateId) != null ? _a : import_provider_utils6.generateId;
576
662
  }
577
663
  get provider() {
578
664
  return this.config.provider;
@@ -596,9 +682,9 @@ var GoogleGenerativeAILanguageModel = class {
596
682
  toolChoice,
597
683
  providerOptions
598
684
  }) {
599
- var _a, _b, _c;
685
+ var _a, _b;
600
686
  const warnings = [];
601
- const googleOptions = await (0, import_provider_utils4.parseProviderOptions)({
687
+ const googleOptions = await (0, import_provider_utils6.parseProviderOptions)({
602
688
  provider: "google",
603
689
  providerOptions,
604
690
  schema: googleGenerativeAIProviderOptions
@@ -609,16 +695,18 @@ var GoogleGenerativeAILanguageModel = class {
609
695
  message: `The 'includeThoughts' option is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`
610
696
  });
611
697
  }
612
- const { contents, systemInstruction } = convertToGoogleGenerativeAIMessages(prompt);
698
+ const isGemmaModel = this.modelId.toLowerCase().startsWith("gemma-");
699
+ const { contents, systemInstruction } = convertToGoogleGenerativeAIMessages(
700
+ prompt,
701
+ { isGemmaModel }
702
+ );
613
703
  const {
614
- tools: googleTools,
704
+ tools: googleTools2,
615
705
  toolConfig: googleToolConfig,
616
706
  toolWarnings
617
707
  } = prepareTools({
618
708
  tools,
619
709
  toolChoice,
620
- useSearchGrounding: (_b = googleOptions == null ? void 0 : googleOptions.useSearchGrounding) != null ? _b : false,
621
- dynamicRetrievalConfig: googleOptions == null ? void 0 : googleOptions.dynamicRetrievalConfig,
622
710
  modelId: this.modelId
623
711
  });
624
712
  return {
@@ -638,7 +726,7 @@ var GoogleGenerativeAILanguageModel = class {
638
726
  responseSchema: (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && // Google GenAI does not support all OpenAPI Schema features,
639
727
  // so this is needed as an escape hatch:
640
728
  // TODO convert into provider option
641
- ((_c = googleOptions == null ? void 0 : googleOptions.structuredOutputs) != null ? _c : true) ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : void 0,
729
+ ((_b = googleOptions == null ? void 0 : googleOptions.structuredOutputs) != null ? _b : true) ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : void 0,
642
730
  ...(googleOptions == null ? void 0 : googleOptions.audioTimestamp) && {
643
731
  audioTimestamp: googleOptions.audioTimestamp
644
732
  },
@@ -647,9 +735,9 @@ var GoogleGenerativeAILanguageModel = class {
647
735
  thinkingConfig: googleOptions == null ? void 0 : googleOptions.thinkingConfig
648
736
  },
649
737
  contents,
650
- systemInstruction,
738
+ systemInstruction: isGemmaModel ? void 0 : systemInstruction,
651
739
  safetySettings: googleOptions == null ? void 0 : googleOptions.safetySettings,
652
- tools: googleTools,
740
+ tools: googleTools2,
653
741
  toolConfig: googleToolConfig,
654
742
  cachedContent: googleOptions == null ? void 0 : googleOptions.cachedContent
655
743
  },
@@ -657,25 +745,25 @@ var GoogleGenerativeAILanguageModel = class {
657
745
  };
658
746
  }
659
747
  async doGenerate(options) {
660
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
748
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
661
749
  const { args, warnings } = await this.getArgs(options);
662
750
  const body = JSON.stringify(args);
663
- const mergedHeaders = (0, import_provider_utils4.combineHeaders)(
664
- await (0, import_provider_utils4.resolve)(this.config.headers),
751
+ const mergedHeaders = (0, import_provider_utils6.combineHeaders)(
752
+ await (0, import_provider_utils6.resolve)(this.config.headers),
665
753
  options.headers
666
754
  );
667
755
  const {
668
756
  responseHeaders,
669
757
  value: response,
670
758
  rawValue: rawResponse
671
- } = await (0, import_provider_utils4.postJsonToApi)({
759
+ } = await (0, import_provider_utils6.postJsonToApi)({
672
760
  url: `${this.config.baseURL}/${getModelPath(
673
761
  this.modelId
674
762
  )}:generateContent`,
675
763
  headers: mergedHeaders,
676
764
  body: args,
677
765
  failedResponseHandler: googleFailedResponseHandler,
678
- successfulResponseHandler: (0, import_provider_utils4.createJsonResponseHandler)(responseSchema),
766
+ successfulResponseHandler: (0, import_provider_utils6.createJsonResponseHandler)(responseSchema),
679
767
  abortSignal: options.abortSignal,
680
768
  fetch: this.config.fetch
681
769
  });
@@ -729,7 +817,9 @@ var GoogleGenerativeAILanguageModel = class {
729
817
  providerMetadata: {
730
818
  google: {
731
819
  groundingMetadata: (_h = candidate.groundingMetadata) != null ? _h : null,
732
- safetyRatings: (_i = candidate.safetyRatings) != null ? _i : null
820
+ urlContextMetadata: (_i = candidate.urlContextMetadata) != null ? _i : null,
821
+ safetyRatings: (_j = candidate.safetyRatings) != null ? _j : null,
822
+ usageMetadata: usageMetadata != null ? usageMetadata : null
733
823
  }
734
824
  },
735
825
  request: { body },
@@ -743,18 +833,18 @@ var GoogleGenerativeAILanguageModel = class {
743
833
  async doStream(options) {
744
834
  const { args, warnings } = await this.getArgs(options);
745
835
  const body = JSON.stringify(args);
746
- const headers = (0, import_provider_utils4.combineHeaders)(
747
- await (0, import_provider_utils4.resolve)(this.config.headers),
836
+ const headers = (0, import_provider_utils6.combineHeaders)(
837
+ await (0, import_provider_utils6.resolve)(this.config.headers),
748
838
  options.headers
749
839
  );
750
- const { responseHeaders, value: response } = await (0, import_provider_utils4.postJsonToApi)({
840
+ const { responseHeaders, value: response } = await (0, import_provider_utils6.postJsonToApi)({
751
841
  url: `${this.config.baseURL}/${getModelPath(
752
842
  this.modelId
753
843
  )}:streamGenerateContent?alt=sse`,
754
844
  headers,
755
845
  body: args,
756
846
  failedResponseHandler: googleFailedResponseHandler,
757
- successfulResponseHandler: (0, import_provider_utils4.createEventSourceResponseHandler)(chunkSchema),
847
+ successfulResponseHandler: (0, import_provider_utils6.createEventSourceResponseHandler)(chunkSchema),
758
848
  abortSignal: options.abortSignal,
759
849
  fetch: this.config.fetch
760
850
  });
@@ -765,11 +855,12 @@ var GoogleGenerativeAILanguageModel = class {
765
855
  totalTokens: void 0
766
856
  };
767
857
  let providerMetadata = void 0;
768
- const generateId2 = this.config.generateId;
858
+ const generateId3 = this.config.generateId;
769
859
  let hasToolCalls = false;
770
860
  let currentTextBlockId = null;
771
861
  let currentReasoningBlockId = null;
772
862
  let blockCounter = 0;
863
+ const emittedSourceUrls = /* @__PURE__ */ new Set();
773
864
  return {
774
865
  stream: response.pipeThrough(
775
866
  new TransformStream({
@@ -799,6 +890,18 @@ var GoogleGenerativeAILanguageModel = class {
799
890
  return;
800
891
  }
801
892
  const content = candidate.content;
893
+ const sources = extractSources({
894
+ groundingMetadata: candidate.groundingMetadata,
895
+ generateId: generateId3
896
+ });
897
+ if (sources != null) {
898
+ for (const source of sources) {
899
+ if (source.sourceType === "url" && !emittedSourceUrls.has(source.url)) {
900
+ emittedSourceUrls.add(source.url);
901
+ controller.enqueue(source);
902
+ }
903
+ }
904
+ }
802
905
  if (content != null) {
803
906
  const parts = (_g = content.parts) != null ? _g : [];
804
907
  for (const part of parts) {
@@ -858,7 +961,7 @@ var GoogleGenerativeAILanguageModel = class {
858
961
  }
859
962
  const toolCallDeltas = getToolCallsFromParts({
860
963
  parts: content.parts,
861
- generateId: generateId2
964
+ generateId: generateId3
862
965
  });
863
966
  if (toolCallDeltas != null) {
864
967
  for (const toolCall of toolCallDeltas) {
@@ -891,19 +994,16 @@ var GoogleGenerativeAILanguageModel = class {
891
994
  finishReason: candidate.finishReason,
892
995
  hasToolCalls
893
996
  });
894
- const sources = (_h = extractSources({
895
- groundingMetadata: candidate.groundingMetadata,
896
- generateId: generateId2
897
- })) != null ? _h : [];
898
- for (const source of sources) {
899
- controller.enqueue(source);
900
- }
901
997
  providerMetadata = {
902
998
  google: {
903
- groundingMetadata: (_i = candidate.groundingMetadata) != null ? _i : null,
999
+ groundingMetadata: (_h = candidate.groundingMetadata) != null ? _h : null,
1000
+ urlContextMetadata: (_i = candidate.urlContextMetadata) != null ? _i : null,
904
1001
  safetyRatings: (_j = candidate.safetyRatings) != null ? _j : null
905
1002
  }
906
1003
  };
1004
+ if (usageMetadata != null) {
1005
+ providerMetadata.google.usageMetadata = usageMetadata;
1006
+ }
907
1007
  }
908
1008
  },
909
1009
  flush(controller) {
@@ -935,14 +1035,14 @@ var GoogleGenerativeAILanguageModel = class {
935
1035
  };
936
1036
  function getToolCallsFromParts({
937
1037
  parts,
938
- generateId: generateId2
1038
+ generateId: generateId3
939
1039
  }) {
940
1040
  const functionCallParts = parts == null ? void 0 : parts.filter(
941
1041
  (part) => "functionCall" in part
942
1042
  );
943
1043
  return functionCallParts == null || functionCallParts.length === 0 ? void 0 : functionCallParts.map((part) => ({
944
1044
  type: "tool-call",
945
- toolCallId: generateId2(),
1045
+ toolCallId: generateId3(),
946
1046
  toolName: part.functionCall.name,
947
1047
  args: JSON.stringify(part.functionCall.args)
948
1048
  }));
@@ -954,7 +1054,7 @@ function getInlineDataParts(parts) {
954
1054
  }
955
1055
  function extractSources({
956
1056
  groundingMetadata,
957
- generateId: generateId2
1057
+ generateId: generateId3
958
1058
  }) {
959
1059
  var _a;
960
1060
  return (_a = groundingMetadata == null ? void 0 : groundingMetadata.groundingChunks) == null ? void 0 : _a.filter(
@@ -962,108 +1062,196 @@ function extractSources({
962
1062
  ).map((chunk) => ({
963
1063
  type: "source",
964
1064
  sourceType: "url",
965
- id: generateId2(),
1065
+ id: generateId3(),
966
1066
  url: chunk.web.uri,
967
1067
  title: chunk.web.title
968
1068
  }));
969
1069
  }
970
- var contentSchema = import_zod5.z.object({
971
- parts: import_zod5.z.array(
972
- import_zod5.z.union([
1070
+ var contentSchema = import_v47.z.object({
1071
+ parts: import_v47.z.array(
1072
+ import_v47.z.union([
973
1073
  // note: order matters since text can be fully empty
974
- import_zod5.z.object({
975
- functionCall: import_zod5.z.object({
976
- name: import_zod5.z.string(),
977
- args: import_zod5.z.unknown()
1074
+ import_v47.z.object({
1075
+ functionCall: import_v47.z.object({
1076
+ name: import_v47.z.string(),
1077
+ args: import_v47.z.unknown()
978
1078
  })
979
1079
  }),
980
- import_zod5.z.object({
981
- inlineData: import_zod5.z.object({
982
- mimeType: import_zod5.z.string(),
983
- data: import_zod5.z.string()
1080
+ import_v47.z.object({
1081
+ inlineData: import_v47.z.object({
1082
+ mimeType: import_v47.z.string(),
1083
+ data: import_v47.z.string()
984
1084
  })
985
1085
  }),
986
- import_zod5.z.object({
987
- text: import_zod5.z.string().nullish(),
988
- thought: import_zod5.z.boolean().nullish()
1086
+ import_v47.z.object({
1087
+ text: import_v47.z.string().nullish(),
1088
+ thought: import_v47.z.boolean().nullish()
989
1089
  })
990
1090
  ])
991
1091
  ).nullish()
992
1092
  });
993
- var groundingChunkSchema = import_zod5.z.object({
994
- web: import_zod5.z.object({ uri: import_zod5.z.string(), title: import_zod5.z.string() }).nullish(),
995
- retrievedContext: import_zod5.z.object({ uri: import_zod5.z.string(), title: import_zod5.z.string() }).nullish()
996
- });
997
- var groundingMetadataSchema = import_zod5.z.object({
998
- webSearchQueries: import_zod5.z.array(import_zod5.z.string()).nullish(),
999
- retrievalQueries: import_zod5.z.array(import_zod5.z.string()).nullish(),
1000
- searchEntryPoint: import_zod5.z.object({ renderedContent: import_zod5.z.string() }).nullish(),
1001
- groundingChunks: import_zod5.z.array(groundingChunkSchema).nullish(),
1002
- groundingSupports: import_zod5.z.array(
1003
- import_zod5.z.object({
1004
- segment: import_zod5.z.object({
1005
- startIndex: import_zod5.z.number().nullish(),
1006
- endIndex: import_zod5.z.number().nullish(),
1007
- text: import_zod5.z.string().nullish()
1008
- }),
1009
- segment_text: import_zod5.z.string().nullish(),
1010
- groundingChunkIndices: import_zod5.z.array(import_zod5.z.number()).nullish(),
1011
- supportChunkIndices: import_zod5.z.array(import_zod5.z.number()).nullish(),
1012
- confidenceScores: import_zod5.z.array(import_zod5.z.number()).nullish(),
1013
- confidenceScore: import_zod5.z.array(import_zod5.z.number()).nullish()
1014
- })
1015
- ).nullish(),
1016
- retrievalMetadata: import_zod5.z.union([
1017
- import_zod5.z.object({
1018
- webDynamicRetrievalScore: import_zod5.z.number()
1019
- }),
1020
- import_zod5.z.object({})
1021
- ]).nullish()
1022
- });
1023
- var safetyRatingSchema = import_zod5.z.object({
1024
- category: import_zod5.z.string().nullish(),
1025
- probability: import_zod5.z.string().nullish(),
1026
- probabilityScore: import_zod5.z.number().nullish(),
1027
- severity: import_zod5.z.string().nullish(),
1028
- severityScore: import_zod5.z.number().nullish(),
1029
- blocked: import_zod5.z.boolean().nullish()
1093
+ var safetyRatingSchema = import_v47.z.object({
1094
+ category: import_v47.z.string().nullish(),
1095
+ probability: import_v47.z.string().nullish(),
1096
+ probabilityScore: import_v47.z.number().nullish(),
1097
+ severity: import_v47.z.string().nullish(),
1098
+ severityScore: import_v47.z.number().nullish(),
1099
+ blocked: import_v47.z.boolean().nullish()
1030
1100
  });
1031
- var usageSchema = import_zod5.z.object({
1032
- cachedContentTokenCount: import_zod5.z.number().nullish(),
1033
- thoughtsTokenCount: import_zod5.z.number().nullish(),
1034
- promptTokenCount: import_zod5.z.number().nullish(),
1035
- candidatesTokenCount: import_zod5.z.number().nullish(),
1036
- totalTokenCount: import_zod5.z.number().nullish()
1101
+ var usageSchema = import_v47.z.object({
1102
+ cachedContentTokenCount: import_v47.z.number().nullish(),
1103
+ thoughtsTokenCount: import_v47.z.number().nullish(),
1104
+ promptTokenCount: import_v47.z.number().nullish(),
1105
+ candidatesTokenCount: import_v47.z.number().nullish(),
1106
+ totalTokenCount: import_v47.z.number().nullish()
1037
1107
  });
1038
- var responseSchema = import_zod5.z.object({
1039
- candidates: import_zod5.z.array(
1040
- import_zod5.z.object({
1041
- content: contentSchema.nullish().or(import_zod5.z.object({}).strict()),
1042
- finishReason: import_zod5.z.string().nullish(),
1043
- safetyRatings: import_zod5.z.array(safetyRatingSchema).nullish(),
1044
- groundingMetadata: groundingMetadataSchema.nullish()
1108
+ var responseSchema = import_v47.z.object({
1109
+ candidates: import_v47.z.array(
1110
+ import_v47.z.object({
1111
+ content: contentSchema.nullish().or(import_v47.z.object({}).strict()),
1112
+ finishReason: import_v47.z.string().nullish(),
1113
+ safetyRatings: import_v47.z.array(safetyRatingSchema).nullish(),
1114
+ groundingMetadata: groundingMetadataSchema.nullish(),
1115
+ urlContextMetadata: urlContextMetadataSchema.nullish()
1045
1116
  })
1046
1117
  ),
1047
1118
  usageMetadata: usageSchema.nullish()
1048
1119
  });
1049
- var chunkSchema = import_zod5.z.object({
1050
- candidates: import_zod5.z.array(
1051
- import_zod5.z.object({
1120
+ var chunkSchema = import_v47.z.object({
1121
+ candidates: import_v47.z.array(
1122
+ import_v47.z.object({
1052
1123
  content: contentSchema.nullish(),
1053
- finishReason: import_zod5.z.string().nullish(),
1054
- safetyRatings: import_zod5.z.array(safetyRatingSchema).nullish(),
1055
- groundingMetadata: groundingMetadataSchema.nullish()
1124
+ finishReason: import_v47.z.string().nullish(),
1125
+ safetyRatings: import_v47.z.array(safetyRatingSchema).nullish(),
1126
+ groundingMetadata: groundingMetadataSchema.nullish(),
1127
+ urlContextMetadata: urlContextMetadataSchema.nullish()
1056
1128
  })
1057
1129
  ).nullish(),
1058
1130
  usageMetadata: usageSchema.nullish()
1059
1131
  });
1060
1132
 
1133
+ // src/google-tools.ts
1134
+ var googleTools = {
1135
+ /**
1136
+ * Creates a Google search tool that gives Google direct access to real-time web content.
1137
+ * Must have name "google_search".
1138
+ */
1139
+ googleSearch,
1140
+ /**
1141
+ * Creates a URL context tool that gives Google direct access to real-time web content.
1142
+ * Must have name "url_context".
1143
+ */
1144
+ urlContext
1145
+ };
1146
+
1147
+ // src/google-generative-ai-image-model.ts
1148
+ var import_provider_utils7 = require("@ai-sdk/provider-utils");
1149
+ var import_v48 = require("zod/v4");
1150
+ var GoogleGenerativeAIImageModel = class {
1151
+ constructor(modelId, settings, config) {
1152
+ this.modelId = modelId;
1153
+ this.settings = settings;
1154
+ this.config = config;
1155
+ this.specificationVersion = "v2";
1156
+ }
1157
+ get maxImagesPerCall() {
1158
+ var _a;
1159
+ return (_a = this.settings.maxImagesPerCall) != null ? _a : 4;
1160
+ }
1161
+ get provider() {
1162
+ return this.config.provider;
1163
+ }
1164
+ async doGenerate(options) {
1165
+ var _a, _b, _c;
1166
+ const {
1167
+ prompt,
1168
+ n = 1,
1169
+ size = "1024x1024",
1170
+ aspectRatio = "1:1",
1171
+ seed,
1172
+ providerOptions,
1173
+ headers,
1174
+ abortSignal
1175
+ } = options;
1176
+ const warnings = [];
1177
+ if (size != null) {
1178
+ warnings.push({
1179
+ type: "unsupported-setting",
1180
+ setting: "size",
1181
+ details: "This model does not support the `size` option. Use `aspectRatio` instead."
1182
+ });
1183
+ }
1184
+ if (seed != null) {
1185
+ warnings.push({
1186
+ type: "unsupported-setting",
1187
+ setting: "seed",
1188
+ details: "This model does not support the `seed` option through this provider."
1189
+ });
1190
+ }
1191
+ const googleOptions = await (0, import_provider_utils7.parseProviderOptions)({
1192
+ provider: "google",
1193
+ providerOptions,
1194
+ schema: googleImageProviderOptionsSchema
1195
+ });
1196
+ const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
1197
+ const parameters = {
1198
+ sampleCount: n
1199
+ };
1200
+ if (aspectRatio != null) {
1201
+ parameters.aspectRatio = aspectRatio;
1202
+ }
1203
+ if (googleOptions) {
1204
+ Object.assign(parameters, googleOptions);
1205
+ }
1206
+ const body = {
1207
+ instances: [{ prompt }],
1208
+ parameters
1209
+ };
1210
+ const { responseHeaders, value: response } = await (0, import_provider_utils7.postJsonToApi)({
1211
+ url: `${this.config.baseURL}/models/${this.modelId}:predict`,
1212
+ headers: (0, import_provider_utils7.combineHeaders)(await (0, import_provider_utils7.resolve)(this.config.headers), headers),
1213
+ body,
1214
+ failedResponseHandler: googleFailedResponseHandler,
1215
+ successfulResponseHandler: (0, import_provider_utils7.createJsonResponseHandler)(
1216
+ googleImageResponseSchema
1217
+ ),
1218
+ abortSignal,
1219
+ fetch: this.config.fetch
1220
+ });
1221
+ return {
1222
+ images: response.predictions.map(
1223
+ (p) => p.bytesBase64Encoded
1224
+ ),
1225
+ warnings: warnings != null ? warnings : [],
1226
+ providerMetadata: {
1227
+ google: {
1228
+ images: response.predictions.map((prediction) => ({
1229
+ // Add any prediction-specific metadata here
1230
+ }))
1231
+ }
1232
+ },
1233
+ response: {
1234
+ timestamp: currentDate,
1235
+ modelId: this.modelId,
1236
+ headers: responseHeaders
1237
+ }
1238
+ };
1239
+ }
1240
+ };
1241
+ var googleImageResponseSchema = import_v48.z.object({
1242
+ predictions: import_v48.z.array(import_v48.z.object({ bytesBase64Encoded: import_v48.z.string() })).default([])
1243
+ });
1244
+ var googleImageProviderOptionsSchema = import_v48.z.object({
1245
+ personGeneration: import_v48.z.enum(["dont_allow", "allow_adult", "allow_all"]).nullish(),
1246
+ aspectRatio: import_v48.z.enum(["1:1", "3:4", "4:3", "9:16", "16:9"]).nullish()
1247
+ });
1248
+
1061
1249
  // src/google-provider.ts
1062
1250
  function createGoogleGenerativeAI(options = {}) {
1063
1251
  var _a;
1064
- const baseURL = (_a = (0, import_provider_utils5.withoutTrailingSlash)(options.baseURL)) != null ? _a : "https://generativelanguage.googleapis.com/v1beta";
1252
+ const baseURL = (_a = (0, import_provider_utils8.withoutTrailingSlash)(options.baseURL)) != null ? _a : "https://generativelanguage.googleapis.com/v1beta";
1065
1253
  const getHeaders = () => ({
1066
- "x-goog-api-key": (0, import_provider_utils5.loadApiKey)({
1254
+ "x-goog-api-key": (0, import_provider_utils8.loadApiKey)({
1067
1255
  apiKey: options.apiKey,
1068
1256
  environmentVariableName: "GOOGLE_GENERATIVE_AI_API_KEY",
1069
1257
  description: "Google Generative AI"
@@ -1076,7 +1264,7 @@ function createGoogleGenerativeAI(options = {}) {
1076
1264
  provider: "google.generative-ai",
1077
1265
  baseURL,
1078
1266
  headers: getHeaders,
1079
- generateId: (_a2 = options.generateId) != null ? _a2 : import_provider_utils5.generateId,
1267
+ generateId: (_a2 = options.generateId) != null ? _a2 : import_provider_utils8.generateId,
1080
1268
  supportedUrls: () => ({
1081
1269
  "*": [
1082
1270
  // Only allow requests to the Google Generative Language "files" endpoint
@@ -1093,6 +1281,12 @@ function createGoogleGenerativeAI(options = {}) {
1093
1281
  headers: getHeaders,
1094
1282
  fetch: options.fetch
1095
1283
  });
1284
+ const createImageModel = (modelId, settings = {}) => new GoogleGenerativeAIImageModel(modelId, settings, {
1285
+ provider: "google.generative-ai",
1286
+ baseURL,
1287
+ headers: getHeaders,
1288
+ fetch: options.fetch
1289
+ });
1096
1290
  const provider = function(modelId) {
1097
1291
  if (new.target) {
1098
1292
  throw new Error(
@@ -1107,9 +1301,9 @@ function createGoogleGenerativeAI(options = {}) {
1107
1301
  provider.embedding = createEmbeddingModel;
1108
1302
  provider.textEmbedding = createEmbeddingModel;
1109
1303
  provider.textEmbeddingModel = createEmbeddingModel;
1110
- provider.imageModel = (modelId) => {
1111
- throw new import_provider4.NoSuchModelError({ modelId, modelType: "imageModel" });
1112
- };
1304
+ provider.image = createImageModel;
1305
+ provider.imageModel = createImageModel;
1306
+ provider.tools = googleTools;
1113
1307
  return provider;
1114
1308
  }
1115
1309
  var google = createGoogleGenerativeAI();