@ai-sdk/google 2.0.0-beta.1 → 2.0.0-beta.11

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,9 +1,6 @@
1
1
  // src/google-provider.ts
2
2
  import {
3
- NoSuchModelError
4
- } from "@ai-sdk/provider";
5
- import {
6
- generateId,
3
+ generateId as generateId2,
7
4
  loadApiKey,
8
5
  withoutTrailingSlash
9
6
  } from "@ai-sdk/provider-utils";
@@ -19,11 +16,11 @@ import {
19
16
  postJsonToApi,
20
17
  resolve
21
18
  } from "@ai-sdk/provider-utils";
22
- import { z as z3 } from "zod";
19
+ import { z as z3 } from "zod/v4";
23
20
 
24
21
  // src/google-error.ts
25
22
  import { createJsonErrorResponseHandler } from "@ai-sdk/provider-utils";
26
- import { z } from "zod";
23
+ import { z } from "zod/v4";
27
24
  var googleErrorDataSchema = z.object({
28
25
  error: z.object({
29
26
  code: z.number().nullable(),
@@ -37,7 +34,7 @@ var googleFailedResponseHandler = createJsonErrorResponseHandler({
37
34
  });
38
35
 
39
36
  // src/google-generative-ai-embedding-options.ts
40
- import { z as z2 } from "zod";
37
+ import { z as z2 } from "zod/v4";
41
38
  var googleGenerativeAIEmbeddingProviderOptions = z2.object({
42
39
  /**
43
40
  * Optional. Optional reduced dimension for the output embedding.
@@ -103,6 +100,35 @@ var GoogleGenerativeAIEmbeddingModel = class {
103
100
  await resolve(this.config.headers),
104
101
  headers
105
102
  );
103
+ if (values.length === 1) {
104
+ const {
105
+ responseHeaders: responseHeaders2,
106
+ value: response2,
107
+ rawValue: rawValue2
108
+ } = await postJsonToApi({
109
+ url: `${this.config.baseURL}/models/${this.modelId}:embedContent`,
110
+ headers: mergedHeaders,
111
+ body: {
112
+ model: `models/${this.modelId}`,
113
+ content: {
114
+ parts: [{ text: values[0] }]
115
+ },
116
+ outputDimensionality: googleOptions == null ? void 0 : googleOptions.outputDimensionality,
117
+ taskType: googleOptions == null ? void 0 : googleOptions.taskType
118
+ },
119
+ failedResponseHandler: googleFailedResponseHandler,
120
+ successfulResponseHandler: createJsonResponseHandler(
121
+ googleGenerativeAISingleEmbeddingResponseSchema
122
+ ),
123
+ abortSignal,
124
+ fetch: this.config.fetch
125
+ });
126
+ return {
127
+ embeddings: [response2.embedding.values],
128
+ usage: void 0,
129
+ response: { headers: responseHeaders2, body: rawValue2 }
130
+ };
131
+ }
106
132
  const {
107
133
  responseHeaders,
108
134
  value: response,
@@ -135,17 +161,21 @@ var GoogleGenerativeAIEmbeddingModel = class {
135
161
  var googleGenerativeAITextEmbeddingResponseSchema = z3.object({
136
162
  embeddings: z3.array(z3.object({ values: z3.array(z3.number()) }))
137
163
  });
164
+ var googleGenerativeAISingleEmbeddingResponseSchema = z3.object({
165
+ embedding: z3.object({ values: z3.array(z3.number()) })
166
+ });
138
167
 
139
168
  // src/google-generative-ai-language-model.ts
140
169
  import {
141
170
  combineHeaders as combineHeaders2,
142
171
  createEventSourceResponseHandler,
143
172
  createJsonResponseHandler as createJsonResponseHandler2,
173
+ generateId,
144
174
  parseProviderOptions as parseProviderOptions2,
145
175
  postJsonToApi as postJsonToApi2,
146
176
  resolve as resolve2
147
177
  } from "@ai-sdk/provider-utils";
148
- import { z as z5 } from "zod";
178
+ import { z as z7 } from "zod/v4";
149
179
 
150
180
  // src/convert-json-schema-to-openapi-schema.ts
151
181
  function convertJSONSchemaToOpenAPISchema(jsonSchema) {
@@ -241,7 +271,7 @@ function convertJSONSchemaToOpenAPISchema(jsonSchema) {
241
271
  return result;
242
272
  }
243
273
  function isEmptyObjectSchema(jsonSchema) {
244
- return jsonSchema != null && typeof jsonSchema === "object" && jsonSchema.type === "object" && (jsonSchema.properties == null || Object.keys(jsonSchema.properties).length === 0);
274
+ return jsonSchema != null && typeof jsonSchema === "object" && jsonSchema.type === "object" && (jsonSchema.properties == null || Object.keys(jsonSchema.properties).length === 0) && !jsonSchema.additionalProperties;
245
275
  }
246
276
 
247
277
  // src/convert-to-google-generative-ai-messages.ts
@@ -249,10 +279,12 @@ import {
249
279
  UnsupportedFunctionalityError
250
280
  } from "@ai-sdk/provider";
251
281
  import { convertToBase64 } from "@ai-sdk/provider-utils";
252
- function convertToGoogleGenerativeAIMessages(prompt) {
282
+ function convertToGoogleGenerativeAIMessages(prompt, options) {
283
+ var _a;
253
284
  const systemInstructionParts = [];
254
285
  const contents = [];
255
286
  let systemMessagesAllowed = true;
287
+ const isGemmaModel = (_a = options == null ? void 0 : options.isGemmaModel) != null ? _a : false;
256
288
  for (const { role, content } of prompt) {
257
289
  switch (role) {
258
290
  case "system": {
@@ -353,8 +385,12 @@ function convertToGoogleGenerativeAIMessages(prompt) {
353
385
  }
354
386
  }
355
387
  }
388
+ if (isGemmaModel && systemInstructionParts.length > 0 && contents.length > 0 && contents[0].role === "user") {
389
+ const systemText = systemInstructionParts.map((part) => part.text).join("\n\n");
390
+ contents[0].parts.unshift({ text: systemText + "\n\n" });
391
+ }
356
392
  return {
357
- systemInstruction: systemInstructionParts.length > 0 ? { parts: systemInstructionParts } : void 0,
393
+ systemInstruction: systemInstructionParts.length > 0 && !isGemmaModel ? { parts: systemInstructionParts } : void 0,
358
394
  contents
359
395
  };
360
396
  }
@@ -365,18 +401,7 @@ function getModelPath(modelId) {
365
401
  }
366
402
 
367
403
  // src/google-generative-ai-options.ts
368
- import { z as z4 } from "zod";
369
- var dynamicRetrievalConfig = z4.object({
370
- /**
371
- * The mode of the predictor to be used in dynamic retrieval.
372
- */
373
- mode: z4.enum(["MODE_UNSPECIFIED", "MODE_DYNAMIC"]).optional(),
374
- /**
375
- * The threshold to be used in dynamic retrieval. If not set, a system default
376
- * value is used.
377
- */
378
- dynamicThreshold: z4.number().optional()
379
- });
404
+ import { z as z4 } from "zod/v4";
380
405
  var googleGenerativeAIProviderOptions = z4.object({
381
406
  responseModalities: z4.array(z4.enum(["TEXT", "IMAGE"])).optional(),
382
407
  thinkingConfig: z4.object({
@@ -434,21 +459,7 @@ var googleGenerativeAIProviderOptions = z4.object({
434
459
  *
435
460
  * https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/audio-understanding
436
461
  */
437
- audioTimestamp: z4.boolean().optional(),
438
- /**
439
- Optional. When enabled, the model will use Google search to ground the response.
440
-
441
- @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/overview
442
- */
443
- useSearchGrounding: z4.boolean().optional(),
444
- /**
445
- Optional. Specifies the dynamic retrieval configuration.
446
-
447
- @note Dynamic retrieval is only compatible with Gemini 1.5 Flash.
448
-
449
- @see https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/ground-with-google-search#dynamic-retrieval
450
- */
451
- dynamicRetrievalConfig: dynamicRetrievalConfig.optional()
462
+ audioTimestamp: z4.boolean().optional()
452
463
  });
453
464
 
454
465
  // src/google-prepare-tools.ts
@@ -458,8 +469,6 @@ import {
458
469
  function prepareTools({
459
470
  tools,
460
471
  toolChoice,
461
- useSearchGrounding,
462
- dynamicRetrievalConfig: dynamicRetrievalConfig2,
463
472
  modelId
464
473
  }) {
465
474
  var _a;
@@ -467,28 +476,76 @@ function prepareTools({
467
476
  const toolWarnings = [];
468
477
  const isGemini2 = modelId.includes("gemini-2");
469
478
  const supportsDynamicRetrieval = modelId.includes("gemini-1.5-flash") && !modelId.includes("-8b");
470
- if (useSearchGrounding) {
479
+ if (tools == null) {
480
+ return { tools: void 0, toolConfig: void 0, toolWarnings };
481
+ }
482
+ const hasFunctionTools = tools.some((tool) => tool.type === "function");
483
+ const hasProviderDefinedTools = tools.some(
484
+ (tool) => tool.type === "provider-defined"
485
+ );
486
+ if (hasFunctionTools && hasProviderDefinedTools) {
487
+ toolWarnings.push({
488
+ type: "unsupported-tool",
489
+ tool: tools.find((tool) => tool.type === "function"),
490
+ 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."
491
+ });
492
+ }
493
+ if (hasProviderDefinedTools) {
494
+ const googleTools2 = {};
495
+ const providerDefinedTools = tools.filter(
496
+ (tool) => tool.type === "provider-defined"
497
+ );
498
+ providerDefinedTools.forEach((tool) => {
499
+ switch (tool.id) {
500
+ case "google.google_search":
501
+ if (isGemini2) {
502
+ googleTools2.googleSearch = {};
503
+ } else if (supportsDynamicRetrieval) {
504
+ googleTools2.googleSearchRetrieval = {
505
+ dynamicRetrievalConfig: {
506
+ mode: tool.args.mode,
507
+ dynamicThreshold: tool.args.dynamicThreshold
508
+ }
509
+ };
510
+ } else {
511
+ googleTools2.googleSearchRetrieval = {};
512
+ }
513
+ break;
514
+ case "google.url_context":
515
+ if (isGemini2) {
516
+ googleTools2.urlContext = {};
517
+ } else {
518
+ toolWarnings.push({
519
+ type: "unsupported-tool",
520
+ tool,
521
+ details: "The URL context tool is not supported with other Gemini models than Gemini 2."
522
+ });
523
+ }
524
+ break;
525
+ default:
526
+ toolWarnings.push({ type: "unsupported-tool", tool });
527
+ break;
528
+ }
529
+ });
471
530
  return {
472
- tools: isGemini2 ? { googleSearch: {} } : {
473
- googleSearchRetrieval: !supportsDynamicRetrieval || !dynamicRetrievalConfig2 ? {} : { dynamicRetrievalConfig: dynamicRetrievalConfig2 }
474
- },
531
+ tools: Object.keys(googleTools2).length > 0 ? googleTools2 : void 0,
475
532
  toolConfig: void 0,
476
533
  toolWarnings
477
534
  };
478
535
  }
479
- if (tools == null) {
480
- return { tools: void 0, toolConfig: void 0, toolWarnings };
481
- }
482
536
  const functionDeclarations = [];
483
537
  for (const tool of tools) {
484
- if (tool.type === "provider-defined") {
485
- toolWarnings.push({ type: "unsupported-tool", tool });
486
- } else {
487
- functionDeclarations.push({
488
- name: tool.name,
489
- description: (_a = tool.description) != null ? _a : "",
490
- parameters: convertJSONSchemaToOpenAPISchema(tool.inputSchema)
491
- });
538
+ switch (tool.type) {
539
+ case "function":
540
+ functionDeclarations.push({
541
+ name: tool.name,
542
+ description: (_a = tool.description) != null ? _a : "",
543
+ parameters: convertJSONSchemaToOpenAPISchema(tool.inputSchema)
544
+ });
545
+ break;
546
+ default:
547
+ toolWarnings.push({ type: "unsupported-tool", tool });
548
+ break;
492
549
  }
493
550
  }
494
551
  if (toolChoice == null) {
@@ -565,12 +622,72 @@ function mapGoogleGenerativeAIFinishReason({
565
622
  }
566
623
  }
567
624
 
625
+ // src/tool/google-search.ts
626
+ import { createProviderDefinedToolFactory } from "@ai-sdk/provider-utils";
627
+ import { z as z5 } from "zod/v4";
628
+ var groundingChunkSchema = z5.object({
629
+ web: z5.object({ uri: z5.string(), title: z5.string() }).nullish(),
630
+ retrievedContext: z5.object({ uri: z5.string(), title: z5.string() }).nullish()
631
+ });
632
+ var groundingMetadataSchema = z5.object({
633
+ webSearchQueries: z5.array(z5.string()).nullish(),
634
+ retrievalQueries: z5.array(z5.string()).nullish(),
635
+ searchEntryPoint: z5.object({ renderedContent: z5.string() }).nullish(),
636
+ groundingChunks: z5.array(groundingChunkSchema).nullish(),
637
+ groundingSupports: z5.array(
638
+ z5.object({
639
+ segment: z5.object({
640
+ startIndex: z5.number().nullish(),
641
+ endIndex: z5.number().nullish(),
642
+ text: z5.string().nullish()
643
+ }),
644
+ segment_text: z5.string().nullish(),
645
+ groundingChunkIndices: z5.array(z5.number()).nullish(),
646
+ supportChunkIndices: z5.array(z5.number()).nullish(),
647
+ confidenceScores: z5.array(z5.number()).nullish(),
648
+ confidenceScore: z5.array(z5.number()).nullish()
649
+ })
650
+ ).nullish(),
651
+ retrievalMetadata: z5.union([
652
+ z5.object({
653
+ webDynamicRetrievalScore: z5.number()
654
+ }),
655
+ z5.object({})
656
+ ]).nullish()
657
+ });
658
+ var googleSearch = createProviderDefinedToolFactory({
659
+ id: "google.google_search",
660
+ name: "google_search",
661
+ inputSchema: z5.object({
662
+ mode: z5.enum(["MODE_DYNAMIC", "MODE_UNSPECIFIED"]).default("MODE_UNSPECIFIED"),
663
+ dynamicThreshold: z5.number().default(1)
664
+ })
665
+ });
666
+
667
+ // src/tool/url-context.ts
668
+ import { createProviderDefinedToolFactory as createProviderDefinedToolFactory2 } from "@ai-sdk/provider-utils";
669
+ import { z as z6 } from "zod/v4";
670
+ var urlMetadataSchema = z6.object({
671
+ retrievedUrl: z6.string(),
672
+ urlRetrievalStatus: z6.string()
673
+ });
674
+ var urlContextMetadataSchema = z6.object({
675
+ urlMetadata: z6.array(urlMetadataSchema)
676
+ });
677
+ var urlContext = createProviderDefinedToolFactory2({
678
+ id: "google.url_context",
679
+ name: "url_context",
680
+ inputSchema: z6.object({})
681
+ });
682
+
568
683
  // src/google-generative-ai-language-model.ts
569
684
  var GoogleGenerativeAILanguageModel = class {
570
685
  constructor(modelId, config) {
571
686
  this.specificationVersion = "v2";
687
+ var _a;
572
688
  this.modelId = modelId;
573
689
  this.config = config;
690
+ this.generateId = (_a = config.generateId) != null ? _a : generateId;
574
691
  }
575
692
  get provider() {
576
693
  return this.config.provider;
@@ -594,7 +711,7 @@ var GoogleGenerativeAILanguageModel = class {
594
711
  toolChoice,
595
712
  providerOptions
596
713
  }) {
597
- var _a, _b, _c;
714
+ var _a, _b;
598
715
  const warnings = [];
599
716
  const googleOptions = await parseProviderOptions2({
600
717
  provider: "google",
@@ -607,16 +724,18 @@ var GoogleGenerativeAILanguageModel = class {
607
724
  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}).`
608
725
  });
609
726
  }
610
- const { contents, systemInstruction } = convertToGoogleGenerativeAIMessages(prompt);
727
+ const isGemmaModel = this.modelId.toLowerCase().startsWith("gemma-");
728
+ const { contents, systemInstruction } = convertToGoogleGenerativeAIMessages(
729
+ prompt,
730
+ { isGemmaModel }
731
+ );
611
732
  const {
612
- tools: googleTools,
733
+ tools: googleTools2,
613
734
  toolConfig: googleToolConfig,
614
735
  toolWarnings
615
736
  } = prepareTools({
616
737
  tools,
617
738
  toolChoice,
618
- useSearchGrounding: (_b = googleOptions == null ? void 0 : googleOptions.useSearchGrounding) != null ? _b : false,
619
- dynamicRetrievalConfig: googleOptions == null ? void 0 : googleOptions.dynamicRetrievalConfig,
620
739
  modelId: this.modelId
621
740
  });
622
741
  return {
@@ -636,7 +755,7 @@ var GoogleGenerativeAILanguageModel = class {
636
755
  responseSchema: (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && // Google GenAI does not support all OpenAPI Schema features,
637
756
  // so this is needed as an escape hatch:
638
757
  // TODO convert into provider option
639
- ((_c = googleOptions == null ? void 0 : googleOptions.structuredOutputs) != null ? _c : true) ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : void 0,
758
+ ((_b = googleOptions == null ? void 0 : googleOptions.structuredOutputs) != null ? _b : true) ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : void 0,
640
759
  ...(googleOptions == null ? void 0 : googleOptions.audioTimestamp) && {
641
760
  audioTimestamp: googleOptions.audioTimestamp
642
761
  },
@@ -645,9 +764,9 @@ var GoogleGenerativeAILanguageModel = class {
645
764
  thinkingConfig: googleOptions == null ? void 0 : googleOptions.thinkingConfig
646
765
  },
647
766
  contents,
648
- systemInstruction,
767
+ systemInstruction: isGemmaModel ? void 0 : systemInstruction,
649
768
  safetySettings: googleOptions == null ? void 0 : googleOptions.safetySettings,
650
- tools: googleTools,
769
+ tools: googleTools2,
651
770
  toolConfig: googleToolConfig,
652
771
  cachedContent: googleOptions == null ? void 0 : googleOptions.cachedContent
653
772
  },
@@ -655,7 +774,7 @@ var GoogleGenerativeAILanguageModel = class {
655
774
  };
656
775
  }
657
776
  async doGenerate(options) {
658
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
777
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
659
778
  const { args, warnings } = await this.getArgs(options);
660
779
  const body = JSON.stringify(args);
661
780
  const mergedHeaders = combineHeaders2(
@@ -727,7 +846,9 @@ var GoogleGenerativeAILanguageModel = class {
727
846
  providerMetadata: {
728
847
  google: {
729
848
  groundingMetadata: (_h = candidate.groundingMetadata) != null ? _h : null,
730
- safetyRatings: (_i = candidate.safetyRatings) != null ? _i : null
849
+ urlContextMetadata: (_i = candidate.urlContextMetadata) != null ? _i : null,
850
+ safetyRatings: (_j = candidate.safetyRatings) != null ? _j : null,
851
+ usageMetadata: usageMetadata != null ? usageMetadata : null
731
852
  }
732
853
  },
733
854
  request: { body },
@@ -763,11 +884,12 @@ var GoogleGenerativeAILanguageModel = class {
763
884
  totalTokens: void 0
764
885
  };
765
886
  let providerMetadata = void 0;
766
- const generateId2 = this.config.generateId;
887
+ const generateId3 = this.config.generateId;
767
888
  let hasToolCalls = false;
768
889
  let currentTextBlockId = null;
769
890
  let currentReasoningBlockId = null;
770
891
  let blockCounter = 0;
892
+ const emittedSourceUrls = /* @__PURE__ */ new Set();
771
893
  return {
772
894
  stream: response.pipeThrough(
773
895
  new TransformStream({
@@ -797,6 +919,18 @@ var GoogleGenerativeAILanguageModel = class {
797
919
  return;
798
920
  }
799
921
  const content = candidate.content;
922
+ const sources = extractSources({
923
+ groundingMetadata: candidate.groundingMetadata,
924
+ generateId: generateId3
925
+ });
926
+ if (sources != null) {
927
+ for (const source of sources) {
928
+ if (source.sourceType === "url" && !emittedSourceUrls.has(source.url)) {
929
+ emittedSourceUrls.add(source.url);
930
+ controller.enqueue(source);
931
+ }
932
+ }
933
+ }
800
934
  if (content != null) {
801
935
  const parts = (_g = content.parts) != null ? _g : [];
802
936
  for (const part of parts) {
@@ -856,7 +990,7 @@ var GoogleGenerativeAILanguageModel = class {
856
990
  }
857
991
  const toolCallDeltas = getToolCallsFromParts({
858
992
  parts: content.parts,
859
- generateId: generateId2
993
+ generateId: generateId3
860
994
  });
861
995
  if (toolCallDeltas != null) {
862
996
  for (const toolCall of toolCallDeltas) {
@@ -889,19 +1023,16 @@ var GoogleGenerativeAILanguageModel = class {
889
1023
  finishReason: candidate.finishReason,
890
1024
  hasToolCalls
891
1025
  });
892
- const sources = (_h = extractSources({
893
- groundingMetadata: candidate.groundingMetadata,
894
- generateId: generateId2
895
- })) != null ? _h : [];
896
- for (const source of sources) {
897
- controller.enqueue(source);
898
- }
899
1026
  providerMetadata = {
900
1027
  google: {
901
- groundingMetadata: (_i = candidate.groundingMetadata) != null ? _i : null,
1028
+ groundingMetadata: (_h = candidate.groundingMetadata) != null ? _h : null,
1029
+ urlContextMetadata: (_i = candidate.urlContextMetadata) != null ? _i : null,
902
1030
  safetyRatings: (_j = candidate.safetyRatings) != null ? _j : null
903
1031
  }
904
1032
  };
1033
+ if (usageMetadata != null) {
1034
+ providerMetadata.google.usageMetadata = usageMetadata;
1035
+ }
905
1036
  }
906
1037
  },
907
1038
  flush(controller) {
@@ -933,14 +1064,14 @@ var GoogleGenerativeAILanguageModel = class {
933
1064
  };
934
1065
  function getToolCallsFromParts({
935
1066
  parts,
936
- generateId: generateId2
1067
+ generateId: generateId3
937
1068
  }) {
938
1069
  const functionCallParts = parts == null ? void 0 : parts.filter(
939
1070
  (part) => "functionCall" in part
940
1071
  );
941
1072
  return functionCallParts == null || functionCallParts.length === 0 ? void 0 : functionCallParts.map((part) => ({
942
1073
  type: "tool-call",
943
- toolCallId: generateId2(),
1074
+ toolCallId: generateId3(),
944
1075
  toolName: part.functionCall.name,
945
1076
  args: JSON.stringify(part.functionCall.args)
946
1077
  }));
@@ -952,7 +1083,7 @@ function getInlineDataParts(parts) {
952
1083
  }
953
1084
  function extractSources({
954
1085
  groundingMetadata,
955
- generateId: generateId2
1086
+ generateId: generateId3
956
1087
  }) {
957
1088
  var _a;
958
1089
  return (_a = groundingMetadata == null ? void 0 : groundingMetadata.groundingChunks) == null ? void 0 : _a.filter(
@@ -960,102 +1091,196 @@ function extractSources({
960
1091
  ).map((chunk) => ({
961
1092
  type: "source",
962
1093
  sourceType: "url",
963
- id: generateId2(),
1094
+ id: generateId3(),
964
1095
  url: chunk.web.uri,
965
1096
  title: chunk.web.title
966
1097
  }));
967
1098
  }
968
- var contentSchema = z5.object({
969
- parts: z5.array(
970
- z5.union([
1099
+ var contentSchema = z7.object({
1100
+ parts: z7.array(
1101
+ z7.union([
971
1102
  // note: order matters since text can be fully empty
972
- z5.object({
973
- functionCall: z5.object({
974
- name: z5.string(),
975
- args: z5.unknown()
1103
+ z7.object({
1104
+ functionCall: z7.object({
1105
+ name: z7.string(),
1106
+ args: z7.unknown()
976
1107
  })
977
1108
  }),
978
- z5.object({
979
- inlineData: z5.object({
980
- mimeType: z5.string(),
981
- data: z5.string()
1109
+ z7.object({
1110
+ inlineData: z7.object({
1111
+ mimeType: z7.string(),
1112
+ data: z7.string()
982
1113
  })
983
1114
  }),
984
- z5.object({
985
- text: z5.string().nullish(),
986
- thought: z5.boolean().nullish()
1115
+ z7.object({
1116
+ text: z7.string().nullish(),
1117
+ thought: z7.boolean().nullish()
987
1118
  })
988
1119
  ])
989
1120
  ).nullish()
990
1121
  });
991
- var groundingChunkSchema = z5.object({
992
- web: z5.object({ uri: z5.string(), title: z5.string() }).nullish(),
993
- retrievedContext: z5.object({ uri: z5.string(), title: z5.string() }).nullish()
1122
+ var safetyRatingSchema = z7.object({
1123
+ category: z7.string().nullish(),
1124
+ probability: z7.string().nullish(),
1125
+ probabilityScore: z7.number().nullish(),
1126
+ severity: z7.string().nullish(),
1127
+ severityScore: z7.number().nullish(),
1128
+ blocked: z7.boolean().nullish()
994
1129
  });
995
- var groundingMetadataSchema = z5.object({
996
- webSearchQueries: z5.array(z5.string()).nullish(),
997
- retrievalQueries: z5.array(z5.string()).nullish(),
998
- searchEntryPoint: z5.object({ renderedContent: z5.string() }).nullish(),
999
- groundingChunks: z5.array(groundingChunkSchema).nullish(),
1000
- groundingSupports: z5.array(
1001
- z5.object({
1002
- segment: z5.object({
1003
- startIndex: z5.number().nullish(),
1004
- endIndex: z5.number().nullish(),
1005
- text: z5.string().nullish()
1006
- }),
1007
- segment_text: z5.string().nullish(),
1008
- groundingChunkIndices: z5.array(z5.number()).nullish(),
1009
- supportChunkIndices: z5.array(z5.number()).nullish(),
1010
- confidenceScores: z5.array(z5.number()).nullish(),
1011
- confidenceScore: z5.array(z5.number()).nullish()
1012
- })
1013
- ).nullish(),
1014
- retrievalMetadata: z5.union([
1015
- z5.object({
1016
- webDynamicRetrievalScore: z5.number()
1017
- }),
1018
- z5.object({})
1019
- ]).nullish()
1020
- });
1021
- var safetyRatingSchema = z5.object({
1022
- category: z5.string().nullish(),
1023
- probability: z5.string().nullish(),
1024
- probabilityScore: z5.number().nullish(),
1025
- severity: z5.string().nullish(),
1026
- severityScore: z5.number().nullish(),
1027
- blocked: z5.boolean().nullish()
1028
- });
1029
- var usageSchema = z5.object({
1030
- cachedContentTokenCount: z5.number().nullish(),
1031
- thoughtsTokenCount: z5.number().nullish(),
1032
- promptTokenCount: z5.number().nullish(),
1033
- candidatesTokenCount: z5.number().nullish(),
1034
- totalTokenCount: z5.number().nullish()
1130
+ var usageSchema = z7.object({
1131
+ cachedContentTokenCount: z7.number().nullish(),
1132
+ thoughtsTokenCount: z7.number().nullish(),
1133
+ promptTokenCount: z7.number().nullish(),
1134
+ candidatesTokenCount: z7.number().nullish(),
1135
+ totalTokenCount: z7.number().nullish()
1035
1136
  });
1036
- var responseSchema = z5.object({
1037
- candidates: z5.array(
1038
- z5.object({
1039
- content: contentSchema.nullish().or(z5.object({}).strict()),
1040
- finishReason: z5.string().nullish(),
1041
- safetyRatings: z5.array(safetyRatingSchema).nullish(),
1042
- groundingMetadata: groundingMetadataSchema.nullish()
1137
+ var responseSchema = z7.object({
1138
+ candidates: z7.array(
1139
+ z7.object({
1140
+ content: contentSchema.nullish().or(z7.object({}).strict()),
1141
+ finishReason: z7.string().nullish(),
1142
+ safetyRatings: z7.array(safetyRatingSchema).nullish(),
1143
+ groundingMetadata: groundingMetadataSchema.nullish(),
1144
+ urlContextMetadata: urlContextMetadataSchema.nullish()
1043
1145
  })
1044
1146
  ),
1045
1147
  usageMetadata: usageSchema.nullish()
1046
1148
  });
1047
- var chunkSchema = z5.object({
1048
- candidates: z5.array(
1049
- z5.object({
1149
+ var chunkSchema = z7.object({
1150
+ candidates: z7.array(
1151
+ z7.object({
1050
1152
  content: contentSchema.nullish(),
1051
- finishReason: z5.string().nullish(),
1052
- safetyRatings: z5.array(safetyRatingSchema).nullish(),
1053
- groundingMetadata: groundingMetadataSchema.nullish()
1153
+ finishReason: z7.string().nullish(),
1154
+ safetyRatings: z7.array(safetyRatingSchema).nullish(),
1155
+ groundingMetadata: groundingMetadataSchema.nullish(),
1156
+ urlContextMetadata: urlContextMetadataSchema.nullish()
1054
1157
  })
1055
1158
  ).nullish(),
1056
1159
  usageMetadata: usageSchema.nullish()
1057
1160
  });
1058
1161
 
1162
+ // src/google-tools.ts
1163
+ var googleTools = {
1164
+ /**
1165
+ * Creates a Google search tool that gives Google direct access to real-time web content.
1166
+ * Must have name "google_search".
1167
+ */
1168
+ googleSearch,
1169
+ /**
1170
+ * Creates a URL context tool that gives Google direct access to real-time web content.
1171
+ * Must have name "url_context".
1172
+ */
1173
+ urlContext
1174
+ };
1175
+
1176
+ // src/google-generative-ai-image-model.ts
1177
+ import {
1178
+ combineHeaders as combineHeaders3,
1179
+ createJsonResponseHandler as createJsonResponseHandler3,
1180
+ parseProviderOptions as parseProviderOptions3,
1181
+ postJsonToApi as postJsonToApi3,
1182
+ resolve as resolve3
1183
+ } from "@ai-sdk/provider-utils";
1184
+ import { z as z8 } from "zod/v4";
1185
+ var GoogleGenerativeAIImageModel = class {
1186
+ constructor(modelId, settings, config) {
1187
+ this.modelId = modelId;
1188
+ this.settings = settings;
1189
+ this.config = config;
1190
+ this.specificationVersion = "v2";
1191
+ }
1192
+ get maxImagesPerCall() {
1193
+ var _a;
1194
+ return (_a = this.settings.maxImagesPerCall) != null ? _a : 4;
1195
+ }
1196
+ get provider() {
1197
+ return this.config.provider;
1198
+ }
1199
+ async doGenerate(options) {
1200
+ var _a, _b, _c;
1201
+ const {
1202
+ prompt,
1203
+ n = 1,
1204
+ size = "1024x1024",
1205
+ aspectRatio = "1:1",
1206
+ seed,
1207
+ providerOptions,
1208
+ headers,
1209
+ abortSignal
1210
+ } = options;
1211
+ const warnings = [];
1212
+ if (size != null) {
1213
+ warnings.push({
1214
+ type: "unsupported-setting",
1215
+ setting: "size",
1216
+ details: "This model does not support the `size` option. Use `aspectRatio` instead."
1217
+ });
1218
+ }
1219
+ if (seed != null) {
1220
+ warnings.push({
1221
+ type: "unsupported-setting",
1222
+ setting: "seed",
1223
+ details: "This model does not support the `seed` option through this provider."
1224
+ });
1225
+ }
1226
+ const googleOptions = await parseProviderOptions3({
1227
+ provider: "google",
1228
+ providerOptions,
1229
+ schema: googleImageProviderOptionsSchema
1230
+ });
1231
+ const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
1232
+ const parameters = {
1233
+ sampleCount: n
1234
+ };
1235
+ if (aspectRatio != null) {
1236
+ parameters.aspectRatio = aspectRatio;
1237
+ }
1238
+ if (googleOptions) {
1239
+ Object.assign(parameters, googleOptions);
1240
+ }
1241
+ const body = {
1242
+ instances: [{ prompt }],
1243
+ parameters
1244
+ };
1245
+ const { responseHeaders, value: response } = await postJsonToApi3({
1246
+ url: `${this.config.baseURL}/models/${this.modelId}:predict`,
1247
+ headers: combineHeaders3(await resolve3(this.config.headers), headers),
1248
+ body,
1249
+ failedResponseHandler: googleFailedResponseHandler,
1250
+ successfulResponseHandler: createJsonResponseHandler3(
1251
+ googleImageResponseSchema
1252
+ ),
1253
+ abortSignal,
1254
+ fetch: this.config.fetch
1255
+ });
1256
+ return {
1257
+ images: response.predictions.map(
1258
+ (p) => p.bytesBase64Encoded
1259
+ ),
1260
+ warnings: warnings != null ? warnings : [],
1261
+ providerMetadata: {
1262
+ google: {
1263
+ images: response.predictions.map((prediction) => ({
1264
+ // Add any prediction-specific metadata here
1265
+ }))
1266
+ }
1267
+ },
1268
+ response: {
1269
+ timestamp: currentDate,
1270
+ modelId: this.modelId,
1271
+ headers: responseHeaders
1272
+ }
1273
+ };
1274
+ }
1275
+ };
1276
+ var googleImageResponseSchema = z8.object({
1277
+ predictions: z8.array(z8.object({ bytesBase64Encoded: z8.string() })).default([])
1278
+ });
1279
+ var googleImageProviderOptionsSchema = z8.object({
1280
+ personGeneration: z8.enum(["dont_allow", "allow_adult", "allow_all"]).nullish(),
1281
+ aspectRatio: z8.enum(["1:1", "3:4", "4:3", "9:16", "16:9"]).nullish()
1282
+ });
1283
+
1059
1284
  // src/google-provider.ts
1060
1285
  function createGoogleGenerativeAI(options = {}) {
1061
1286
  var _a;
@@ -1074,7 +1299,7 @@ function createGoogleGenerativeAI(options = {}) {
1074
1299
  provider: "google.generative-ai",
1075
1300
  baseURL,
1076
1301
  headers: getHeaders,
1077
- generateId: (_a2 = options.generateId) != null ? _a2 : generateId,
1302
+ generateId: (_a2 = options.generateId) != null ? _a2 : generateId2,
1078
1303
  supportedUrls: () => ({
1079
1304
  "*": [
1080
1305
  // Only allow requests to the Google Generative Language "files" endpoint
@@ -1091,6 +1316,12 @@ function createGoogleGenerativeAI(options = {}) {
1091
1316
  headers: getHeaders,
1092
1317
  fetch: options.fetch
1093
1318
  });
1319
+ const createImageModel = (modelId, settings = {}) => new GoogleGenerativeAIImageModel(modelId, settings, {
1320
+ provider: "google.generative-ai",
1321
+ baseURL,
1322
+ headers: getHeaders,
1323
+ fetch: options.fetch
1324
+ });
1094
1325
  const provider = function(modelId) {
1095
1326
  if (new.target) {
1096
1327
  throw new Error(
@@ -1105,9 +1336,9 @@ function createGoogleGenerativeAI(options = {}) {
1105
1336
  provider.embedding = createEmbeddingModel;
1106
1337
  provider.textEmbedding = createEmbeddingModel;
1107
1338
  provider.textEmbeddingModel = createEmbeddingModel;
1108
- provider.imageModel = (modelId) => {
1109
- throw new NoSuchModelError({ modelId, modelType: "imageModel" });
1110
- };
1339
+ provider.image = createImageModel;
1340
+ provider.imageModel = createImageModel;
1341
+ provider.tools = googleTools;
1111
1342
  return provider;
1112
1343
  }
1113
1344
  var google = createGoogleGenerativeAI();