cloudassist-ai-provider 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/CHANGELOG.md +1901 -0
  2. package/README.md +35 -0
  3. package/dist/convert-json-schema-to-openapi-schema.d.ts +6 -0
  4. package/dist/convert-json-schema-to-openapi-schema.d.ts.map +1 -0
  5. package/dist/convert-json-schema-to-openapi-schema.js +108 -0
  6. package/dist/convert-json-schema-to-openapi-schema.test.d.ts +2 -0
  7. package/dist/convert-json-schema-to-openapi-schema.test.d.ts.map +1 -0
  8. package/dist/convert-json-schema-to-openapi-schema.test.js +630 -0
  9. package/dist/convert-to-google-generative-ai-messages.d.ts +7 -0
  10. package/dist/convert-to-google-generative-ai-messages.d.ts.map +1 -0
  11. package/dist/convert-to-google-generative-ai-messages.js +195 -0
  12. package/dist/convert-to-google-generative-ai-messages.test.d.ts +2 -0
  13. package/dist/convert-to-google-generative-ai-messages.test.d.ts.map +1 -0
  14. package/dist/convert-to-google-generative-ai-messages.test.js +456 -0
  15. package/dist/get-model-path.d.ts +2 -0
  16. package/dist/get-model-path.d.ts.map +1 -0
  17. package/dist/get-model-path.js +3 -0
  18. package/dist/get-model-path.test.d.ts +2 -0
  19. package/dist/get-model-path.test.d.ts.map +1 -0
  20. package/dist/get-model-path.test.js +11 -0
  21. package/dist/google-error.d.ts +12 -0
  22. package/dist/google-error.d.ts.map +1 -0
  23. package/dist/google-error.js +13 -0
  24. package/dist/google-generative-ai-embedding-model.d.ts +21 -0
  25. package/dist/google-generative-ai-embedding-model.d.ts.map +1 -0
  26. package/dist/google-generative-ai-embedding-model.js +88 -0
  27. package/dist/google-generative-ai-embedding-model.test.d.ts +2 -0
  28. package/dist/google-generative-ai-embedding-model.test.d.ts.map +1 -0
  29. package/dist/google-generative-ai-embedding-model.test.js +148 -0
  30. package/dist/google-generative-ai-embedding-options.d.ts +8 -0
  31. package/dist/google-generative-ai-embedding-options.d.ts.map +1 -0
  32. package/dist/google-generative-ai-embedding-options.js +33 -0
  33. package/dist/google-generative-ai-image-model.d.ts +31 -0
  34. package/dist/google-generative-ai-image-model.d.ts.map +1 -0
  35. package/dist/google-generative-ai-image-model.js +96 -0
  36. package/dist/google-generative-ai-image-model.test.d.ts +2 -0
  37. package/dist/google-generative-ai-image-model.test.d.ts.map +1 -0
  38. package/dist/google-generative-ai-image-model.test.js +252 -0
  39. package/dist/google-generative-ai-image-settings.d.ts +8 -0
  40. package/dist/google-generative-ai-image-settings.d.ts.map +1 -0
  41. package/dist/google-generative-ai-image-settings.js +1 -0
  42. package/dist/google-generative-ai-language-model.d.ts +183 -0
  43. package/dist/google-generative-ai-language-model.d.ts.map +1 -0
  44. package/dist/google-generative-ai-language-model.js +1001 -0
  45. package/dist/google-generative-ai-language-model.test.d.ts +2 -0
  46. package/dist/google-generative-ai-language-model.test.d.ts.map +1 -0
  47. package/dist/google-generative-ai-language-model.test.js +3463 -0
  48. package/dist/google-generative-ai-options.d.ts +37 -0
  49. package/dist/google-generative-ai-options.d.ts.map +1 -0
  50. package/dist/google-generative-ai-options.js +149 -0
  51. package/dist/google-generative-ai-prompt.d.ts +52 -0
  52. package/dist/google-generative-ai-prompt.d.ts.map +1 -0
  53. package/dist/google-generative-ai-prompt.js +1 -0
  54. package/dist/google-prepare-tools.d.ts +27 -0
  55. package/dist/google-prepare-tools.d.ts.map +1 -0
  56. package/dist/google-prepare-tools.js +219 -0
  57. package/dist/google-prepare-tools.test.d.ts +2 -0
  58. package/dist/google-prepare-tools.test.d.ts.map +1 -0
  59. package/dist/google-prepare-tools.test.js +447 -0
  60. package/dist/google-provider.d.ts +65 -0
  61. package/dist/google-provider.d.ts.map +1 -0
  62. package/dist/google-provider.js +74 -0
  63. package/dist/google-provider.test.d.ts +2 -0
  64. package/dist/google-provider.test.d.ts.map +1 -0
  65. package/dist/google-provider.test.js +234 -0
  66. package/dist/google-supported-file-url.d.ts +2 -0
  67. package/dist/google-supported-file-url.d.ts.map +1 -0
  68. package/dist/google-supported-file-url.js +13 -0
  69. package/dist/google-supported-file-url.test.d.ts +2 -0
  70. package/dist/google-supported-file-url.test.d.ts.map +1 -0
  71. package/dist/google-supported-file-url.test.js +45 -0
  72. package/dist/google-tools.d.ts +76 -0
  73. package/dist/google-tools.d.ts.map +1 -0
  74. package/dist/google-tools.js +65 -0
  75. package/dist/index.d.mts +326 -0
  76. package/dist/index.d.ts +9 -0
  77. package/dist/index.d.ts.map +1 -0
  78. package/dist/index.js +2 -0
  79. package/dist/index.js.map +1 -0
  80. package/dist/index.mjs +2172 -0
  81. package/dist/index.mjs.map +1 -0
  82. package/dist/internal/index.d.mts +262 -0
  83. package/dist/internal/index.d.ts +4 -0
  84. package/dist/internal/index.d.ts.map +1 -0
  85. package/dist/internal/index.js +2 -0
  86. package/dist/internal/index.js.map +1 -0
  87. package/dist/internal/index.mjs +1810 -0
  88. package/dist/internal/index.mjs.map +1 -0
  89. package/dist/map-google-generative-ai-finish-reason.d.ts +6 -0
  90. package/dist/map-google-generative-ai-finish-reason.d.ts.map +1 -0
  91. package/dist/map-google-generative-ai-finish-reason.js +22 -0
  92. package/dist/tool/code-execution.d.ts +17 -0
  93. package/dist/tool/code-execution.d.ts.map +1 -0
  94. package/dist/tool/code-execution.js +25 -0
  95. package/dist/tool/enterprise-web-search.d.ts +2 -0
  96. package/dist/tool/enterprise-web-search.d.ts.map +1 -0
  97. package/dist/tool/enterprise-web-search.js +8 -0
  98. package/dist/tool/file-search.d.ts +16 -0
  99. package/dist/tool/file-search.d.ts.map +1 -0
  100. package/dist/tool/file-search.js +33 -0
  101. package/dist/tool/google-maps.d.ts +2 -0
  102. package/dist/tool/google-maps.d.ts.map +1 -0
  103. package/dist/tool/google-maps.js +9 -0
  104. package/dist/tool/google-search.d.ts +14 -0
  105. package/dist/tool/google-search.d.ts.map +1 -0
  106. package/dist/tool/google-search.js +15 -0
  107. package/dist/tool/url-context.d.ts +2 -0
  108. package/dist/tool/url-context.d.ts.map +1 -0
  109. package/dist/tool/url-context.js +7 -0
  110. package/dist/tool/vertex-rag-store.d.ts +16 -0
  111. package/dist/tool/vertex-rag-store.d.ts.map +1 -0
  112. package/dist/tool/vertex-rag-store.js +17 -0
  113. package/dist/version.d.ts +2 -0
  114. package/dist/version.d.ts.map +1 -0
  115. package/dist/version.js +3 -0
  116. package/internal.d.ts +1 -0
  117. package/package.json +73 -0
