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