package/dist/index.mjs ADDED
@@ -0,0 +1,2172 @@
1
+ // src/google-provider.ts
2
+ import {
3
+ generateId as generateId2,
4
+ loadApiKey,
5
+ withoutTrailingSlash,
6
+ withUserAgentSuffix
7
+ } from "@ai-sdk/provider-utils";
8
+
9
+ // src/version.ts
10
+ var VERSION = true ? "2.0.52" : "0.0.0-test";
11
+
12
+ // src/google-generative-ai-embedding-model.ts
13
+ import {
14
+ TooManyEmbeddingValuesForCallError
15
+ } from "@ai-sdk/provider";
16
+ import {
17
+ combineHeaders,
18
+ createJsonResponseHandler,
19
+ lazySchema as lazySchema3,
20
+ parseProviderOptions,
21
+ postJsonToApi,
22
+ resolve,
23
+ zodSchema as zodSchema3
24
+ } from "@ai-sdk/provider-utils";
25
+ import { z as z3 } from "zod/v4";
26
+
27
+ // src/google-error.ts
28
+ import {
29
+ createJsonErrorResponseHandler,
30
+ lazySchema,
31
+ zodSchema
32
+ } from "@ai-sdk/provider-utils";
33
+ import { z } from "zod/v4";
34
+ var googleErrorDataSchema = lazySchema(
35
+ () => zodSchema(
36
+ z.object({
37
+ error: z.object({
38
+ code: z.number().nullable(),
39
+ message: z.string(),
40
+ status: z.string()
41
+ })
42
+ })
43
+ )
44
+ );
45
+ var googleFailedResponseHandler = createJsonErrorResponseHandler({
46
+ errorSchema: googleErrorDataSchema,
47
+ errorToMessage: (data) => data.error.message
48
+ });
49
+
50
+ // src/google-generative-ai-embedding-options.ts
51
+ import {
52
+ lazySchema as lazySchema2,
53
+ zodSchema as zodSchema2
54
+ } from "@ai-sdk/provider-utils";
55
+ import { z as z2 } from "zod/v4";
56
+ var googleGenerativeAIEmbeddingProviderOptions = lazySchema2(
57
+ () => zodSchema2(
58
+ z2.object({
59
+ /**
60
+ * Optional. Optional reduced dimension for the output embedding.
61
+ * If set, excessive values in the output embedding are truncated from the end.
62
+ */
63
+ outputDimensionality: z2.number().optional(),
64
+ /**
65
+ * Optional. Specifies the task type for generating embeddings.
66
+ * Supported task types:
67
+ * - SEMANTIC_SIMILARITY: Optimized for text similarity.
68
+ * - CLASSIFICATION: Optimized for text classification.
69
+ * - CLUSTERING: Optimized for clustering texts based on similarity.
70
+ * - RETRIEVAL_DOCUMENT: Optimized for document retrieval.
71
+ * - RETRIEVAL_QUERY: Optimized for query-based retrieval.
72
+ * - QUESTION_ANSWERING: Optimized for answering questions.
73
+ * - FACT_VERIFICATION: Optimized for verifying factual information.
74
+ * - CODE_RETRIEVAL_QUERY: Optimized for retrieving code blocks based on natural language queries.
75
+ */
76
+ taskType: z2.enum([
77
+ "SEMANTIC_SIMILARITY",
78
+ "CLASSIFICATION",
79
+ "CLUSTERING",
80
+ "RETRIEVAL_DOCUMENT",
81
+ "RETRIEVAL_QUERY",
82
+ "QUESTION_ANSWERING",
83
+ "FACT_VERIFICATION",
84
+ "CODE_RETRIEVAL_QUERY"
85
+ ]).optional()
86
+ })
87
+ )
88
+ );
89
+
90
+ // src/google-generative-ai-embedding-model.ts
91
+ var GoogleGenerativeAIEmbeddingModel = class {
92
+ constructor(modelId, config) {
93
+ this.specificationVersion = "v2";
94
+ this.maxEmbeddingsPerCall = 2048;
95
+ this.supportsParallelCalls = true;
96
+ this.modelId = modelId;
97
+ this.config = config;
98
+ }
99
+ get provider() {
100
+ return this.config.provider;
101
+ }
102
+ async doEmbed({
103
+ values,
104
+ headers,
105
+ abortSignal,
106
+ providerOptions
107
+ }) {
108
+ const googleOptions = await parseProviderOptions({
109
+ provider: "google",
110
+ providerOptions,
111
+ schema: googleGenerativeAIEmbeddingProviderOptions
112
+ });
113
+ if (values.length > this.maxEmbeddingsPerCall) {
114
+ throw new TooManyEmbeddingValuesForCallError({
115
+ provider: this.provider,
116
+ modelId: this.modelId,
117
+ maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
118
+ values
119
+ });
120
+ }
121
+ const mergedHeaders = combineHeaders(
122
+ await resolve(this.config.headers),
123
+ headers
124
+ );
125
+ if (values.length === 1) {
126
+ const {
127
+ responseHeaders: responseHeaders2,
128
+ value: response2,
129
+ rawValue: rawValue2
130
+ } = await postJsonToApi({
131
+ url: `${this.config.baseURL}/models/${this.modelId}:embedContent`,
132
+ headers: mergedHeaders,
133
+ body: {
134
+ model: `models/${this.modelId}`,
135
+ content: {
136
+ parts: [{ text: values[0] }]
137
+ },
138
+ outputDimensionality: googleOptions == null ? void 0 : googleOptions.outputDimensionality,
139
+ taskType: googleOptions == null ? void 0 : googleOptions.taskType
140
+ },
141
+ failedResponseHandler: googleFailedResponseHandler,
142
+ successfulResponseHandler: createJsonResponseHandler(
143
+ googleGenerativeAISingleEmbeddingResponseSchema
144
+ ),
145
+ abortSignal,
146
+ fetch: this.config.fetch
147
+ });
148
+ return {
149
+ embeddings: [response2.embedding.values],
150
+ usage: void 0,
151
+ response: { headers: responseHeaders2, body: rawValue2 }
152
+ };
153
+ }
154
+ const {
155
+ responseHeaders,
156
+ value: response,
157
+ rawValue
158
+ } = await postJsonToApi({
159
+ url: `${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,
160
+ headers: mergedHeaders,
161
+ body: {
162
+ requests: values.map((value) => ({
163
+ model: `models/${this.modelId}`,
164
+ content: { role: "user", parts: [{ text: value }] },
165
+ outputDimensionality: googleOptions == null ? void 0 : googleOptions.outputDimensionality,
166
+ taskType: googleOptions == null ? void 0 : googleOptions.taskType
167
+ }))
168
+ },
169
+ failedResponseHandler: googleFailedResponseHandler,
170
+ successfulResponseHandler: createJsonResponseHandler(
171
+ googleGenerativeAITextEmbeddingResponseSchema
172
+ ),
173
+ abortSignal,
174
+ fetch: this.config.fetch
175
+ });
176
+ return {
177
+ embeddings: response.embeddings.map((item) => item.values),
178
+ usage: void 0,
179
+ response: { headers: responseHeaders, body: rawValue }
180
+ };
181
+ }
182
+ };
183
+ var googleGenerativeAITextEmbeddingResponseSchema = lazySchema3(
184
+ () => zodSchema3(
185
+ z3.object({
186
+ embeddings: z3.array(z3.object({ values: z3.array(z3.number()) }))
187
+ })
188
+ )
189
+ );
190
+ var googleGenerativeAISingleEmbeddingResponseSchema = lazySchema3(
191
+ () => zodSchema3(
192
+ z3.object({
193
+ embedding: z3.object({ values: z3.array(z3.number()) })
194
+ })
195
+ )
196
+ );
197
+
198
+ // src/google-generative-ai-language-model.ts
199
+ import {
200
+ combineHeaders as combineHeaders2,
201
+ createEventSourceResponseHandler,
202
+ generateId,
203
+ lazySchema as lazySchema5,
204
+ parseProviderOptions as parseProviderOptions2,
205
+ postJsonToApi as postJsonToApi2,
206
+ resolve as resolve2,
207
+ zodSchema as zodSchema5
208
+ } from "@ai-sdk/provider-utils";
209
+ import { z as z5 } from "zod/v4";
210
+
211
+ // src/convert-json-schema-to-openapi-schema.ts
212
+ function convertJSONSchemaToOpenAPISchema(jsonSchema, isRoot = true) {
213
+ if (jsonSchema == null) {
214
+ return void 0;
215
+ }
216
+ if (isEmptyObjectSchema(jsonSchema)) {
217
+ if (isRoot) {
218
+ return void 0;
219
+ }
220
+ if (typeof jsonSchema === "object" && jsonSchema.description) {
221
+ return { type: "object", description: jsonSchema.description };
222
+ }
223
+ return { type: "object" };
224
+ }
225
+ if (typeof jsonSchema === "boolean") {
226
+ return { type: "boolean", properties: {} };
227
+ }
228
+ const {
229
+ type,
230
+ description,
231
+ required,
232
+ properties,
233
+ items,
234
+ allOf,
235
+ anyOf,
236
+ oneOf,
237
+ format,
238
+ const: constValue,
239
+ minLength,
240
+ enum: enumValues
241
+ } = jsonSchema;
242
+ const result = {};
243
+ if (description) result.description = description;
244
+ if (required) result.required = required;
245
+ if (format) result.format = format;
246
+ if (constValue !== void 0) {
247
+ result.enum = [constValue];
248
+ }
249
+ if (type) {
250
+ if (Array.isArray(type)) {
251
+ const hasNull = type.includes("null");
252
+ const nonNullTypes = type.filter((t) => t !== "null");
253
+ if (nonNullTypes.length === 0) {
254
+ result.type = "null";
255
+ } else {
256
+ result.anyOf = nonNullTypes.map((t) => ({ type: t }));
257
+ if (hasNull) {
258
+ result.nullable = true;
259
+ }
260
+ }
261
+ } else {
262
+ result.type = type;
263
+ }
264
+ }
265
+ if (enumValues !== void 0) {
266
+ result.enum = enumValues;
267
+ }
268
+ if (properties != null) {
269
+ result.properties = Object.entries(properties).reduce(
270
+ (acc, [key, value]) => {
271
+ acc[key] = convertJSONSchemaToOpenAPISchema(value, false);
272
+ return acc;
273
+ },
274
+ {}
275
+ );
276
+ }
277
+ if (items) {
278
+ result.items = Array.isArray(items) ? items.map((item) => convertJSONSchemaToOpenAPISchema(item, false)) : convertJSONSchemaToOpenAPISchema(items, false);
279
+ }
280
+ if (allOf) {
281
+ result.allOf = allOf.map(
282
+ (item) => convertJSONSchemaToOpenAPISchema(item, false)
283
+ );
284
+ }
285
+ if (anyOf) {
286
+ if (anyOf.some(
287
+ (schema) => typeof schema === "object" && (schema == null ? void 0 : schema.type) === "null"
288
+ )) {
289
+ const nonNullSchemas = anyOf.filter(
290
+ (schema) => !(typeof schema === "object" && (schema == null ? void 0 : schema.type) === "null")
291
+ );
292
+ if (nonNullSchemas.length === 1) {
293
+ const converted = convertJSONSchemaToOpenAPISchema(
294
+ nonNullSchemas[0],
295
+ false
296
+ );
297
+ if (typeof converted === "object") {
298
+ result.nullable = true;
299
+ Object.assign(result, converted);
300
+ }
301
+ } else {
302
+ result.anyOf = nonNullSchemas.map(
303
+ (item) => convertJSONSchemaToOpenAPISchema(item, false)
304
+ );
305
+ result.nullable = true;
306
+ }
307
+ } else {
308
+ result.anyOf = anyOf.map(
309
+ (item) => convertJSONSchemaToOpenAPISchema(item, false)
310
+ );
311
+ }
312
+ }
313
+ if (oneOf) {
314
+ result.oneOf = oneOf.map(
315
+ (item) => convertJSONSchemaToOpenAPISchema(item, false)
316
+ );
317
+ }
318
+ if (minLength !== void 0) {
319
+ result.minLength = minLength;
320
+ }
321
+ return result;
322
+ }
323
+ function isEmptyObjectSchema(jsonSchema) {
324
+ return jsonSchema != null && typeof jsonSchema === "object" && jsonSchema.type === "object" && (jsonSchema.properties == null || Object.keys(jsonSchema.properties).length === 0) && !jsonSchema.additionalProperties;
325
+ }
326
+
327
+ // src/convert-to-google-generative-ai-messages.ts
328
+ import {
329
+ UnsupportedFunctionalityError as UnsupportedFunctionalityError2
330
+ } from "@ai-sdk/provider";
331
+ import { convertToBase64 } from "@ai-sdk/provider-utils";
332
+
333
+ // src/google-prepare-tools.ts
334
+ import {
335
+ UnsupportedFunctionalityError
336
+ } from "@ai-sdk/provider";
337
+ function isClaudeModel(modelId) {
338
+ return modelId.toLowerCase().startsWith("claude-");
339
+ }
340
+ function prepareTools({
341
+ tools,
342
+ toolChoice,
343
+ modelId
344
+ }) {
345
+ var _a;
346
+ tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
347
+ const toolWarnings = [];
348
+ const isLatest = [
349
+ "gemini-flash-latest",
350
+ "gemini-flash-lite-latest",
351
+ "gemini-pro-latest"
352
+ ].some((id) => id === modelId);
353
+ const isGemini2orNewer = modelId.includes("gemini-2") || modelId.includes("gemini-3") || isLatest;
354
+ const supportsDynamicRetrieval = modelId.includes("gemini-1.5-flash") && !modelId.includes("-8b");
355
+ const supportsFileSearch = modelId.includes("gemini-2.5");
356
+ if (tools == null) {
357
+ return { tools: void 0, toolConfig: void 0, toolWarnings };
358
+ }
359
+ const hasFunctionTools = tools.some((tool) => tool.type === "function");
360
+ const hasProviderDefinedTools = tools.some(
361
+ (tool) => tool.type === "provider-defined"
362
+ );
363
+ if (hasFunctionTools && hasProviderDefinedTools) {
364
+ const functionTools = tools.filter((tool) => tool.type === "function");
365
+ toolWarnings.push({
366
+ type: "unsupported-tool",
367
+ tool: tools.find((tool) => tool.type === "function"),
368
+ details: `Cannot mix function tools with provider-defined tools in the same request. Falling back to provider-defined tools only. The following function tools will be ignored: ${functionTools.map((t) => t.name).join(", ")}. Please use either function tools or provider-defined tools, but not both.`
369
+ });
370
+ }
371
+ if (hasProviderDefinedTools) {
372
+ const googleTools2 = [];
373
+ const providerDefinedTools = tools.filter(
374
+ (tool) => tool.type === "provider-defined"
375
+ );
376
+ providerDefinedTools.forEach((tool) => {
377
+ switch (tool.id) {
378
+ case "google.google_search":
379
+ if (isGemini2orNewer) {
380
+ googleTools2.push({ googleSearch: {} });
381
+ } else if (supportsDynamicRetrieval) {
382
+ googleTools2.push({
383
+ googleSearchRetrieval: {
384
+ dynamicRetrievalConfig: {
385
+ mode: tool.args.mode,
386
+ dynamicThreshold: tool.args.dynamicThreshold
387
+ }
388
+ }
389
+ });
390
+ } else {
391
+ googleTools2.push({ googleSearchRetrieval: {} });
392
+ }
393
+ break;
394
+ case "google.enterprise_web_search":
395
+ if (isGemini2orNewer) {
396
+ googleTools2.push({ enterpriseWebSearch: {} });
397
+ } else {
398
+ toolWarnings.push({
399
+ type: "unsupported-tool",
400
+ tool,
401
+ details: "Enterprise Web Search requires Gemini 2.0 or newer."
402
+ });
403
+ }
404
+ break;
405
+ case "google.url_context":
406
+ if (isGemini2orNewer) {
407
+ googleTools2.push({ urlContext: {} });
408
+ } else {
409
+ toolWarnings.push({
410
+ type: "unsupported-tool",
411
+ tool,
412
+ details: "The URL context tool is not supported with other Gemini models than Gemini 2."
413
+ });
414
+ }
415
+ break;
416
+ case "google.code_execution":
417
+ if (isGemini2orNewer) {
418
+ googleTools2.push({ codeExecution: {} });
419
+ } else {
420
+ toolWarnings.push({
421
+ type: "unsupported-tool",
422
+ tool,
423
+ details: "The code execution tools is not supported with other Gemini models than Gemini 2."
424
+ });
425
+ }
426
+ break;
427
+ case "google.file_search":
428
+ if (supportsFileSearch) {
429
+ googleTools2.push({ fileSearch: { ...tool.args } });
430
+ } else {
431
+ toolWarnings.push({
432
+ type: "unsupported-tool",
433
+ tool,
434
+ details: "The file search tool is only supported with Gemini 2.5 models."
435
+ });
436
+ }
437
+ break;
438
+ case "google.vertex_rag_store":
439
+ if (isGemini2orNewer) {
440
+ googleTools2.push({
441
+ retrieval: {
442
+ vertex_rag_store: {
443
+ rag_resources: {
444
+ rag_corpus: tool.args.ragCorpus
445
+ },
446
+ similarity_top_k: tool.args.topK
447
+ }
448
+ }
449
+ });
450
+ } else {
451
+ toolWarnings.push({
452
+ type: "unsupported-tool",
453
+ tool,
454
+ details: "The RAG store tool is not supported with other Gemini models than Gemini 2."
455
+ });
456
+ }
457
+ break;
458
+ case "google.google_maps":
459
+ if (isGemini2orNewer) {
460
+ googleTools2.push({ googleMaps: {} });
461
+ } else {
462
+ toolWarnings.push({
463
+ type: "unsupported-tool",
464
+ tool,
465
+ details: "The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."
466
+ });
467
+ }
468
+ break;
469
+ default:
470
+ toolWarnings.push({ type: "unsupported-tool", tool });
471
+ break;
472
+ }
473
+ });
474
+ return {
475
+ tools: googleTools2.length > 0 ? googleTools2 : void 0,
476
+ toolConfig: void 0,
477
+ toolWarnings
478
+ };
479
+ }
480
+ const functionDeclarations = [];
481
+ for (const tool of tools) {
482
+ switch (tool.type) {
483
+ case "function": {
484
+ let parameters = convertJSONSchemaToOpenAPISchema(tool.inputSchema);
485
+ if (isClaudeModel(modelId) && !parameters) {
486
+ parameters = { type: "object", properties: {} };
487
+ }
488
+ functionDeclarations.push({
489
+ name: tool.name,
490
+ description: (_a = tool.description) != null ? _a : "",
491
+ parameters
492
+ });
493
+ break;
494
+ }
495
+ default:
496
+ toolWarnings.push({ type: "unsupported-tool", tool });
497
+ break;
498
+ }
499
+ }
500
+ if (toolChoice == null) {
501
+ return {
502
+ tools: [{ functionDeclarations }],
503
+ toolConfig: void 0,
504
+ toolWarnings
505
+ };
506
+ }
507
+ const type = toolChoice.type;
508
+ switch (type) {
509
+ case "auto":
510
+ return {
511
+ tools: [{ functionDeclarations }],
512
+ toolConfig: { functionCallingConfig: { mode: "AUTO" } },
513
+ toolWarnings
514
+ };
515
+ case "none":
516
+ return {
517
+ tools: [{ functionDeclarations }],
518
+ toolConfig: { functionCallingConfig: { mode: "NONE" } },
519
+ toolWarnings
520
+ };
521
+ case "required":
522
+ return {
523
+ tools: [{ functionDeclarations }],
524
+ toolConfig: { functionCallingConfig: { mode: "ANY" } },
525
+ toolWarnings
526
+ };
527
+ case "tool":
528
+ return {
529
+ tools: [{ functionDeclarations }],
530
+ toolConfig: {
531
+ functionCallingConfig: {
532
+ mode: "ANY",
533
+ allowedFunctionNames: [toolChoice.toolName]
534
+ }
535
+ },
536
+ toolWarnings
537
+ };
538
+ default: {
539
+ const _exhaustiveCheck = type;
540
+ throw new UnsupportedFunctionalityError({
541
+ functionality: `tool choice type: ${_exhaustiveCheck}`
542
+ });
543
+ }
544
+ }
545
+ }
546
+
547
+ // src/convert-to-google-generative-ai-messages.ts
548
+ function convertToGoogleGenerativeAIMessages(prompt, options) {
549
+ var _a, _b;
550
+ const systemInstructionParts = [];
551
+ const contents = [];
552
+ let systemMessagesAllowed = true;
553
+ const isGemmaModel = (_a = options == null ? void 0 : options.isGemmaModel) != null ? _a : false;
554
+ const modelId = (_b = options == null ? void 0 : options.modelId) != null ? _b : "";
555
+ const includeToolCallId = isClaudeModel(modelId);
556
+ for (const { role, content } of prompt) {
557
+ switch (role) {
558
+ case "system": {
559
+ if (!systemMessagesAllowed) {
560
+ throw new UnsupportedFunctionalityError2({
561
+ functionality: "system messages are only supported at the beginning of the conversation"
562
+ });
563
+ }
564
+ systemInstructionParts.push({ text: content });
565
+ break;
566
+ }
567
+ case "user": {
568
+ systemMessagesAllowed = false;
569
+ const parts = [];
570
+ for (const part of content) {
571
+ switch (part.type) {
572
+ case "text": {
573
+ parts.push({ text: part.text });
574
+ break;
575
+ }
576
+ case "file": {
577
+ const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
578
+ parts.push(
579
+ part.data instanceof URL ? {
580
+ fileData: {
581
+ mimeType: mediaType,
582
+ fileUri: part.data.toString()
583
+ }
584
+ } : {
585
+ inlineData: {
586
+ mimeType: mediaType,
587
+ data: convertToBase64(part.data)
588
+ }
589
+ }
590
+ );
591
+ break;
592
+ }
593
+ }
594
+ }
595
+ contents.push({ role: "user", parts });
596
+ break;
597
+ }
598
+ case "assistant": {
599
+ systemMessagesAllowed = false;
600
+ contents.push({
601
+ role: "model",
602
+ parts: content.map((part) => {
603
+ var _a2, _b2, _c;
604
+ const thoughtSignature = ((_b2 = (_a2 = part.providerOptions) == null ? void 0 : _a2.google) == null ? void 0 : _b2.thoughtSignature) != null ? String((_c = part.providerOptions.google) == null ? void 0 : _c.thoughtSignature) : void 0;
605
+ switch (part.type) {
606
+ case "text": {
607
+ return part.text.length === 0 ? void 0 : {
608
+ text: part.text,
609
+ thoughtSignature
610
+ };
611
+ }
612
+ case "reasoning": {
613
+ return part.text.length === 0 ? void 0 : {
614
+ text: part.text,
615
+ thought: true,
616
+ thoughtSignature
617
+ };
618
+ }
619
+ case "file": {
620
+ if (part.mediaType !== "image/png") {
621
+ throw new UnsupportedFunctionalityError2({
622
+ functionality: "Only PNG images are supported in assistant messages"
623
+ });
624
+ }
625
+ if (part.data instanceof URL) {
626
+ throw new UnsupportedFunctionalityError2({
627
+ functionality: "File data URLs in assistant messages are not supported"
628
+ });
629
+ }
630
+ return {
631
+ inlineData: {
632
+ mimeType: part.mediaType,
633
+ data: convertToBase64(part.data)
634
+ }
635
+ };
636
+ }
637
+ case "tool-call": {
638
+ return {
639
+ functionCall: {
640
+ name: part.toolName,
641
+ args: part.input,
642
+ ...includeToolCallId && part.toolCallId ? { id: part.toolCallId } : {}
643
+ },
644
+ thoughtSignature
645
+ };
646
+ }
647
+ }
648
+ }).filter((part) => part !== void 0)
649
+ });
650
+ break;
651
+ }
652
+ case "tool": {
653
+ systemMessagesAllowed = false;
654
+ const parts = [];
655
+ for (const part of content) {
656
+ const output = part.output;
657
+ if (output.type === "content") {
658
+ for (const contentPart of output.value) {
659
+ switch (contentPart.type) {
660
+ case "text":
661
+ parts.push({
662
+ functionResponse: {
663
+ name: part.toolName,
664
+ response: {
665
+ name: part.toolName,
666
+ content: contentPart.text
667
+ },
668
+ ...includeToolCallId && part.toolCallId ? { id: part.toolCallId } : {}
669
+ }
670
+ });
671
+ break;
672
+ case "media":
673
+ parts.push(
674
+ {
675
+ inlineData: {
676
+ mimeType: contentPart.mediaType,
677
+ data: contentPart.data
678
+ }
679
+ },
680
+ {
681
+ text: "Tool executed successfully and returned this image as a response"
682
+ }
683
+ );
684
+ break;
685
+ default:
686
+ parts.push({ text: JSON.stringify(contentPart) });
687
+ break;
688
+ }
689
+ }
690
+ } else {
691
+ parts.push({
692
+ functionResponse: {
693
+ name: part.toolName,
694
+ response: {
695
+ name: part.toolName,
696
+ content: output.value
697
+ },
698
+ ...includeToolCallId && part.toolCallId ? { id: part.toolCallId } : {}
699
+ }
700
+ });
701
+ }
702
+ }
703
+ contents.push({
704
+ role: "user",
705
+ parts
706
+ });
707
+ break;
708
+ }
709
+ }
710
+ }
711
+ if (isGemmaModel && systemInstructionParts.length > 0 && contents.length > 0 && contents[0].role === "user") {
712
+ const systemText = systemInstructionParts.map((part) => part.text).join("\n\n");
713
+ contents[0].parts.unshift({ text: systemText + "\n\n" });
714
+ }
715
+ return {
716
+ systemInstruction: systemInstructionParts.length > 0 && !isGemmaModel ? { parts: systemInstructionParts } : void 0,
717
+ contents
718
+ };
719
+ }
720
+
721
+ // src/google-generative-ai-options.ts
722
+ import {
723
+ lazySchema as lazySchema4,
724
+ zodSchema as zodSchema4
725
+ } from "@ai-sdk/provider-utils";
726
+ import { z as z4 } from "zod/v4";
727
+ var googleGenerativeAIProviderOptions = lazySchema4(
728
+ () => zodSchema4(
729
+ z4.object({
730
+ responseModalities: z4.array(z4.enum(["TEXT", "IMAGE"])).optional(),
731
+ thinkingConfig: z4.object({
732
+ thinkingBudget: z4.number().optional(),
733
+ includeThoughts: z4.boolean().optional(),
734
+ // https://ai.google.dev/gemini-api/docs/gemini-3?thinking=high#thinking_level
735
+ thinkingLevel: z4.enum(["minimal", "low", "medium", "high"]).optional()
736
+ }).optional(),
737
+ /**
738
+ * Optional.
739
+ * The name of the cached content used as context to serve the prediction.
740
+ * Format: cachedContents/{cachedContent}
741
+ */
742
+ cachedContent: z4.string().optional(),
743
+ /**
744
+ * Optional. Enable structured output. Default is true.
745
+ *
746
+ * This is useful when the JSON Schema contains elements that are
747
+ * not supported by the OpenAPI schema version that
748
+ * Google Generative AI uses. You can use this to disable
749
+ * structured outputs if you need to.
750
+ */
751
+ structuredOutputs: z4.boolean().optional(),
752
+ /**
753
+ * Optional. A list of unique safety settings for blocking unsafe content.
754
+ */
755
+ safetySettings: z4.array(
756
+ z4.object({
757
+ category: z4.enum([
758
+ "HARM_CATEGORY_UNSPECIFIED",
759
+ "HARM_CATEGORY_HATE_SPEECH",
760
+ "HARM_CATEGORY_DANGEROUS_CONTENT",
761
+ "HARM_CATEGORY_HARASSMENT",
762
+ "HARM_CATEGORY_SEXUALLY_EXPLICIT",
763
+ "HARM_CATEGORY_CIVIC_INTEGRITY"
764
+ ]),
765
+ threshold: z4.enum([
766
+ "HARM_BLOCK_THRESHOLD_UNSPECIFIED",
767
+ "BLOCK_LOW_AND_ABOVE",
768
+ "BLOCK_MEDIUM_AND_ABOVE",
769
+ "BLOCK_ONLY_HIGH",
770
+ "BLOCK_NONE",
771
+ "OFF"
772
+ ])
773
+ })
774
+ ).optional(),
775
+ threshold: z4.enum([
776
+ "HARM_BLOCK_THRESHOLD_UNSPECIFIED",
777
+ "BLOCK_LOW_AND_ABOVE",
778
+ "BLOCK_MEDIUM_AND_ABOVE",
779
+ "BLOCK_ONLY_HIGH",
780
+ "BLOCK_NONE",
781
+ "OFF"
782
+ ]).optional(),
783
+ /**
784
+ * Optional. Enables timestamp understanding for audio-only files.
785
+ *
786
+ * https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/audio-understanding
787
+ */
788
+ audioTimestamp: z4.boolean().optional(),
789
+ /**
790
+ * Optional. Defines labels used in billing reports. Available on Vertex AI only.
791
+ *
792
+ * https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/add-labels-to-api-calls
793
+ */
794
+ labels: z4.record(z4.string(), z4.string()).optional(),
795
+ /**
796
+ * Optional. If specified, the media resolution specified will be used.
797
+ *
798
+ * https://ai.google.dev/api/generate-content#MediaResolution
799
+ */
800
+ mediaResolution: z4.enum([
801
+ "MEDIA_RESOLUTION_UNSPECIFIED",
802
+ "MEDIA_RESOLUTION_LOW",
803
+ "MEDIA_RESOLUTION_MEDIUM",
804
+ "MEDIA_RESOLUTION_HIGH"
805
+ ]).optional(),
806
+ /**
807
+ * Optional. Configures the image generation aspect ratio for Gemini models.
808
+ *
809
+ * https://ai.google.dev/gemini-api/docs/image-generation#aspect_ratios
810
+ */
811
+ imageConfig: z4.object({
812
+ aspectRatio: z4.enum([
813
+ "1:1",
814
+ "2:3",
815
+ "3:2",
816
+ "3:4",
817
+ "4:3",
818
+ "4:5",
819
+ "5:4",
820
+ "9:16",
821
+ "16:9",
822
+ "21:9"
823
+ ]).optional(),
824
+ imageSize: z4.enum(["1K", "2K", "4K"]).optional()
825
+ }).optional(),
826
+ /**
827
+ * Optional. Configuration for grounding retrieval.
828
+ * Used to provide location context for Google Maps and Google Search grounding.
829
+ *
830
+ * https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-with-google-maps
831
+ */
832
+ retrievalConfig: z4.object({
833
+ latLng: z4.object({
834
+ latitude: z4.number(),
835
+ longitude: z4.number()
836
+ }).optional()
837
+ }).optional(),
838
+ // Cloud Assist specific options
839
+ /**
840
+ * Required for Cloud Assist. The Google Cloud project ID.
841
+ */
842
+ projectId: z4.string().optional(),
843
+ /**
844
+ * Optional. Session ID for conversation continuity.
845
+ */
846
+ sessionId: z4.string().optional(),
847
+ /**
848
+ * Optional. Request type (e.g., "agent").
849
+ */
850
+ requestType: z4.string().optional(),
851
+ /**
852
+ * Required for Cloud Assist. User agent identifier.
853
+ */
854
+ userAgent: z4.string().optional(),
855
+ /**
856
+ * Optional. Custom request ID. If not provided, one will be generated.
857
+ */
858
+ requestId: z4.string().optional()
859
+ })
860
+ )
861
+ );
862
+
863
+ // src/map-google-generative-ai-finish-reason.ts
864
+ function mapGoogleGenerativeAIFinishReason({
865
+ finishReason,
866
+ hasToolCalls
867
+ }) {
868
+ switch (finishReason) {
869
+ case "STOP":
870
+ return hasToolCalls ? "tool-calls" : "stop";
871
+ case "MAX_TOKENS":
872
+ return "length";
873
+ case "IMAGE_SAFETY":
874
+ case "RECITATION":
875
+ case "SAFETY":
876
+ case "BLOCKLIST":
877
+ case "PROHIBITED_CONTENT":
878
+ case "SPII":
879
+ return "content-filter";
880
+ case "FINISH_REASON_UNSPECIFIED":
881
+ case "OTHER":
882
+ return "other";
883
+ case "MALFORMED_FUNCTION_CALL":
884
+ return "error";
885
+ default:
886
+ return "unknown";
887
+ }
888
+ }
889
+
890
+ // src/google-generative-ai-language-model.ts
891
+ var GoogleGenerativeAILanguageModel = class {
892
+ constructor(modelId, config) {
893
+ this.specificationVersion = "v2";
894
+ var _a;
895
+ this.modelId = modelId;
896
+ this.config = config;
897
+ this.generateId = (_a = config.generateId) != null ? _a : generateId;
898
+ }
899
+ get provider() {
900
+ return this.config.provider;
901
+ }
902
+ get supportedUrls() {
903
+ var _a, _b, _c;
904
+ return (_c = (_b = (_a = this.config).supportedUrls) == null ? void 0 : _b.call(_a)) != null ? _c : {};
905
+ }
906
+ async getArgs({
907
+ prompt,
908
+ maxOutputTokens,
909
+ temperature,
910
+ topP,
911
+ topK,
912
+ frequencyPenalty,
913
+ presencePenalty,
914
+ stopSequences,
915
+ responseFormat,
916
+ seed,
917
+ tools,
918
+ toolChoice,
919
+ providerOptions
920
+ }) {
921
+ var _a;
922
+ const warnings = [];
923
+ const googleOptions = await parseProviderOptions2({
924
+ provider: "google",
925
+ providerOptions,
926
+ schema: googleGenerativeAIProviderOptions
927
+ });
928
+ if ((tools == null ? void 0 : tools.some(
929
+ (tool) => tool.type === "provider-defined" && tool.id === "google.vertex_rag_store"
930
+ )) && !this.config.provider.startsWith("google.vertex.")) {
931
+ warnings.push({
932
+ type: "other",
933
+ message: `The 'vertex_rag_store' tool 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}).`
934
+ });
935
+ }
936
+ const isGemmaModel = this.modelId.toLowerCase().startsWith("gemma-");
937
+ const { contents, systemInstruction } = convertToGoogleGenerativeAIMessages(
938
+ prompt,
939
+ { isGemmaModel, modelId: this.modelId }
940
+ );
941
+ const {
942
+ tools: googleTools2,
943
+ toolConfig: googleToolConfig,
944
+ toolWarnings
945
+ } = prepareTools({
946
+ tools,
947
+ toolChoice,
948
+ modelId: this.modelId
949
+ });
950
+ return {
951
+ args: {
952
+ generationConfig: {
953
+ // standardized settings:
954
+ maxOutputTokens,
955
+ temperature,
956
+ topK,
957
+ topP,
958
+ frequencyPenalty,
959
+ presencePenalty,
960
+ stopSequences,
961
+ seed,
962
+ // response format:
963
+ responseMimeType: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? "application/json" : void 0,
964
+ responseSchema: (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && // Google GenAI does not support all OpenAPI Schema features,
965
+ // so this is needed as an escape hatch:
966
+ // TODO convert into provider option
967
+ ((_a = googleOptions == null ? void 0 : googleOptions.structuredOutputs) != null ? _a : true) ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : void 0,
968
+ ...(googleOptions == null ? void 0 : googleOptions.audioTimestamp) && {
969
+ audioTimestamp: googleOptions.audioTimestamp
970
+ },
971
+ // provider options:
972
+ responseModalities: googleOptions == null ? void 0 : googleOptions.responseModalities,
973
+ thinkingConfig: googleOptions == null ? void 0 : googleOptions.thinkingConfig,
974
+ ...(googleOptions == null ? void 0 : googleOptions.imageConfig) && {
975
+ imageConfig: googleOptions.imageConfig
976
+ },
977
+ ...(googleOptions == null ? void 0 : googleOptions.mediaResolution) && {
978
+ mediaResolution: googleOptions.mediaResolution
979
+ }
980
+ },
981
+ contents,
982
+ systemInstruction: isGemmaModel ? void 0 : systemInstruction,
983
+ safetySettings: googleOptions == null ? void 0 : googleOptions.safetySettings,
984
+ tools: googleTools2,
985
+ toolConfig: (googleOptions == null ? void 0 : googleOptions.retrievalConfig) ? {
986
+ ...googleToolConfig,
987
+ retrievalConfig: googleOptions.retrievalConfig
988
+ } : googleToolConfig,
989
+ cachedContent: googleOptions == null ? void 0 : googleOptions.cachedContent,
990
+ labels: googleOptions == null ? void 0 : googleOptions.labels,
991
+ // Cloud Assist: sessionId goes inside the request
992
+ ...(googleOptions == null ? void 0 : googleOptions.sessionId) && { sessionId: googleOptions.sessionId }
993
+ },
994
+ warnings: [...warnings, ...toolWarnings],
995
+ // Cloud Assist specific options (used to wrap the request)
996
+ cloudAssistOptions: {
997
+ projectId: googleOptions == null ? void 0 : googleOptions.projectId,
998
+ requestType: googleOptions == null ? void 0 : googleOptions.requestType,
999
+ userAgent: googleOptions == null ? void 0 : googleOptions.userAgent,
1000
+ requestId: googleOptions == null ? void 0 : googleOptions.requestId
1001
+ }
1002
+ };
1003
+ }
1004
+ async doGenerate(options) {
1005
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
1006
+ const { args, warnings, cloudAssistOptions } = await this.getArgs(options);
1007
+ const wrappedRequest = {
1008
+ project: cloudAssistOptions.projectId,
1009
+ model: this.modelId,
1010
+ request: args,
1011
+ ...cloudAssistOptions.requestType && {
1012
+ requestType: cloudAssistOptions.requestType
1013
+ },
1014
+ userAgent: (_a = cloudAssistOptions.userAgent) != null ? _a : "ai-sdk",
1015
+ requestId: (_b = cloudAssistOptions.requestId) != null ? _b : `ai-sdk-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`
1016
+ };
1017
+ const body = JSON.stringify(wrappedRequest);
1018
+ const mergedHeaders = combineHeaders2(
1019
+ await resolve2(this.config.headers),
1020
+ options.headers
1021
+ );
1022
+ const { responseHeaders, value: response } = await postJsonToApi2({
1023
+ url: `${this.config.baseURL}/v1internal:streamGenerateContent?alt=sse`,
1024
+ headers: mergedHeaders,
1025
+ body: wrappedRequest,
1026
+ failedResponseHandler: googleFailedResponseHandler,
1027
+ successfulResponseHandler: createEventSourceResponseHandler(chunkSchema),
1028
+ abortSignal: options.abortSignal,
1029
+ fetch: this.config.fetch
1030
+ });
1031
+ const content = [];
1032
+ let finishReason = "unknown";
1033
+ let usageMetadata;
1034
+ let promptFeedback;
1035
+ let groundingMetadata;
1036
+ let urlContextMetadata;
1037
+ let safetyRatings;
1038
+ let currentTextContent = "";
1039
+ let currentTextThoughtSignature;
1040
+ let currentReasoningContent = "";
1041
+ let currentReasoningThoughtSignature;
1042
+ let isInReasoning = false;
1043
+ let lastCodeExecutionToolCallId;
1044
+ const useToolCallId = isClaudeModel(this.modelId);
1045
+ const reader = response.getReader();
1046
+ try {
1047
+ while (true) {
1048
+ const { done, value: chunk } = await reader.read();
1049
+ if (done) break;
1050
+ if (!chunk.success) continue;
1051
+ const value = chunk.value;
1052
+ const responseData = (_c = value.response) != null ? _c : value;
1053
+ if (responseData.usageMetadata) {
1054
+ usageMetadata = responseData.usageMetadata;
1055
+ }
1056
+ if (responseData.promptFeedback) {
1057
+ promptFeedback = responseData.promptFeedback;
1058
+ }
1059
+ const candidate = (_d = responseData.candidates) == null ? void 0 : _d[0];
1060
+ if (!candidate) continue;
1061
+ if (candidate.groundingMetadata) {
1062
+ groundingMetadata = candidate.groundingMetadata;
1063
+ }
1064
+ if (candidate.urlContextMetadata) {
1065
+ urlContextMetadata = candidate.urlContextMetadata;
1066
+ }
1067
+ if (candidate.safetyRatings) {
1068
+ safetyRatings = candidate.safetyRatings;
1069
+ }
1070
+ const parts = (_f = (_e = candidate.content) == null ? void 0 : _e.parts) != null ? _f : [];
1071
+ for (const part of parts) {
1072
+ if ("executableCode" in part && ((_g = part.executableCode) == null ? void 0 : _g.code)) {
1073
+ if (currentTextContent) {
1074
+ content.push({
1075
+ type: "text",
1076
+ text: currentTextContent,
1077
+ providerMetadata: currentTextThoughtSignature ? { google: { thoughtSignature: currentTextThoughtSignature } } : void 0
1078
+ });
1079
+ currentTextContent = "";
1080
+ currentTextThoughtSignature = void 0;
1081
+ }
1082
+ if (currentReasoningContent) {
1083
+ content.push({
1084
+ type: "reasoning",
1085
+ text: currentReasoningContent,
1086
+ providerMetadata: currentReasoningThoughtSignature ? {
1087
+ google: {
1088
+ thoughtSignature: currentReasoningThoughtSignature
1089
+ }
1090
+ } : void 0
1091
+ });
1092
+ currentReasoningContent = "";
1093
+ currentReasoningThoughtSignature = void 0;
1094
+ }
1095
+ const toolCallId = this.config.generateId();
1096
+ lastCodeExecutionToolCallId = toolCallId;
1097
+ content.push({
1098
+ type: "tool-call",
1099
+ toolCallId,
1100
+ toolName: "code_execution",
1101
+ input: JSON.stringify(part.executableCode),
1102
+ providerExecuted: true
1103
+ });
1104
+ } else if ("codeExecutionResult" in part && part.codeExecutionResult) {
1105
+ content.push({
1106
+ type: "tool-result",
1107
+ toolCallId: lastCodeExecutionToolCallId,
1108
+ toolName: "code_execution",
1109
+ result: {
1110
+ outcome: part.codeExecutionResult.outcome,
1111
+ output: part.codeExecutionResult.output
1112
+ },
1113
+ providerExecuted: true
1114
+ });
1115
+ lastCodeExecutionToolCallId = void 0;
1116
+ } else if ("text" in part && part.text != null) {
1117
+ const isThinking = part.thought === true;
1118
+ if (isThinking) {
1119
+ if (!isInReasoning && currentTextContent) {
1120
+ content.push({
1121
+ type: "text",
1122
+ text: currentTextContent,
1123
+ providerMetadata: currentTextThoughtSignature ? {
1124
+ google: {
1125
+ thoughtSignature: currentTextThoughtSignature
1126
+ }
1127
+ } : void 0
1128
+ });
1129
+ currentTextContent = "";
1130
+ currentTextThoughtSignature = void 0;
1131
+ }
1132
+ isInReasoning = true;
1133
+ currentReasoningContent += part.text;
1134
+ if (part.thoughtSignature) {
1135
+ currentReasoningThoughtSignature = part.thoughtSignature;
1136
+ }
1137
+ } else {
1138
+ if (isInReasoning && currentReasoningContent) {
1139
+ content.push({
1140
+ type: "reasoning",
1141
+ text: currentReasoningContent,
1142
+ providerMetadata: currentReasoningThoughtSignature ? {
1143
+ google: {
1144
+ thoughtSignature: currentReasoningThoughtSignature
1145
+ }
1146
+ } : void 0
1147
+ });
1148
+ currentReasoningContent = "";
1149
+ currentReasoningThoughtSignature = void 0;
1150
+ }
1151
+ isInReasoning = false;
1152
+ currentTextContent += part.text;
1153
+ if (part.thoughtSignature) {
1154
+ currentTextThoughtSignature = part.thoughtSignature;
1155
+ }
1156
+ }
1157
+ } else if ("functionCall" in part) {
1158
+ if (currentTextContent) {
1159
+ content.push({
1160
+ type: "text",
1161
+ text: currentTextContent,
1162
+ providerMetadata: currentTextThoughtSignature ? { google: { thoughtSignature: currentTextThoughtSignature } } : void 0
1163
+ });
1164
+ currentTextContent = "";
1165
+ currentTextThoughtSignature = void 0;
1166
+ }
1167
+ if (currentReasoningContent) {
1168
+ content.push({
1169
+ type: "reasoning",
1170
+ text: currentReasoningContent,
1171
+ providerMetadata: currentReasoningThoughtSignature ? {
1172
+ google: {
1173
+ thoughtSignature: currentReasoningThoughtSignature
1174
+ }
1175
+ } : void 0
1176
+ });
1177
+ currentReasoningContent = "";
1178
+ currentReasoningThoughtSignature = void 0;
1179
+ }
1180
+ const toolCallId = useToolCallId && part.functionCall.id ? part.functionCall.id : this.config.generateId();
1181
+ content.push({
1182
+ type: "tool-call",
1183
+ toolCallId,
1184
+ toolName: part.functionCall.name,
1185
+ input: JSON.stringify(part.functionCall.args),
1186
+ providerMetadata: part.thoughtSignature ? { google: { thoughtSignature: part.thoughtSignature } } : void 0
1187
+ });
1188
+ } else if ("inlineData" in part) {
1189
+ if (currentTextContent) {
1190
+ content.push({
1191
+ type: "text",
1192
+ text: currentTextContent,
1193
+ providerMetadata: currentTextThoughtSignature ? { google: { thoughtSignature: currentTextThoughtSignature } } : void 0
1194
+ });
1195
+ currentTextContent = "";
1196
+ currentTextThoughtSignature = void 0;
1197
+ }
1198
+ if (currentReasoningContent) {
1199
+ content.push({
1200
+ type: "reasoning",
1201
+ text: currentReasoningContent,
1202
+ providerMetadata: currentReasoningThoughtSignature ? {
1203
+ google: {
1204
+ thoughtSignature: currentReasoningThoughtSignature
1205
+ }
1206
+ } : void 0
1207
+ });
1208
+ currentReasoningContent = "";
1209
+ currentReasoningThoughtSignature = void 0;
1210
+ }
1211
+ content.push({
1212
+ type: "file",
1213
+ data: part.inlineData.data,
1214
+ mediaType: part.inlineData.mimeType
1215
+ });
1216
+ }
1217
+ }
1218
+ if (candidate.finishReason) {
1219
+ finishReason = mapGoogleGenerativeAIFinishReason({
1220
+ finishReason: candidate.finishReason,
1221
+ hasToolCalls: content.some((part) => part.type === "tool-call")
1222
+ });
1223
+ }
1224
+ }
1225
+ } finally {
1226
+ reader.releaseLock();
1227
+ }
1228
+ if (currentTextContent) {
1229
+ content.push({
1230
+ type: "text",
1231
+ text: currentTextContent,
1232
+ providerMetadata: currentTextThoughtSignature ? { google: { thoughtSignature: currentTextThoughtSignature } } : void 0
1233
+ });
1234
+ }
1235
+ if (currentReasoningContent) {
1236
+ content.push({
1237
+ type: "reasoning",
1238
+ text: currentReasoningContent,
1239
+ providerMetadata: currentReasoningThoughtSignature ? { google: { thoughtSignature: currentReasoningThoughtSignature } } : void 0
1240
+ });
1241
+ }
1242
+ const sources = (_h = extractSources({
1243
+ groundingMetadata,
1244
+ generateId: this.config.generateId
1245
+ })) != null ? _h : [];
1246
+ for (const source of sources) {
1247
+ content.push(source);
1248
+ }
1249
+ return {
1250
+ content,
1251
+ finishReason,
1252
+ usage: {
1253
+ inputTokens: (_i = usageMetadata == null ? void 0 : usageMetadata.promptTokenCount) != null ? _i : void 0,
1254
+ outputTokens: (_j = usageMetadata == null ? void 0 : usageMetadata.candidatesTokenCount) != null ? _j : void 0,
1255
+ totalTokens: (_k = usageMetadata == null ? void 0 : usageMetadata.totalTokenCount) != null ? _k : void 0,
1256
+ reasoningTokens: (_l = usageMetadata == null ? void 0 : usageMetadata.thoughtsTokenCount) != null ? _l : void 0,
1257
+ cachedInputTokens: (_m = usageMetadata == null ? void 0 : usageMetadata.cachedContentTokenCount) != null ? _m : void 0
1258
+ },
1259
+ warnings,
1260
+ providerMetadata: {
1261
+ google: {
1262
+ promptFeedback: promptFeedback != null ? promptFeedback : null,
1263
+ groundingMetadata: groundingMetadata != null ? groundingMetadata : null,
1264
+ urlContextMetadata: urlContextMetadata != null ? urlContextMetadata : null,
1265
+ safetyRatings: safetyRatings != null ? safetyRatings : null,
1266
+ usageMetadata: usageMetadata != null ? usageMetadata : null
1267
+ }
1268
+ },
1269
+ request: { body },
1270
+ response: {
1271
+ headers: responseHeaders
1272
+ }
1273
+ };
1274
+ }
1275
+ async doStream(options) {
1276
+ var _a, _b;
1277
+ const { args, warnings, cloudAssistOptions } = await this.getArgs(options);
1278
+ const wrappedRequest = {
1279
+ project: cloudAssistOptions.projectId,
1280
+ model: this.modelId,
1281
+ request: args,
1282
+ ...cloudAssistOptions.requestType && {
1283
+ requestType: cloudAssistOptions.requestType
1284
+ },
1285
+ userAgent: (_a = cloudAssistOptions.userAgent) != null ? _a : "ai-sdk",
1286
+ requestId: (_b = cloudAssistOptions.requestId) != null ? _b : `ai-sdk-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`
1287
+ };
1288
+ const body = JSON.stringify(wrappedRequest);
1289
+ const headers = combineHeaders2(
1290
+ await resolve2(this.config.headers),
1291
+ options.headers
1292
+ );
1293
+ const { responseHeaders, value: response } = await postJsonToApi2({
1294
+ url: `${this.config.baseURL}/v1internal:streamGenerateContent?alt=sse`,
1295
+ headers,
1296
+ body: wrappedRequest,
1297
+ failedResponseHandler: googleFailedResponseHandler,
1298
+ successfulResponseHandler: createEventSourceResponseHandler(chunkSchema),
1299
+ abortSignal: options.abortSignal,
1300
+ fetch: this.config.fetch
1301
+ });
1302
+ let finishReason = "unknown";
1303
+ const usage = {
1304
+ inputTokens: void 0,
1305
+ outputTokens: void 0,
1306
+ totalTokens: void 0
1307
+ };
1308
+ let providerMetadata = void 0;
1309
+ const generateId3 = this.config.generateId;
1310
+ const useToolCallId = isClaudeModel(this.modelId);
1311
+ let hasToolCalls = false;
1312
+ let currentTextBlockId = null;
1313
+ let currentReasoningBlockId = null;
1314
+ let blockCounter = 0;
1315
+ const emittedSourceUrls = /* @__PURE__ */ new Set();
1316
+ let lastCodeExecutionToolCallId;
1317
+ return {
1318
+ stream: response.pipeThrough(
1319
+ new TransformStream({
1320
+ start(controller) {
1321
+ controller.enqueue({ type: "stream-start", warnings });
1322
+ },
1323
+ transform(chunk, controller) {
1324
+ var _a2, _b2, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
1325
+ if (options.includeRawChunks) {
1326
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
1327
+ }
1328
+ if (!chunk.success) {
1329
+ controller.enqueue({ type: "error", error: chunk.error });
1330
+ return;
1331
+ }
1332
+ const value = chunk.value;
1333
+ const responseData = (_a2 = value.response) != null ? _a2 : value;
1334
+ const usageMetadata = responseData.usageMetadata;
1335
+ if (usageMetadata != null) {
1336
+ usage.inputTokens = (_b2 = usageMetadata.promptTokenCount) != null ? _b2 : void 0;
1337
+ usage.outputTokens = (_c = usageMetadata.candidatesTokenCount) != null ? _c : void 0;
1338
+ usage.totalTokens = (_d = usageMetadata.totalTokenCount) != null ? _d : void 0;
1339
+ usage.reasoningTokens = (_e = usageMetadata.thoughtsTokenCount) != null ? _e : void 0;
1340
+ usage.cachedInputTokens = (_f = usageMetadata.cachedContentTokenCount) != null ? _f : void 0;
1341
+ }
1342
+ const candidate = (_g = responseData.candidates) == null ? void 0 : _g[0];
1343
+ if (candidate == null) {
1344
+ return;
1345
+ }
1346
+ const content = candidate.content;
1347
+ const sources = extractSources({
1348
+ groundingMetadata: candidate.groundingMetadata,
1349
+ generateId: generateId3
1350
+ });
1351
+ if (sources != null) {
1352
+ for (const source of sources) {
1353
+ if (source.sourceType === "url" && !emittedSourceUrls.has(source.url)) {
1354
+ emittedSourceUrls.add(source.url);
1355
+ controller.enqueue(source);
1356
+ }
1357
+ }
1358
+ }
1359
+ if (content != null) {
1360
+ const parts = (_h = content.parts) != null ? _h : [];
1361
+ for (const part of parts) {
1362
+ if ("executableCode" in part && ((_i = part.executableCode) == null ? void 0 : _i.code)) {
1363
+ const toolCallId = generateId3();
1364
+ lastCodeExecutionToolCallId = toolCallId;
1365
+ controller.enqueue({
1366
+ type: "tool-call",
1367
+ toolCallId,
1368
+ toolName: "code_execution",
1369
+ input: JSON.stringify(part.executableCode),
1370
+ providerExecuted: true
1371
+ });
1372
+ hasToolCalls = true;
1373
+ } else if ("codeExecutionResult" in part && part.codeExecutionResult) {
1374
+ const toolCallId = lastCodeExecutionToolCallId;
1375
+ if (toolCallId) {
1376
+ controller.enqueue({
1377
+ type: "tool-result",
1378
+ toolCallId,
1379
+ toolName: "code_execution",
1380
+ result: {
1381
+ outcome: part.codeExecutionResult.outcome,
1382
+ output: part.codeExecutionResult.output
1383
+ },
1384
+ providerExecuted: true
1385
+ });
1386
+ lastCodeExecutionToolCallId = void 0;
1387
+ }
1388
+ } else if ("text" in part && part.text != null && part.text.length > 0) {
1389
+ if (part.thought === true) {
1390
+ if (currentTextBlockId !== null) {
1391
+ controller.enqueue({
1392
+ type: "text-end",
1393
+ id: currentTextBlockId
1394
+ });
1395
+ currentTextBlockId = null;
1396
+ }
1397
+ if (currentReasoningBlockId === null) {
1398
+ currentReasoningBlockId = String(blockCounter++);
1399
+ controller.enqueue({
1400
+ type: "reasoning-start",
1401
+ id: currentReasoningBlockId,
1402
+ providerMetadata: part.thoughtSignature ? {
1403
+ google: {
1404
+ thoughtSignature: part.thoughtSignature
1405
+ }
1406
+ } : void 0
1407
+ });
1408
+ }
1409
+ controller.enqueue({
1410
+ type: "reasoning-delta",
1411
+ id: currentReasoningBlockId,
1412
+ delta: part.text,
1413
+ providerMetadata: part.thoughtSignature ? {
1414
+ google: { thoughtSignature: part.thoughtSignature }
1415
+ } : void 0
1416
+ });
1417
+ } else {
1418
+ if (currentReasoningBlockId !== null) {
1419
+ controller.enqueue({
1420
+ type: "reasoning-end",
1421
+ id: currentReasoningBlockId
1422
+ });
1423
+ currentReasoningBlockId = null;
1424
+ }
1425
+ if (currentTextBlockId === null) {
1426
+ currentTextBlockId = String(blockCounter++);
1427
+ controller.enqueue({
1428
+ type: "text-start",
1429
+ id: currentTextBlockId,
1430
+ providerMetadata: part.thoughtSignature ? {
1431
+ google: {
1432
+ thoughtSignature: part.thoughtSignature
1433
+ }
1434
+ } : void 0
1435
+ });
1436
+ }
1437
+ controller.enqueue({
1438
+ type: "text-delta",
1439
+ id: currentTextBlockId,
1440
+ delta: part.text,
1441
+ providerMetadata: part.thoughtSignature ? {
1442
+ google: { thoughtSignature: part.thoughtSignature }
1443
+ } : void 0
1444
+ });
1445
+ }
1446
+ } else if ("inlineData" in part) {
1447
+ controller.enqueue({
1448
+ type: "file",
1449
+ mediaType: part.inlineData.mimeType,
1450
+ data: part.inlineData.data
1451
+ });
1452
+ }
1453
+ }
1454
+ const toolCallDeltas = getToolCallsFromParts({
1455
+ parts: content.parts,
1456
+ generateId: generateId3,
1457
+ useToolCallId
1458
+ });
1459
+ if (toolCallDeltas != null) {
1460
+ for (const toolCall of toolCallDeltas) {
1461
+ controller.enqueue({
1462
+ type: "tool-input-start",
1463
+ id: toolCall.toolCallId,
1464
+ toolName: toolCall.toolName,
1465
+ providerMetadata: toolCall.providerMetadata
1466
+ });
1467
+ controller.enqueue({
1468
+ type: "tool-input-delta",
1469
+ id: toolCall.toolCallId,
1470
+ delta: toolCall.args,
1471
+ providerMetadata: toolCall.providerMetadata
1472
+ });
1473
+ controller.enqueue({
1474
+ type: "tool-input-end",
1475
+ id: toolCall.toolCallId,
1476
+ providerMetadata: toolCall.providerMetadata
1477
+ });
1478
+ controller.enqueue({
1479
+ type: "tool-call",
1480
+ toolCallId: toolCall.toolCallId,
1481
+ toolName: toolCall.toolName,
1482
+ input: toolCall.args,
1483
+ providerMetadata: toolCall.providerMetadata
1484
+ });
1485
+ hasToolCalls = true;
1486
+ }
1487
+ }
1488
+ }
1489
+ if (candidate.finishReason != null) {
1490
+ finishReason = mapGoogleGenerativeAIFinishReason({
1491
+ finishReason: candidate.finishReason,
1492
+ hasToolCalls
1493
+ });
1494
+ providerMetadata = {
1495
+ google: {
1496
+ promptFeedback: (_j = responseData.promptFeedback) != null ? _j : null,
1497
+ groundingMetadata: (_k = candidate.groundingMetadata) != null ? _k : null,
1498
+ urlContextMetadata: (_l = candidate.urlContextMetadata) != null ? _l : null,
1499
+ safetyRatings: (_m = candidate.safetyRatings) != null ? _m : null
1500
+ }
1501
+ };
1502
+ if (usageMetadata != null) {
1503
+ providerMetadata.google.usageMetadata = usageMetadata;
1504
+ }
1505
+ }
1506
+ },
1507
+ flush(controller) {
1508
+ if (currentTextBlockId !== null) {
1509
+ controller.enqueue({
1510
+ type: "text-end",
1511
+ id: currentTextBlockId
1512
+ });
1513
+ }
1514
+ if (currentReasoningBlockId !== null) {
1515
+ controller.enqueue({
1516
+ type: "reasoning-end",
1517
+ id: currentReasoningBlockId
1518
+ });
1519
+ }
1520
+ controller.enqueue({
1521
+ type: "finish",
1522
+ finishReason,
1523
+ usage,
1524
+ providerMetadata
1525
+ });
1526
+ }
1527
+ })
1528
+ ),
1529
+ response: { headers: responseHeaders },
1530
+ request: { body }
1531
+ };
1532
+ }
1533
+ };
1534
+ function getToolCallsFromParts({
1535
+ parts,
1536
+ generateId: generateId3,
1537
+ useToolCallId = false
1538
+ }) {
1539
+ const functionCallParts = parts == null ? void 0 : parts.filter(
1540
+ (part) => "functionCall" in part
1541
+ );
1542
+ return functionCallParts == null || functionCallParts.length === 0 ? void 0 : functionCallParts.map((part) => ({
1543
+ type: "tool-call",
1544
+ // Use provided id for Claude models, generate for others
1545
+ toolCallId: useToolCallId && part.functionCall.id ? part.functionCall.id : generateId3(),
1546
+ toolName: part.functionCall.name,
1547
+ args: JSON.stringify(part.functionCall.args),
1548
+ providerMetadata: part.thoughtSignature ? { google: { thoughtSignature: part.thoughtSignature } } : void 0
1549
+ }));
1550
+ }
1551
+ function extractSources({
1552
+ groundingMetadata,
1553
+ generateId: generateId3
1554
+ }) {
1555
+ var _a, _b, _c, _d, _e;
1556
+ if (!(groundingMetadata == null ? void 0 : groundingMetadata.groundingChunks)) {
1557
+ return void 0;
1558
+ }
1559
+ const sources = [];
1560
+ for (const chunk of groundingMetadata.groundingChunks) {
1561
+ if (chunk.web != null) {
1562
+ sources.push({
1563
+ type: "source",
1564
+ sourceType: "url",
1565
+ id: generateId3(),
1566
+ url: chunk.web.uri,
1567
+ title: (_a = chunk.web.title) != null ? _a : void 0
1568
+ });
1569
+ } else if (chunk.retrievedContext != null) {
1570
+ const uri = chunk.retrievedContext.uri;
1571
+ const fileSearchStore = chunk.retrievedContext.fileSearchStore;
1572
+ if (uri && (uri.startsWith("http://") || uri.startsWith("https://"))) {
1573
+ sources.push({
1574
+ type: "source",
1575
+ sourceType: "url",
1576
+ id: generateId3(),
1577
+ url: uri,
1578
+ title: (_b = chunk.retrievedContext.title) != null ? _b : void 0
1579
+ });
1580
+ } else if (uri) {
1581
+ const title = (_c = chunk.retrievedContext.title) != null ? _c : "Unknown Document";
1582
+ let mediaType = "application/octet-stream";
1583
+ let filename = void 0;
1584
+ if (uri.endsWith(".pdf")) {
1585
+ mediaType = "application/pdf";
1586
+ filename = uri.split("/").pop();
1587
+ } else if (uri.endsWith(".txt")) {
1588
+ mediaType = "text/plain";
1589
+ filename = uri.split("/").pop();
1590
+ } else if (uri.endsWith(".docx")) {
1591
+ mediaType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
1592
+ filename = uri.split("/").pop();
1593
+ } else if (uri.endsWith(".doc")) {
1594
+ mediaType = "application/msword";
1595
+ filename = uri.split("/").pop();
1596
+ } else if (uri.match(/\.(md|markdown)$/)) {
1597
+ mediaType = "text/markdown";
1598
+ filename = uri.split("/").pop();
1599
+ } else {
1600
+ filename = uri.split("/").pop();
1601
+ }
1602
+ sources.push({
1603
+ type: "source",
1604
+ sourceType: "document",
1605
+ id: generateId3(),
1606
+ mediaType,
1607
+ title,
1608
+ filename
1609
+ });
1610
+ } else if (fileSearchStore) {
1611
+ const title = (_d = chunk.retrievedContext.title) != null ? _d : "Unknown Document";
1612
+ sources.push({
1613
+ type: "source",
1614
+ sourceType: "document",
1615
+ id: generateId3(),
1616
+ mediaType: "application/octet-stream",
1617
+ title,
1618
+ filename: fileSearchStore.split("/").pop()
1619
+ });
1620
+ }
1621
+ } else if (chunk.maps != null) {
1622
+ if (chunk.maps.uri) {
1623
+ sources.push({
1624
+ type: "source",
1625
+ sourceType: "url",
1626
+ id: generateId3(),
1627
+ url: chunk.maps.uri,
1628
+ title: (_e = chunk.maps.title) != null ? _e : void 0
1629
+ });
1630
+ }
1631
+ }
1632
+ }
1633
+ return sources.length > 0 ? sources : void 0;
1634
+ }
1635
+ var getGroundingMetadataSchema = () => z5.object({
1636
+ webSearchQueries: z5.array(z5.string()).nullish(),
1637
+ retrievalQueries: z5.array(z5.string()).nullish(),
1638
+ searchEntryPoint: z5.object({ renderedContent: z5.string() }).nullish(),
1639
+ groundingChunks: z5.array(
1640
+ z5.object({
1641
+ web: z5.object({ uri: z5.string(), title: z5.string().nullish() }).nullish(),
1642
+ retrievedContext: z5.object({
1643
+ uri: z5.string().nullish(),
1644
+ title: z5.string().nullish(),
1645
+ text: z5.string().nullish(),
1646
+ fileSearchStore: z5.string().nullish()
1647
+ }).nullish(),
1648
+ maps: z5.object({
1649
+ uri: z5.string().nullish(),
1650
+ title: z5.string().nullish(),
1651
+ text: z5.string().nullish(),
1652
+ placeId: z5.string().nullish()
1653
+ }).nullish()
1654
+ })
1655
+ ).nullish(),
1656
+ groundingSupports: z5.array(
1657
+ z5.object({
1658
+ segment: z5.object({
1659
+ startIndex: z5.number().nullish(),
1660
+ endIndex: z5.number().nullish(),
1661
+ text: z5.string().nullish()
1662
+ }),
1663
+ segment_text: z5.string().nullish(),
1664
+ groundingChunkIndices: z5.array(z5.number()).nullish(),
1665
+ supportChunkIndices: z5.array(z5.number()).nullish(),
1666
+ confidenceScores: z5.array(z5.number()).nullish(),
1667
+ confidenceScore: z5.array(z5.number()).nullish()
1668
+ })
1669
+ ).nullish(),
1670
+ retrievalMetadata: z5.union([
1671
+ z5.object({
1672
+ webDynamicRetrievalScore: z5.number()
1673
+ }),
1674
+ z5.object({})
1675
+ ]).nullish()
1676
+ });
1677
+ var getContentSchema = () => z5.object({
1678
+ parts: z5.array(
1679
+ z5.union([
1680
+ // note: order matters since text can be fully empty
1681
+ z5.object({
1682
+ functionCall: z5.object({
1683
+ name: z5.string(),
1684
+ args: z5.unknown(),
1685
+ id: z5.string().nullish()
1686
+ // Claude models include tool call ID
1687
+ }),
1688
+ thoughtSignature: z5.string().nullish()
1689
+ }),
1690
+ z5.object({
1691
+ inlineData: z5.object({
1692
+ mimeType: z5.string(),
1693
+ data: z5.string()
1694
+ })
1695
+ }),
1696
+ z5.object({
1697
+ executableCode: z5.object({
1698
+ language: z5.string(),
1699
+ code: z5.string()
1700
+ }).nullish(),
1701
+ codeExecutionResult: z5.object({
1702
+ outcome: z5.string(),
1703
+ output: z5.string()
1704
+ }).nullish(),
1705
+ text: z5.string().nullish(),
1706
+ thought: z5.boolean().nullish(),
1707
+ thoughtSignature: z5.string().nullish()
1708
+ })
1709
+ ])
1710
+ ).nullish()
1711
+ });
1712
+ var getSafetyRatingSchema = () => z5.object({
1713
+ category: z5.string().nullish(),
1714
+ probability: z5.string().nullish(),
1715
+ probabilityScore: z5.number().nullish(),
1716
+ severity: z5.string().nullish(),
1717
+ severityScore: z5.number().nullish(),
1718
+ blocked: z5.boolean().nullish()
1719
+ });
1720
+ var usageSchema = z5.object({
1721
+ cachedContentTokenCount: z5.number().nullish(),
1722
+ thoughtsTokenCount: z5.number().nullish(),
1723
+ promptTokenCount: z5.number().nullish(),
1724
+ candidatesTokenCount: z5.number().nullish(),
1725
+ totalTokenCount: z5.number().nullish(),
1726
+ // https://cloud.google.com/vertex-ai/generative-ai/docs/reference/rest/v1/GenerateContentResponse#TrafficType
1727
+ trafficType: z5.string().nullish()
1728
+ });
1729
+ var getUrlContextMetadataSchema = () => z5.object({
1730
+ urlMetadata: z5.array(
1731
+ z5.object({
1732
+ retrievedUrl: z5.string(),
1733
+ urlRetrievalStatus: z5.string()
1734
+ })
1735
+ )
1736
+ });
1737
+ var responseSchema = lazySchema5(
1738
+ () => zodSchema5(
1739
+ z5.object({
1740
+ candidates: z5.array(
1741
+ z5.object({
1742
+ content: getContentSchema().nullish().or(z5.object({}).strict()),
1743
+ finishReason: z5.string().nullish(),
1744
+ safetyRatings: z5.array(getSafetyRatingSchema()).nullish(),
1745
+ groundingMetadata: getGroundingMetadataSchema().nullish(),
1746
+ urlContextMetadata: getUrlContextMetadataSchema().nullish()
1747
+ })
1748
+ ),
1749
+ usageMetadata: usageSchema.nullish(),
1750
+ promptFeedback: z5.object({
1751
+ blockReason: z5.string().nullish(),
1752
+ safetyRatings: z5.array(getSafetyRatingSchema()).nullish()
1753
+ }).nullish()
1754
+ })
1755
+ )
1756
+ );
1757
+ var getResponseContentSchema = () => z5.object({
1758
+ candidates: z5.array(
1759
+ z5.object({
1760
+ content: getContentSchema().nullish(),
1761
+ finishReason: z5.string().nullish(),
1762
+ safetyRatings: z5.array(getSafetyRatingSchema()).nullish(),
1763
+ groundingMetadata: getGroundingMetadataSchema().nullish(),
1764
+ urlContextMetadata: getUrlContextMetadataSchema().nullish()
1765
+ })
1766
+ ).nullish(),
1767
+ usageMetadata: usageSchema.nullish(),
1768
+ promptFeedback: z5.object({
1769
+ blockReason: z5.string().nullish(),
1770
+ safetyRatings: z5.array(getSafetyRatingSchema()).nullish()
1771
+ }).nullish(),
1772
+ modelVersion: z5.string().nullish(),
1773
+ responseId: z5.string().nullish()
1774
+ });
1775
+ var chunkSchema = lazySchema5(
1776
+ () => zodSchema5(
1777
+ z5.object({
1778
+ // Cloud Assist wrapper fields
1779
+ response: getResponseContentSchema().nullish(),
1780
+ traceId: z5.string().nullish(),
1781
+ // Also allow direct fields for compatibility
1782
+ candidates: z5.array(
1783
+ z5.object({
1784
+ content: getContentSchema().nullish(),
1785
+ finishReason: z5.string().nullish(),
1786
+ safetyRatings: z5.array(getSafetyRatingSchema()).nullish(),
1787
+ groundingMetadata: getGroundingMetadataSchema().nullish(),
1788
+ urlContextMetadata: getUrlContextMetadataSchema().nullish()
1789
+ })
1790
+ ).nullish(),
1791
+ usageMetadata: usageSchema.nullish(),
1792
+ promptFeedback: z5.object({
1793
+ blockReason: z5.string().nullish(),
1794
+ safetyRatings: z5.array(getSafetyRatingSchema()).nullish()
1795
+ }).nullish()
1796
+ })
1797
+ )
1798
+ );
1799
+
1800
+ // src/tool/code-execution.ts
1801
+ import { createProviderDefinedToolFactoryWithOutputSchema } from "@ai-sdk/provider-utils";
1802
+ import { z as z6 } from "zod/v4";
1803
+ var codeExecution = createProviderDefinedToolFactoryWithOutputSchema({
1804
+ id: "google.code_execution",
1805
+ name: "code_execution",
1806
+ inputSchema: z6.object({
1807
+ language: z6.string().describe("The programming language of the code."),
1808
+ code: z6.string().describe("The code to be executed.")
1809
+ }),
1810
+ outputSchema: z6.object({
1811
+ outcome: z6.string().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),
1812
+ output: z6.string().describe("The output from the code execution.")
1813
+ })
1814
+ });
1815
+
1816
+ // src/tool/enterprise-web-search.ts
1817
+ import {
1818
+ createProviderDefinedToolFactory,
1819
+ lazySchema as lazySchema6,
1820
+ zodSchema as zodSchema6
1821
+ } from "@ai-sdk/provider-utils";
1822
+ import { z as z7 } from "zod/v4";
1823
+ var enterpriseWebSearch = createProviderDefinedToolFactory({
1824
+ id: "google.enterprise_web_search",
1825
+ name: "enterprise_web_search",
1826
+ inputSchema: lazySchema6(() => zodSchema6(z7.object({})))
1827
+ });
1828
+
1829
+ // src/tool/file-search.ts
1830
+ import {
1831
+ createProviderDefinedToolFactory as createProviderDefinedToolFactory2,
1832
+ lazySchema as lazySchema7,
1833
+ zodSchema as zodSchema7
1834
+ } from "@ai-sdk/provider-utils";
1835
+ import { z as z8 } from "zod/v4";
1836
+ var fileSearchArgsBaseSchema = z8.object({
1837
+ /** The names of the file_search_stores to retrieve from.
1838
+ * Example: `fileSearchStores/my-file-search-store-123`
1839
+ */
1840
+ fileSearchStoreNames: z8.array(z8.string()).describe(
1841
+ "The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"
1842
+ ),
1843
+ /** The number of file search retrieval chunks to retrieve. */
1844
+ topK: z8.number().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),
1845
+ /** Metadata filter to apply to the file search retrieval documents.
1846
+ * See https://google.aip.dev/160 for the syntax of the filter expression.
1847
+ */
1848
+ metadataFilter: z8.string().describe(
1849
+ "Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression."
1850
+ ).optional()
1851
+ }).passthrough();
1852
+ var fileSearchArgsSchema = lazySchema7(
1853
+ () => zodSchema7(fileSearchArgsBaseSchema)
1854
+ );
1855
+ var fileSearch = createProviderDefinedToolFactory2({
1856
+ id: "google.file_search",
1857
+ name: "file_search",
1858
+ inputSchema: fileSearchArgsSchema
1859
+ });
1860
+
1861
+ // src/tool/google-maps.ts
1862
+ import {
1863
+ createProviderDefinedToolFactory as createProviderDefinedToolFactory3,
1864
+ lazySchema as lazySchema8,
1865
+ zodSchema as zodSchema8
1866
+ } from "@ai-sdk/provider-utils";
1867
+ import { z as z9 } from "zod/v4";
1868
+ var googleMaps = createProviderDefinedToolFactory3({
1869
+ id: "google.google_maps",
1870
+ name: "google_maps",
1871
+ inputSchema: lazySchema8(() => zodSchema8(z9.object({})))
1872
+ });
1873
+
1874
+ // src/tool/google-search.ts
1875
+ import {
1876
+ createProviderDefinedToolFactory as createProviderDefinedToolFactory4,
1877
+ lazySchema as lazySchema9,
1878
+ zodSchema as zodSchema9
1879
+ } from "@ai-sdk/provider-utils";
1880
+ import { z as z10 } from "zod/v4";
1881
+ var googleSearch = createProviderDefinedToolFactory4({
1882
+ id: "google.google_search",
1883
+ name: "google_search",
1884
+ inputSchema: lazySchema9(
1885
+ () => zodSchema9(
1886
+ z10.object({
1887
+ mode: z10.enum(["MODE_DYNAMIC", "MODE_UNSPECIFIED"]).default("MODE_UNSPECIFIED"),
1888
+ dynamicThreshold: z10.number().default(1)
1889
+ })
1890
+ )
1891
+ )
1892
+ });
1893
+
1894
+ // src/tool/url-context.ts
1895
+ import {
1896
+ createProviderDefinedToolFactory as createProviderDefinedToolFactory5,
1897
+ lazySchema as lazySchema10,
1898
+ zodSchema as zodSchema10
1899
+ } from "@ai-sdk/provider-utils";
1900
+ import { z as z11 } from "zod/v4";
1901
+ var urlContext = createProviderDefinedToolFactory5({
1902
+ id: "google.url_context",
1903
+ name: "url_context",
1904
+ inputSchema: lazySchema10(() => zodSchema10(z11.object({})))
1905
+ });
1906
+
1907
+ // src/tool/vertex-rag-store.ts
1908
+ import { createProviderDefinedToolFactory as createProviderDefinedToolFactory6 } from "@ai-sdk/provider-utils";
1909
+ import { z as z12 } from "zod/v4";
1910
+ var vertexRagStore = createProviderDefinedToolFactory6({
1911
+ id: "google.vertex_rag_store",
1912
+ name: "vertex_rag_store",
1913
+ inputSchema: z12.object({
1914
+ ragCorpus: z12.string(),
1915
+ topK: z12.number().optional()
1916
+ })
1917
+ });
1918
+
1919
+ // src/google-tools.ts
1920
+ var googleTools = {
1921
+ /**
1922
+ * Creates a Google search tool that gives Google direct access to real-time web content.
1923
+ * Must have name "google_search".
1924
+ */
1925
+ googleSearch,
1926
+ /**
1927
+ * Creates an Enterprise Web Search tool for grounding responses using a compliance-focused web index.
1928
+ * Designed for highly-regulated industries (finance, healthcare, public sector).
1929
+ * Does not log customer data and supports VPC service controls.
1930
+ * Must have name "enterprise_web_search".
1931
+ *
1932
+ * @note Only available on Vertex AI. Requires Gemini 2.0 or newer.
1933
+ *
1934
+ * @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/web-grounding-enterprise
1935
+ */
1936
+ enterpriseWebSearch,
1937
+ /**
1938
+ * Creates a Google Maps grounding tool that gives the model access to Google Maps data.
1939
+ * Must have name "google_maps".
1940
+ *
1941
+ * @see https://ai.google.dev/gemini-api/docs/maps-grounding
1942
+ * @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-with-google-maps
1943
+ */
1944
+ googleMaps,
1945
+ /**
1946
+ * Creates a URL context tool that gives Google direct access to real-time web content.
1947
+ * Must have name "url_context".
1948
+ */
1949
+ urlContext,
1950
+ /**
1951
+ * Enables Retrieval Augmented Generation (RAG) via the Gemini File Search tool.
1952
+ * Must have name "file_search".
1953
+ *
1954
+ * @param fileSearchStoreNames - Fully-qualified File Search store resource names.
1955
+ * @param metadataFilter - Optional filter expression to restrict the files that can be retrieved.
1956
+ * @param topK - Optional result limit for the number of chunks returned from File Search.
1957
+ *
1958
+ * @see https://ai.google.dev/gemini-api/docs/file-search
1959
+ */
1960
+ fileSearch,
1961
+ /**
1962
+ * A tool that enables the model to generate and run Python code.
1963
+ * Must have name "code_execution".
1964
+ *
1965
+ * @note Ensure the selected model supports Code Execution.
1966
+ * Multi-tool usage with the code execution tool is typically compatible with Gemini >=2 models.
1967
+ *
1968
+ * @see https://ai.google.dev/gemini-api/docs/code-execution (Google AI)
1969
+ * @see https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/code-execution-api (Vertex AI)
1970
+ */
1971
+ codeExecution,
1972
+ /**
1973
+ * Creates a Vertex RAG Store tool that enables the model to perform RAG searches against a Vertex RAG Store.
1974
+ * Must have name "vertex_rag_store".
1975
+ */
1976
+ vertexRagStore
1977
+ };
1978
+
1979
+ // src/google-generative-ai-image-model.ts
1980
+ import {
1981
+ combineHeaders as combineHeaders3,
1982
+ createJsonResponseHandler as createJsonResponseHandler3,
1983
+ lazySchema as lazySchema11,
1984
+ parseProviderOptions as parseProviderOptions3,
1985
+ postJsonToApi as postJsonToApi3,
1986
+ resolve as resolve3,
1987
+ zodSchema as zodSchema11
1988
+ } from "@ai-sdk/provider-utils";
1989
+ import { z as z13 } from "zod/v4";
1990
+ var GoogleGenerativeAIImageModel = class {
1991
+ constructor(modelId, settings, config) {
1992
+ this.modelId = modelId;
1993
+ this.settings = settings;
1994
+ this.config = config;
1995
+ this.specificationVersion = "v2";
1996
+ }
1997
+ get maxImagesPerCall() {
1998
+ var _a;
1999
+ return (_a = this.settings.maxImagesPerCall) != null ? _a : 4;
2000
+ }
2001
+ get provider() {
2002
+ return this.config.provider;
2003
+ }
2004
+ async doGenerate(options) {
2005
+ var _a, _b, _c;
2006
+ const {
2007
+ prompt,
2008
+ n = 1,
2009
+ size = "1024x1024",
2010
+ aspectRatio = "1:1",
2011
+ seed,
2012
+ providerOptions,
2013
+ headers,
2014
+ abortSignal
2015
+ } = options;
2016
+ const warnings = [];
2017
+ if (size != null) {
2018
+ warnings.push({
2019
+ type: "unsupported-setting",
2020
+ setting: "size",
2021
+ details: "This model does not support the `size` option. Use `aspectRatio` instead."
2022
+ });
2023
+ }
2024
+ if (seed != null) {
2025
+ warnings.push({
2026
+ type: "unsupported-setting",
2027
+ setting: "seed",
2028
+ details: "This model does not support the `seed` option through this provider."
2029
+ });
2030
+ }
2031
+ const googleOptions = await parseProviderOptions3({
2032
+ provider: "google",
2033
+ providerOptions,
2034
+ schema: googleImageProviderOptionsSchema
2035
+ });
2036
+ const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
2037
+ const parameters = {
2038
+ sampleCount: n
2039
+ };
2040
+ if (aspectRatio != null) {
2041
+ parameters.aspectRatio = aspectRatio;
2042
+ }
2043
+ if (googleOptions) {
2044
+ Object.assign(parameters, googleOptions);
2045
+ }
2046
+ const body = {
2047
+ instances: [{ prompt }],
2048
+ parameters
2049
+ };
2050
+ const { responseHeaders, value: response } = await postJsonToApi3({
2051
+ url: `${this.config.baseURL}/models/${this.modelId}:predict`,
2052
+ headers: combineHeaders3(await resolve3(this.config.headers), headers),
2053
+ body,
2054
+ failedResponseHandler: googleFailedResponseHandler,
2055
+ successfulResponseHandler: createJsonResponseHandler3(
2056
+ googleImageResponseSchema
2057
+ ),
2058
+ abortSignal,
2059
+ fetch: this.config.fetch
2060
+ });
2061
+ return {
2062
+ images: response.predictions.map(
2063
+ (p) => p.bytesBase64Encoded
2064
+ ),
2065
+ warnings: warnings != null ? warnings : [],
2066
+ providerMetadata: {
2067
+ google: {
2068
+ images: response.predictions.map((prediction) => ({
2069
+ // Add any prediction-specific metadata here
2070
+ }))
2071
+ }
2072
+ },
2073
+ response: {
2074
+ timestamp: currentDate,
2075
+ modelId: this.modelId,
2076
+ headers: responseHeaders
2077
+ }
2078
+ };
2079
+ }
2080
+ };
2081
+ var googleImageResponseSchema = lazySchema11(
2082
+ () => zodSchema11(
2083
+ z13.object({
2084
+ predictions: z13.array(z13.object({ bytesBase64Encoded: z13.string() })).default([])
2085
+ })
2086
+ )
2087
+ );
2088
+ var googleImageProviderOptionsSchema = lazySchema11(
2089
+ () => zodSchema11(
2090
+ z13.object({
2091
+ personGeneration: z13.enum(["dont_allow", "allow_adult", "allow_all"]).nullish(),
2092
+ aspectRatio: z13.enum(["1:1", "3:4", "4:3", "9:16", "16:9"]).nullish()
2093
+ })
2094
+ )
2095
+ );
2096
+
2097
+ // src/google-provider.ts
2098
+ function createGoogleGenerativeAI(options = {}) {
2099
+ var _a, _b;
2100
+ const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://cloudcode-pa.googleapis.com";
2101
+ const providerName = (_b = options.name) != null ? _b : "google.generative-ai";
2102
+ const getHeaders = () => withUserAgentSuffix(
2103
+ {
2104
+ Authorization: `Bearer ${loadApiKey({
2105
+ apiKey: options.apiKey,
2106
+ environmentVariableName: "GOOGLE_CLOUD_ACCESS_TOKEN",
2107
+ description: "Google Cloud Access Token"
2108
+ })}`,
2109
+ ...options.headers
2110
+ },
2111
+ `ai-sdk/google-cloudassist/${VERSION}`
2112
+ );
2113
+ const createChatModel = (modelId) => {
2114
+ var _a2;
2115
+ return new GoogleGenerativeAILanguageModel(modelId, {
2116
+ provider: providerName,
2117
+ baseURL,
2118
+ headers: getHeaders,
2119
+ generateId: (_a2 = options.generateId) != null ? _a2 : generateId2,
2120
+ supportedUrls: () => ({
2121
+ "*": [
2122
+ // Google Generative Language "files" endpoint
2123
+ // e.g. https://generativelanguage.googleapis.com/v1beta/files/...
2124
+ new RegExp(`^${baseURL}/files/.*$`),
2125
+ // YouTube URLs (public or unlisted videos)
2126
+ new RegExp(
2127
+ `^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$`
2128
+ ),
2129
+ new RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`)
2130
+ ]
2131
+ }),
2132
+ fetch: options.fetch
2133
+ });
2134
+ };
2135
+ const createEmbeddingModel = (modelId) => new GoogleGenerativeAIEmbeddingModel(modelId, {
2136
+ provider: providerName,
2137
+ baseURL,
2138
+ headers: getHeaders,
2139
+ fetch: options.fetch
2140
+ });
2141
+ const createImageModel = (modelId, settings = {}) => new GoogleGenerativeAIImageModel(modelId, settings, {
2142
+ provider: providerName,
2143
+ baseURL,
2144
+ headers: getHeaders,
2145
+ fetch: options.fetch
2146
+ });
2147
+ const provider = function(modelId) {
2148
+ if (new.target) {
2149
+ throw new Error(
2150
+ "The Google Generative AI model function cannot be called with the new keyword."
2151
+ );
2152
+ }
2153
+ return createChatModel(modelId);
2154
+ };
2155
+ provider.languageModel = createChatModel;
2156
+ provider.chat = createChatModel;
2157
+ provider.generativeAI = createChatModel;
2158
+ provider.embedding = createEmbeddingModel;
2159
+ provider.textEmbedding = createEmbeddingModel;
2160
+ provider.textEmbeddingModel = createEmbeddingModel;
2161
+ provider.image = createImageModel;
2162
+ provider.imageModel = createImageModel;
2163
+ provider.tools = googleTools;
2164
+ return provider;
2165
+ }
2166
+ var google = createGoogleGenerativeAI();
2167
+ export {
2168
+ VERSION,
2169
+ createGoogleGenerativeAI,
2170
+ google
2171
+ };
2172
+ //# sourceMappingURL=index.mjs.map