@ai-sdk/google 4.0.0-beta.35 → 4.0.0-beta.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/dist/index.js +492 -416
- package/dist/index.js.map +1 -1
- package/dist/internal/index.js +307 -283
- package/dist/internal/index.js.map +1 -1
- package/package.json +9 -10
- package/src/google-generative-ai-language-model.ts +8 -1
- package/src/google-generative-ai-options.ts +7 -0
- package/dist/index.d.mts +0 -427
- package/dist/index.mjs +0 -3430
- package/dist/index.mjs.map +0 -1
- package/dist/internal/index.d.mts +0 -319
- package/dist/internal/index.mjs +0 -2449
- package/dist/internal/index.mjs.map +0 -1
package/dist/index.mjs
DELETED
|
@@ -1,3430 +0,0 @@
|
|
|
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 ? "4.0.0-beta.35" : "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 googleEmbeddingContentPartSchema = z2.union([
|
|
57
|
-
z2.object({ text: z2.string() }),
|
|
58
|
-
z2.object({
|
|
59
|
-
inlineData: z2.object({
|
|
60
|
-
mimeType: z2.string(),
|
|
61
|
-
data: z2.string()
|
|
62
|
-
})
|
|
63
|
-
})
|
|
64
|
-
]);
|
|
65
|
-
var googleEmbeddingModelOptions = lazySchema2(
|
|
66
|
-
() => zodSchema2(
|
|
67
|
-
z2.object({
|
|
68
|
-
/**
|
|
69
|
-
* Optional. Optional reduced dimension for the output embedding.
|
|
70
|
-
* If set, excessive values in the output embedding are truncated from the end.
|
|
71
|
-
*/
|
|
72
|
-
outputDimensionality: z2.number().optional(),
|
|
73
|
-
/**
|
|
74
|
-
* Optional. Specifies the task type for generating embeddings.
|
|
75
|
-
* Supported task types:
|
|
76
|
-
* - SEMANTIC_SIMILARITY: Optimized for text similarity.
|
|
77
|
-
* - CLASSIFICATION: Optimized for text classification.
|
|
78
|
-
* - CLUSTERING: Optimized for clustering texts based on similarity.
|
|
79
|
-
* - RETRIEVAL_DOCUMENT: Optimized for document retrieval.
|
|
80
|
-
* - RETRIEVAL_QUERY: Optimized for query-based retrieval.
|
|
81
|
-
* - QUESTION_ANSWERING: Optimized for answering questions.
|
|
82
|
-
* - FACT_VERIFICATION: Optimized for verifying factual information.
|
|
83
|
-
* - CODE_RETRIEVAL_QUERY: Optimized for retrieving code blocks based on natural language queries.
|
|
84
|
-
*/
|
|
85
|
-
taskType: z2.enum([
|
|
86
|
-
"SEMANTIC_SIMILARITY",
|
|
87
|
-
"CLASSIFICATION",
|
|
88
|
-
"CLUSTERING",
|
|
89
|
-
"RETRIEVAL_DOCUMENT",
|
|
90
|
-
"RETRIEVAL_QUERY",
|
|
91
|
-
"QUESTION_ANSWERING",
|
|
92
|
-
"FACT_VERIFICATION",
|
|
93
|
-
"CODE_RETRIEVAL_QUERY"
|
|
94
|
-
]).optional(),
|
|
95
|
-
/**
|
|
96
|
-
* Optional. Per-value multimodal content parts for embedding non-text
|
|
97
|
-
* content (images, video, PDF, audio). Each entry corresponds to the
|
|
98
|
-
* embedding value at the same index and its parts are merged with the
|
|
99
|
-
* text value in the request. Use `null` for entries that are text-only.
|
|
100
|
-
*
|
|
101
|
-
* The array length must match the number of values being embedded. In
|
|
102
|
-
* the case of a single embedding, the array length must be 1.
|
|
103
|
-
*/
|
|
104
|
-
content: z2.array(z2.array(googleEmbeddingContentPartSchema).min(1).nullable()).optional()
|
|
105
|
-
})
|
|
106
|
-
)
|
|
107
|
-
);
|
|
108
|
-
|
|
109
|
-
// src/google-generative-ai-embedding-model.ts
|
|
110
|
-
var GoogleGenerativeAIEmbeddingModel = class {
|
|
111
|
-
constructor(modelId, config) {
|
|
112
|
-
this.specificationVersion = "v4";
|
|
113
|
-
this.maxEmbeddingsPerCall = 2048;
|
|
114
|
-
this.supportsParallelCalls = true;
|
|
115
|
-
this.modelId = modelId;
|
|
116
|
-
this.config = config;
|
|
117
|
-
}
|
|
118
|
-
get provider() {
|
|
119
|
-
return this.config.provider;
|
|
120
|
-
}
|
|
121
|
-
async doEmbed({
|
|
122
|
-
values,
|
|
123
|
-
headers,
|
|
124
|
-
abortSignal,
|
|
125
|
-
providerOptions
|
|
126
|
-
}) {
|
|
127
|
-
const googleOptions = await parseProviderOptions({
|
|
128
|
-
provider: "google",
|
|
129
|
-
providerOptions,
|
|
130
|
-
schema: googleEmbeddingModelOptions
|
|
131
|
-
});
|
|
132
|
-
if (values.length > this.maxEmbeddingsPerCall) {
|
|
133
|
-
throw new TooManyEmbeddingValuesForCallError({
|
|
134
|
-
provider: this.provider,
|
|
135
|
-
modelId: this.modelId,
|
|
136
|
-
maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
|
|
137
|
-
values
|
|
138
|
-
});
|
|
139
|
-
}
|
|
140
|
-
const mergedHeaders = combineHeaders(
|
|
141
|
-
await resolve(this.config.headers),
|
|
142
|
-
headers
|
|
143
|
-
);
|
|
144
|
-
const multimodalContent = googleOptions == null ? void 0 : googleOptions.content;
|
|
145
|
-
if (multimodalContent != null && multimodalContent.length !== values.length) {
|
|
146
|
-
throw new Error(
|
|
147
|
-
`The number of multimodal content entries (${multimodalContent.length}) must match the number of values (${values.length}).`
|
|
148
|
-
);
|
|
149
|
-
}
|
|
150
|
-
if (values.length === 1) {
|
|
151
|
-
const valueParts = multimodalContent == null ? void 0 : multimodalContent[0];
|
|
152
|
-
const textPart = values[0] ? [{ text: values[0] }] : [];
|
|
153
|
-
const parts = valueParts != null ? [...textPart, ...valueParts] : [{ text: values[0] }];
|
|
154
|
-
const {
|
|
155
|
-
responseHeaders: responseHeaders2,
|
|
156
|
-
value: response2,
|
|
157
|
-
rawValue: rawValue2
|
|
158
|
-
} = await postJsonToApi({
|
|
159
|
-
url: `${this.config.baseURL}/models/${this.modelId}:embedContent`,
|
|
160
|
-
headers: mergedHeaders,
|
|
161
|
-
body: {
|
|
162
|
-
model: `models/${this.modelId}`,
|
|
163
|
-
content: {
|
|
164
|
-
parts
|
|
165
|
-
},
|
|
166
|
-
outputDimensionality: googleOptions == null ? void 0 : googleOptions.outputDimensionality,
|
|
167
|
-
taskType: googleOptions == null ? void 0 : googleOptions.taskType
|
|
168
|
-
},
|
|
169
|
-
failedResponseHandler: googleFailedResponseHandler,
|
|
170
|
-
successfulResponseHandler: createJsonResponseHandler(
|
|
171
|
-
googleGenerativeAISingleEmbeddingResponseSchema
|
|
172
|
-
),
|
|
173
|
-
abortSignal,
|
|
174
|
-
fetch: this.config.fetch
|
|
175
|
-
});
|
|
176
|
-
return {
|
|
177
|
-
warnings: [],
|
|
178
|
-
embeddings: [response2.embedding.values],
|
|
179
|
-
usage: void 0,
|
|
180
|
-
response: { headers: responseHeaders2, body: rawValue2 }
|
|
181
|
-
};
|
|
182
|
-
}
|
|
183
|
-
const {
|
|
184
|
-
responseHeaders,
|
|
185
|
-
value: response,
|
|
186
|
-
rawValue
|
|
187
|
-
} = await postJsonToApi({
|
|
188
|
-
url: `${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,
|
|
189
|
-
headers: mergedHeaders,
|
|
190
|
-
body: {
|
|
191
|
-
requests: values.map((value, index) => {
|
|
192
|
-
const valueParts = multimodalContent == null ? void 0 : multimodalContent[index];
|
|
193
|
-
const textPart = value ? [{ text: value }] : [];
|
|
194
|
-
return {
|
|
195
|
-
model: `models/${this.modelId}`,
|
|
196
|
-
content: {
|
|
197
|
-
role: "user",
|
|
198
|
-
parts: valueParts != null ? [...textPart, ...valueParts] : [{ text: value }]
|
|
199
|
-
},
|
|
200
|
-
outputDimensionality: googleOptions == null ? void 0 : googleOptions.outputDimensionality,
|
|
201
|
-
taskType: googleOptions == null ? void 0 : googleOptions.taskType
|
|
202
|
-
};
|
|
203
|
-
})
|
|
204
|
-
},
|
|
205
|
-
failedResponseHandler: googleFailedResponseHandler,
|
|
206
|
-
successfulResponseHandler: createJsonResponseHandler(
|
|
207
|
-
googleGenerativeAITextEmbeddingResponseSchema
|
|
208
|
-
),
|
|
209
|
-
abortSignal,
|
|
210
|
-
fetch: this.config.fetch
|
|
211
|
-
});
|
|
212
|
-
return {
|
|
213
|
-
warnings: [],
|
|
214
|
-
embeddings: response.embeddings.map((item) => item.values),
|
|
215
|
-
usage: void 0,
|
|
216
|
-
response: { headers: responseHeaders, body: rawValue }
|
|
217
|
-
};
|
|
218
|
-
}
|
|
219
|
-
};
|
|
220
|
-
var googleGenerativeAITextEmbeddingResponseSchema = lazySchema3(
|
|
221
|
-
() => zodSchema3(
|
|
222
|
-
z3.object({
|
|
223
|
-
embeddings: z3.array(z3.object({ values: z3.array(z3.number()) }))
|
|
224
|
-
})
|
|
225
|
-
)
|
|
226
|
-
);
|
|
227
|
-
var googleGenerativeAISingleEmbeddingResponseSchema = lazySchema3(
|
|
228
|
-
() => zodSchema3(
|
|
229
|
-
z3.object({
|
|
230
|
-
embedding: z3.object({ values: z3.array(z3.number()) })
|
|
231
|
-
})
|
|
232
|
-
)
|
|
233
|
-
);
|
|
234
|
-
|
|
235
|
-
// src/google-generative-ai-language-model.ts
|
|
236
|
-
import {
|
|
237
|
-
combineHeaders as combineHeaders2,
|
|
238
|
-
createEventSourceResponseHandler,
|
|
239
|
-
createJsonResponseHandler as createJsonResponseHandler2,
|
|
240
|
-
generateId,
|
|
241
|
-
isCustomReasoning,
|
|
242
|
-
lazySchema as lazySchema5,
|
|
243
|
-
mapReasoningToProviderBudget,
|
|
244
|
-
mapReasoningToProviderEffort,
|
|
245
|
-
parseProviderOptions as parseProviderOptions2,
|
|
246
|
-
postJsonToApi as postJsonToApi2,
|
|
247
|
-
resolve as resolve2,
|
|
248
|
-
zodSchema as zodSchema5
|
|
249
|
-
} from "@ai-sdk/provider-utils";
|
|
250
|
-
import { z as z5 } from "zod/v4";
|
|
251
|
-
|
|
252
|
-
// src/convert-google-generative-ai-usage.ts
|
|
253
|
-
function convertGoogleGenerativeAIUsage(usage) {
|
|
254
|
-
var _a, _b, _c, _d;
|
|
255
|
-
if (usage == null) {
|
|
256
|
-
return {
|
|
257
|
-
inputTokens: {
|
|
258
|
-
total: void 0,
|
|
259
|
-
noCache: void 0,
|
|
260
|
-
cacheRead: void 0,
|
|
261
|
-
cacheWrite: void 0
|
|
262
|
-
},
|
|
263
|
-
outputTokens: {
|
|
264
|
-
total: void 0,
|
|
265
|
-
text: void 0,
|
|
266
|
-
reasoning: void 0
|
|
267
|
-
},
|
|
268
|
-
raw: void 0
|
|
269
|
-
};
|
|
270
|
-
}
|
|
271
|
-
const promptTokens = (_a = usage.promptTokenCount) != null ? _a : 0;
|
|
272
|
-
const candidatesTokens = (_b = usage.candidatesTokenCount) != null ? _b : 0;
|
|
273
|
-
const cachedContentTokens = (_c = usage.cachedContentTokenCount) != null ? _c : 0;
|
|
274
|
-
const thoughtsTokens = (_d = usage.thoughtsTokenCount) != null ? _d : 0;
|
|
275
|
-
return {
|
|
276
|
-
inputTokens: {
|
|
277
|
-
total: promptTokens,
|
|
278
|
-
noCache: promptTokens - cachedContentTokens,
|
|
279
|
-
cacheRead: cachedContentTokens,
|
|
280
|
-
cacheWrite: void 0
|
|
281
|
-
},
|
|
282
|
-
outputTokens: {
|
|
283
|
-
total: candidatesTokens + thoughtsTokens,
|
|
284
|
-
text: candidatesTokens,
|
|
285
|
-
reasoning: thoughtsTokens
|
|
286
|
-
},
|
|
287
|
-
raw: usage
|
|
288
|
-
};
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
// src/convert-json-schema-to-openapi-schema.ts
|
|
292
|
-
function convertJSONSchemaToOpenAPISchema(jsonSchema, isRoot = true) {
|
|
293
|
-
if (jsonSchema == null) {
|
|
294
|
-
return void 0;
|
|
295
|
-
}
|
|
296
|
-
if (isEmptyObjectSchema(jsonSchema)) {
|
|
297
|
-
if (isRoot) {
|
|
298
|
-
return void 0;
|
|
299
|
-
}
|
|
300
|
-
if (typeof jsonSchema === "object" && jsonSchema.description) {
|
|
301
|
-
return { type: "object", description: jsonSchema.description };
|
|
302
|
-
}
|
|
303
|
-
return { type: "object" };
|
|
304
|
-
}
|
|
305
|
-
if (typeof jsonSchema === "boolean") {
|
|
306
|
-
return { type: "boolean", properties: {} };
|
|
307
|
-
}
|
|
308
|
-
const {
|
|
309
|
-
type,
|
|
310
|
-
description,
|
|
311
|
-
required,
|
|
312
|
-
properties,
|
|
313
|
-
items,
|
|
314
|
-
allOf,
|
|
315
|
-
anyOf,
|
|
316
|
-
oneOf,
|
|
317
|
-
format,
|
|
318
|
-
const: constValue,
|
|
319
|
-
minLength,
|
|
320
|
-
enum: enumValues
|
|
321
|
-
} = jsonSchema;
|
|
322
|
-
const result = {};
|
|
323
|
-
if (description) result.description = description;
|
|
324
|
-
if (required) result.required = required;
|
|
325
|
-
if (format) result.format = format;
|
|
326
|
-
if (constValue !== void 0) {
|
|
327
|
-
result.enum = [constValue];
|
|
328
|
-
}
|
|
329
|
-
if (type) {
|
|
330
|
-
if (Array.isArray(type)) {
|
|
331
|
-
const hasNull = type.includes("null");
|
|
332
|
-
const nonNullTypes = type.filter((t) => t !== "null");
|
|
333
|
-
if (nonNullTypes.length === 0) {
|
|
334
|
-
result.type = "null";
|
|
335
|
-
} else {
|
|
336
|
-
result.anyOf = nonNullTypes.map((t) => ({ type: t }));
|
|
337
|
-
if (hasNull) {
|
|
338
|
-
result.nullable = true;
|
|
339
|
-
}
|
|
340
|
-
}
|
|
341
|
-
} else {
|
|
342
|
-
result.type = type;
|
|
343
|
-
}
|
|
344
|
-
}
|
|
345
|
-
if (enumValues !== void 0) {
|
|
346
|
-
result.enum = enumValues;
|
|
347
|
-
}
|
|
348
|
-
if (properties != null) {
|
|
349
|
-
result.properties = Object.entries(properties).reduce(
|
|
350
|
-
(acc, [key, value]) => {
|
|
351
|
-
acc[key] = convertJSONSchemaToOpenAPISchema(value, false);
|
|
352
|
-
return acc;
|
|
353
|
-
},
|
|
354
|
-
{}
|
|
355
|
-
);
|
|
356
|
-
}
|
|
357
|
-
if (items) {
|
|
358
|
-
result.items = Array.isArray(items) ? items.map((item) => convertJSONSchemaToOpenAPISchema(item, false)) : convertJSONSchemaToOpenAPISchema(items, false);
|
|
359
|
-
}
|
|
360
|
-
if (allOf) {
|
|
361
|
-
result.allOf = allOf.map(
|
|
362
|
-
(item) => convertJSONSchemaToOpenAPISchema(item, false)
|
|
363
|
-
);
|
|
364
|
-
}
|
|
365
|
-
if (anyOf) {
|
|
366
|
-
if (anyOf.some(
|
|
367
|
-
(schema) => typeof schema === "object" && (schema == null ? void 0 : schema.type) === "null"
|
|
368
|
-
)) {
|
|
369
|
-
const nonNullSchemas = anyOf.filter(
|
|
370
|
-
(schema) => !(typeof schema === "object" && (schema == null ? void 0 : schema.type) === "null")
|
|
371
|
-
);
|
|
372
|
-
if (nonNullSchemas.length === 1) {
|
|
373
|
-
const converted = convertJSONSchemaToOpenAPISchema(
|
|
374
|
-
nonNullSchemas[0],
|
|
375
|
-
false
|
|
376
|
-
);
|
|
377
|
-
if (typeof converted === "object") {
|
|
378
|
-
result.nullable = true;
|
|
379
|
-
Object.assign(result, converted);
|
|
380
|
-
}
|
|
381
|
-
} else {
|
|
382
|
-
result.anyOf = nonNullSchemas.map(
|
|
383
|
-
(item) => convertJSONSchemaToOpenAPISchema(item, false)
|
|
384
|
-
);
|
|
385
|
-
result.nullable = true;
|
|
386
|
-
}
|
|
387
|
-
} else {
|
|
388
|
-
result.anyOf = anyOf.map(
|
|
389
|
-
(item) => convertJSONSchemaToOpenAPISchema(item, false)
|
|
390
|
-
);
|
|
391
|
-
}
|
|
392
|
-
}
|
|
393
|
-
if (oneOf) {
|
|
394
|
-
result.oneOf = oneOf.map(
|
|
395
|
-
(item) => convertJSONSchemaToOpenAPISchema(item, false)
|
|
396
|
-
);
|
|
397
|
-
}
|
|
398
|
-
if (minLength !== void 0) {
|
|
399
|
-
result.minLength = minLength;
|
|
400
|
-
}
|
|
401
|
-
return result;
|
|
402
|
-
}
|
|
403
|
-
function isEmptyObjectSchema(jsonSchema) {
|
|
404
|
-
return jsonSchema != null && typeof jsonSchema === "object" && jsonSchema.type === "object" && (jsonSchema.properties == null || Object.keys(jsonSchema.properties).length === 0) && !jsonSchema.additionalProperties;
|
|
405
|
-
}
|
|
406
|
-
|
|
407
|
-
// src/convert-to-google-generative-ai-messages.ts
|
|
408
|
-
import {
|
|
409
|
-
UnsupportedFunctionalityError
|
|
410
|
-
} from "@ai-sdk/provider";
|
|
411
|
-
import {
|
|
412
|
-
convertToBase64,
|
|
413
|
-
isProviderReference,
|
|
414
|
-
resolveProviderReference
|
|
415
|
-
} from "@ai-sdk/provider-utils";
|
|
416
|
-
var dataUrlRegex = /^data:([^;,]+);base64,(.+)$/s;
|
|
417
|
-
function parseBase64DataUrl(value) {
|
|
418
|
-
const match = dataUrlRegex.exec(value);
|
|
419
|
-
if (match == null) {
|
|
420
|
-
return void 0;
|
|
421
|
-
}
|
|
422
|
-
return {
|
|
423
|
-
mediaType: match[1],
|
|
424
|
-
data: match[2]
|
|
425
|
-
};
|
|
426
|
-
}
|
|
427
|
-
function convertUrlToolResultPart(url) {
|
|
428
|
-
const parsedDataUrl = parseBase64DataUrl(url);
|
|
429
|
-
if (parsedDataUrl == null) {
|
|
430
|
-
return void 0;
|
|
431
|
-
}
|
|
432
|
-
return {
|
|
433
|
-
inlineData: {
|
|
434
|
-
mimeType: parsedDataUrl.mediaType,
|
|
435
|
-
data: parsedDataUrl.data
|
|
436
|
-
}
|
|
437
|
-
};
|
|
438
|
-
}
|
|
439
|
-
function appendToolResultParts(parts, toolName, outputValue) {
|
|
440
|
-
const functionResponseParts = [];
|
|
441
|
-
const responseTextParts = [];
|
|
442
|
-
for (const contentPart of outputValue) {
|
|
443
|
-
switch (contentPart.type) {
|
|
444
|
-
case "text": {
|
|
445
|
-
responseTextParts.push(contentPart.text);
|
|
446
|
-
break;
|
|
447
|
-
}
|
|
448
|
-
case "image-data":
|
|
449
|
-
case "file-data": {
|
|
450
|
-
functionResponseParts.push({
|
|
451
|
-
inlineData: {
|
|
452
|
-
mimeType: contentPart.mediaType,
|
|
453
|
-
data: contentPart.data
|
|
454
|
-
}
|
|
455
|
-
});
|
|
456
|
-
break;
|
|
457
|
-
}
|
|
458
|
-
case "image-url":
|
|
459
|
-
case "file-url": {
|
|
460
|
-
const functionResponsePart = convertUrlToolResultPart(
|
|
461
|
-
contentPart.url
|
|
462
|
-
);
|
|
463
|
-
if (functionResponsePart != null) {
|
|
464
|
-
functionResponseParts.push(functionResponsePart);
|
|
465
|
-
} else {
|
|
466
|
-
responseTextParts.push(JSON.stringify(contentPart));
|
|
467
|
-
}
|
|
468
|
-
break;
|
|
469
|
-
}
|
|
470
|
-
default: {
|
|
471
|
-
responseTextParts.push(JSON.stringify(contentPart));
|
|
472
|
-
break;
|
|
473
|
-
}
|
|
474
|
-
}
|
|
475
|
-
}
|
|
476
|
-
parts.push({
|
|
477
|
-
functionResponse: {
|
|
478
|
-
name: toolName,
|
|
479
|
-
response: {
|
|
480
|
-
name: toolName,
|
|
481
|
-
content: responseTextParts.length > 0 ? responseTextParts.join("\n") : "Tool executed successfully."
|
|
482
|
-
},
|
|
483
|
-
...functionResponseParts.length > 0 ? { parts: functionResponseParts } : {}
|
|
484
|
-
}
|
|
485
|
-
});
|
|
486
|
-
}
|
|
487
|
-
function appendLegacyToolResultParts(parts, toolName, outputValue) {
|
|
488
|
-
for (const contentPart of outputValue) {
|
|
489
|
-
switch (contentPart.type) {
|
|
490
|
-
case "text":
|
|
491
|
-
parts.push({
|
|
492
|
-
functionResponse: {
|
|
493
|
-
name: toolName,
|
|
494
|
-
response: {
|
|
495
|
-
name: toolName,
|
|
496
|
-
content: contentPart.text
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
});
|
|
500
|
-
break;
|
|
501
|
-
case "image-data":
|
|
502
|
-
parts.push(
|
|
503
|
-
{
|
|
504
|
-
inlineData: {
|
|
505
|
-
mimeType: String(contentPart.mediaType),
|
|
506
|
-
data: String(contentPart.data)
|
|
507
|
-
}
|
|
508
|
-
},
|
|
509
|
-
{
|
|
510
|
-
text: "Tool executed successfully and returned this image as a response"
|
|
511
|
-
}
|
|
512
|
-
);
|
|
513
|
-
break;
|
|
514
|
-
default:
|
|
515
|
-
parts.push({ text: JSON.stringify(contentPart) });
|
|
516
|
-
break;
|
|
517
|
-
}
|
|
518
|
-
}
|
|
519
|
-
}
|
|
520
|
-
function convertToGoogleGenerativeAIMessages(prompt, options) {
|
|
521
|
-
var _a, _b, _c, _d, _e, _f, _g, _h;
|
|
522
|
-
const systemInstructionParts = [];
|
|
523
|
-
const contents = [];
|
|
524
|
-
let systemMessagesAllowed = true;
|
|
525
|
-
const isGemmaModel = (_a = options == null ? void 0 : options.isGemmaModel) != null ? _a : false;
|
|
526
|
-
const providerOptionsName = (_b = options == null ? void 0 : options.providerOptionsName) != null ? _b : "google";
|
|
527
|
-
const supportsFunctionResponseParts = (_c = options == null ? void 0 : options.supportsFunctionResponseParts) != null ? _c : true;
|
|
528
|
-
for (const { role, content } of prompt) {
|
|
529
|
-
switch (role) {
|
|
530
|
-
case "system": {
|
|
531
|
-
if (!systemMessagesAllowed) {
|
|
532
|
-
throw new UnsupportedFunctionalityError({
|
|
533
|
-
functionality: "system messages are only supported at the beginning of the conversation"
|
|
534
|
-
});
|
|
535
|
-
}
|
|
536
|
-
systemInstructionParts.push({ text: content });
|
|
537
|
-
break;
|
|
538
|
-
}
|
|
539
|
-
case "user": {
|
|
540
|
-
systemMessagesAllowed = false;
|
|
541
|
-
const parts = [];
|
|
542
|
-
for (const part of content) {
|
|
543
|
-
switch (part.type) {
|
|
544
|
-
case "text": {
|
|
545
|
-
parts.push({ text: part.text });
|
|
546
|
-
break;
|
|
547
|
-
}
|
|
548
|
-
case "file": {
|
|
549
|
-
const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
|
|
550
|
-
if (part.data instanceof URL) {
|
|
551
|
-
parts.push({
|
|
552
|
-
fileData: {
|
|
553
|
-
mimeType: mediaType,
|
|
554
|
-
fileUri: part.data.toString()
|
|
555
|
-
}
|
|
556
|
-
});
|
|
557
|
-
} else if (isProviderReference(part.data)) {
|
|
558
|
-
if (providerOptionsName === "vertex") {
|
|
559
|
-
throw new UnsupportedFunctionalityError({
|
|
560
|
-
functionality: "file parts with provider references"
|
|
561
|
-
});
|
|
562
|
-
}
|
|
563
|
-
parts.push({
|
|
564
|
-
fileData: {
|
|
565
|
-
mimeType: mediaType,
|
|
566
|
-
fileUri: resolveProviderReference({
|
|
567
|
-
reference: part.data,
|
|
568
|
-
provider: "google"
|
|
569
|
-
})
|
|
570
|
-
}
|
|
571
|
-
});
|
|
572
|
-
} else {
|
|
573
|
-
parts.push({
|
|
574
|
-
inlineData: {
|
|
575
|
-
mimeType: mediaType,
|
|
576
|
-
data: convertToBase64(part.data)
|
|
577
|
-
}
|
|
578
|
-
});
|
|
579
|
-
}
|
|
580
|
-
break;
|
|
581
|
-
}
|
|
582
|
-
}
|
|
583
|
-
}
|
|
584
|
-
contents.push({ role: "user", parts });
|
|
585
|
-
break;
|
|
586
|
-
}
|
|
587
|
-
case "assistant": {
|
|
588
|
-
systemMessagesAllowed = false;
|
|
589
|
-
contents.push({
|
|
590
|
-
role: "model",
|
|
591
|
-
parts: content.map((part) => {
|
|
592
|
-
var _a2, _b2, _c2, _d2;
|
|
593
|
-
const providerOpts = (_d2 = (_a2 = part.providerOptions) == null ? void 0 : _a2[providerOptionsName]) != null ? _d2 : providerOptionsName !== "google" ? (_b2 = part.providerOptions) == null ? void 0 : _b2.google : (_c2 = part.providerOptions) == null ? void 0 : _c2.vertex;
|
|
594
|
-
const thoughtSignature = (providerOpts == null ? void 0 : providerOpts.thoughtSignature) != null ? String(providerOpts.thoughtSignature) : void 0;
|
|
595
|
-
switch (part.type) {
|
|
596
|
-
case "text": {
|
|
597
|
-
return part.text.length === 0 ? void 0 : {
|
|
598
|
-
text: part.text,
|
|
599
|
-
thoughtSignature
|
|
600
|
-
};
|
|
601
|
-
}
|
|
602
|
-
case "reasoning": {
|
|
603
|
-
return part.text.length === 0 ? void 0 : {
|
|
604
|
-
text: part.text,
|
|
605
|
-
thought: true,
|
|
606
|
-
thoughtSignature
|
|
607
|
-
};
|
|
608
|
-
}
|
|
609
|
-
case "reasoning-file": {
|
|
610
|
-
if (part.data instanceof URL) {
|
|
611
|
-
throw new UnsupportedFunctionalityError({
|
|
612
|
-
functionality: "File data URLs in assistant messages are not supported"
|
|
613
|
-
});
|
|
614
|
-
}
|
|
615
|
-
return {
|
|
616
|
-
inlineData: {
|
|
617
|
-
mimeType: part.mediaType,
|
|
618
|
-
data: convertToBase64(part.data)
|
|
619
|
-
},
|
|
620
|
-
thought: true,
|
|
621
|
-
thoughtSignature
|
|
622
|
-
};
|
|
623
|
-
}
|
|
624
|
-
case "file": {
|
|
625
|
-
if (part.data instanceof URL) {
|
|
626
|
-
throw new UnsupportedFunctionalityError({
|
|
627
|
-
functionality: "File data URLs in assistant messages are not supported"
|
|
628
|
-
});
|
|
629
|
-
}
|
|
630
|
-
if (isProviderReference(part.data)) {
|
|
631
|
-
if (providerOptionsName === "vertex") {
|
|
632
|
-
throw new UnsupportedFunctionalityError({
|
|
633
|
-
functionality: "file parts with provider references"
|
|
634
|
-
});
|
|
635
|
-
}
|
|
636
|
-
return {
|
|
637
|
-
fileData: {
|
|
638
|
-
mimeType: part.mediaType,
|
|
639
|
-
fileUri: resolveProviderReference({
|
|
640
|
-
reference: part.data,
|
|
641
|
-
provider: "google"
|
|
642
|
-
})
|
|
643
|
-
},
|
|
644
|
-
...(providerOpts == null ? void 0 : providerOpts.thought) === true ? { thought: true } : {},
|
|
645
|
-
thoughtSignature
|
|
646
|
-
};
|
|
647
|
-
}
|
|
648
|
-
return {
|
|
649
|
-
inlineData: {
|
|
650
|
-
mimeType: part.mediaType,
|
|
651
|
-
data: convertToBase64(part.data)
|
|
652
|
-
},
|
|
653
|
-
...(providerOpts == null ? void 0 : providerOpts.thought) === true ? { thought: true } : {},
|
|
654
|
-
thoughtSignature
|
|
655
|
-
};
|
|
656
|
-
}
|
|
657
|
-
case "tool-call": {
|
|
658
|
-
const serverToolCallId = (providerOpts == null ? void 0 : providerOpts.serverToolCallId) != null ? String(providerOpts.serverToolCallId) : void 0;
|
|
659
|
-
const serverToolType = (providerOpts == null ? void 0 : providerOpts.serverToolType) != null ? String(providerOpts.serverToolType) : void 0;
|
|
660
|
-
if (serverToolCallId && serverToolType) {
|
|
661
|
-
return {
|
|
662
|
-
toolCall: {
|
|
663
|
-
toolType: serverToolType,
|
|
664
|
-
args: typeof part.input === "string" ? JSON.parse(part.input) : part.input,
|
|
665
|
-
id: serverToolCallId
|
|
666
|
-
},
|
|
667
|
-
thoughtSignature
|
|
668
|
-
};
|
|
669
|
-
}
|
|
670
|
-
return {
|
|
671
|
-
functionCall: {
|
|
672
|
-
name: part.toolName,
|
|
673
|
-
args: part.input
|
|
674
|
-
},
|
|
675
|
-
thoughtSignature
|
|
676
|
-
};
|
|
677
|
-
}
|
|
678
|
-
case "tool-result": {
|
|
679
|
-
const serverToolCallId = (providerOpts == null ? void 0 : providerOpts.serverToolCallId) != null ? String(providerOpts.serverToolCallId) : void 0;
|
|
680
|
-
const serverToolType = (providerOpts == null ? void 0 : providerOpts.serverToolType) != null ? String(providerOpts.serverToolType) : void 0;
|
|
681
|
-
if (serverToolCallId && serverToolType) {
|
|
682
|
-
return {
|
|
683
|
-
toolResponse: {
|
|
684
|
-
toolType: serverToolType,
|
|
685
|
-
response: part.output.type === "json" ? part.output.value : {},
|
|
686
|
-
id: serverToolCallId
|
|
687
|
-
},
|
|
688
|
-
thoughtSignature
|
|
689
|
-
};
|
|
690
|
-
}
|
|
691
|
-
return void 0;
|
|
692
|
-
}
|
|
693
|
-
}
|
|
694
|
-
}).filter((part) => part !== void 0)
|
|
695
|
-
});
|
|
696
|
-
break;
|
|
697
|
-
}
|
|
698
|
-
case "tool": {
|
|
699
|
-
systemMessagesAllowed = false;
|
|
700
|
-
const parts = [];
|
|
701
|
-
for (const part of content) {
|
|
702
|
-
if (part.type === "tool-approval-response") {
|
|
703
|
-
continue;
|
|
704
|
-
}
|
|
705
|
-
const partProviderOpts = (_g = (_d = part.providerOptions) == null ? void 0 : _d[providerOptionsName]) != null ? _g : providerOptionsName !== "google" ? (_e = part.providerOptions) == null ? void 0 : _e.google : (_f = part.providerOptions) == null ? void 0 : _f.vertex;
|
|
706
|
-
const serverToolCallId = (partProviderOpts == null ? void 0 : partProviderOpts.serverToolCallId) != null ? String(partProviderOpts.serverToolCallId) : void 0;
|
|
707
|
-
const serverToolType = (partProviderOpts == null ? void 0 : partProviderOpts.serverToolType) != null ? String(partProviderOpts.serverToolType) : void 0;
|
|
708
|
-
if (serverToolCallId && serverToolType) {
|
|
709
|
-
const serverThoughtSignature = (partProviderOpts == null ? void 0 : partProviderOpts.thoughtSignature) != null ? String(partProviderOpts.thoughtSignature) : void 0;
|
|
710
|
-
if (contents.length > 0) {
|
|
711
|
-
const lastContent = contents[contents.length - 1];
|
|
712
|
-
if (lastContent.role === "model") {
|
|
713
|
-
lastContent.parts.push({
|
|
714
|
-
toolResponse: {
|
|
715
|
-
toolType: serverToolType,
|
|
716
|
-
response: part.output.type === "json" ? part.output.value : {},
|
|
717
|
-
id: serverToolCallId
|
|
718
|
-
},
|
|
719
|
-
thoughtSignature: serverThoughtSignature
|
|
720
|
-
});
|
|
721
|
-
continue;
|
|
722
|
-
}
|
|
723
|
-
}
|
|
724
|
-
}
|
|
725
|
-
const output = part.output;
|
|
726
|
-
if (output.type === "content") {
|
|
727
|
-
if (supportsFunctionResponseParts) {
|
|
728
|
-
appendToolResultParts(parts, part.toolName, output.value);
|
|
729
|
-
} else {
|
|
730
|
-
appendLegacyToolResultParts(parts, part.toolName, output.value);
|
|
731
|
-
}
|
|
732
|
-
} else {
|
|
733
|
-
parts.push({
|
|
734
|
-
functionResponse: {
|
|
735
|
-
name: part.toolName,
|
|
736
|
-
response: {
|
|
737
|
-
name: part.toolName,
|
|
738
|
-
content: output.type === "execution-denied" ? (_h = output.reason) != null ? _h : "Tool execution denied." : output.value
|
|
739
|
-
}
|
|
740
|
-
}
|
|
741
|
-
});
|
|
742
|
-
}
|
|
743
|
-
}
|
|
744
|
-
contents.push({
|
|
745
|
-
role: "user",
|
|
746
|
-
parts
|
|
747
|
-
});
|
|
748
|
-
break;
|
|
749
|
-
}
|
|
750
|
-
}
|
|
751
|
-
}
|
|
752
|
-
if (isGemmaModel && systemInstructionParts.length > 0 && contents.length > 0 && contents[0].role === "user") {
|
|
753
|
-
const systemText = systemInstructionParts.map((part) => part.text).join("\n\n");
|
|
754
|
-
contents[0].parts.unshift({ text: systemText + "\n\n" });
|
|
755
|
-
}
|
|
756
|
-
return {
|
|
757
|
-
systemInstruction: systemInstructionParts.length > 0 && !isGemmaModel ? { parts: systemInstructionParts } : void 0,
|
|
758
|
-
contents
|
|
759
|
-
};
|
|
760
|
-
}
|
|
761
|
-
|
|
762
|
-
// src/get-model-path.ts
|
|
763
|
-
function getModelPath(modelId) {
|
|
764
|
-
return modelId.includes("/") ? modelId : `models/${modelId}`;
|
|
765
|
-
}
|
|
766
|
-
|
|
767
|
-
// src/google-generative-ai-options.ts
|
|
768
|
-
import { lazySchema as lazySchema4, zodSchema as zodSchema4 } from "@ai-sdk/provider-utils";
|
|
769
|
-
import { z as z4 } from "zod/v4";
|
|
770
|
-
var googleLanguageModelOptions = lazySchema4(
|
|
771
|
-
() => zodSchema4(
|
|
772
|
-
z4.object({
|
|
773
|
-
responseModalities: z4.array(z4.enum(["TEXT", "IMAGE"])).optional(),
|
|
774
|
-
thinkingConfig: z4.object({
|
|
775
|
-
thinkingBudget: z4.number().optional(),
|
|
776
|
-
includeThoughts: z4.boolean().optional(),
|
|
777
|
-
// https://ai.google.dev/gemini-api/docs/gemini-3?thinking=high#thinking_level
|
|
778
|
-
thinkingLevel: z4.enum(["minimal", "low", "medium", "high"]).optional()
|
|
779
|
-
}).optional(),
|
|
780
|
-
/**
|
|
781
|
-
* Optional.
|
|
782
|
-
* The name of the cached content used as context to serve the prediction.
|
|
783
|
-
* Format: cachedContents/{cachedContent}
|
|
784
|
-
*/
|
|
785
|
-
cachedContent: z4.string().optional(),
|
|
786
|
-
/**
|
|
787
|
-
* Optional. Enable structured output. Default is true.
|
|
788
|
-
*
|
|
789
|
-
* This is useful when the JSON Schema contains elements that are
|
|
790
|
-
* not supported by the OpenAPI schema version that
|
|
791
|
-
* Google Generative AI uses. You can use this to disable
|
|
792
|
-
* structured outputs if you need to.
|
|
793
|
-
*/
|
|
794
|
-
structuredOutputs: z4.boolean().optional(),
|
|
795
|
-
/**
|
|
796
|
-
* Optional. A list of unique safety settings for blocking unsafe content.
|
|
797
|
-
*/
|
|
798
|
-
safetySettings: z4.array(
|
|
799
|
-
z4.object({
|
|
800
|
-
category: z4.enum([
|
|
801
|
-
"HARM_CATEGORY_UNSPECIFIED",
|
|
802
|
-
"HARM_CATEGORY_HATE_SPEECH",
|
|
803
|
-
"HARM_CATEGORY_DANGEROUS_CONTENT",
|
|
804
|
-
"HARM_CATEGORY_HARASSMENT",
|
|
805
|
-
"HARM_CATEGORY_SEXUALLY_EXPLICIT",
|
|
806
|
-
"HARM_CATEGORY_CIVIC_INTEGRITY"
|
|
807
|
-
]),
|
|
808
|
-
threshold: z4.enum([
|
|
809
|
-
"HARM_BLOCK_THRESHOLD_UNSPECIFIED",
|
|
810
|
-
"BLOCK_LOW_AND_ABOVE",
|
|
811
|
-
"BLOCK_MEDIUM_AND_ABOVE",
|
|
812
|
-
"BLOCK_ONLY_HIGH",
|
|
813
|
-
"BLOCK_NONE",
|
|
814
|
-
"OFF"
|
|
815
|
-
])
|
|
816
|
-
})
|
|
817
|
-
).optional(),
|
|
818
|
-
threshold: z4.enum([
|
|
819
|
-
"HARM_BLOCK_THRESHOLD_UNSPECIFIED",
|
|
820
|
-
"BLOCK_LOW_AND_ABOVE",
|
|
821
|
-
"BLOCK_MEDIUM_AND_ABOVE",
|
|
822
|
-
"BLOCK_ONLY_HIGH",
|
|
823
|
-
"BLOCK_NONE",
|
|
824
|
-
"OFF"
|
|
825
|
-
]).optional(),
|
|
826
|
-
/**
|
|
827
|
-
* Optional. Enables timestamp understanding for audio-only files.
|
|
828
|
-
*
|
|
829
|
-
* https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/audio-understanding
|
|
830
|
-
*/
|
|
831
|
-
audioTimestamp: z4.boolean().optional(),
|
|
832
|
-
/**
|
|
833
|
-
* Optional. Defines labels used in billing reports. Available on Vertex AI only.
|
|
834
|
-
*
|
|
835
|
-
* https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/add-labels-to-api-calls
|
|
836
|
-
*/
|
|
837
|
-
labels: z4.record(z4.string(), z4.string()).optional(),
|
|
838
|
-
/**
|
|
839
|
-
* Optional. If specified, the media resolution specified will be used.
|
|
840
|
-
*
|
|
841
|
-
* https://ai.google.dev/api/generate-content#MediaResolution
|
|
842
|
-
*/
|
|
843
|
-
mediaResolution: z4.enum([
|
|
844
|
-
"MEDIA_RESOLUTION_UNSPECIFIED",
|
|
845
|
-
"MEDIA_RESOLUTION_LOW",
|
|
846
|
-
"MEDIA_RESOLUTION_MEDIUM",
|
|
847
|
-
"MEDIA_RESOLUTION_HIGH"
|
|
848
|
-
]).optional(),
|
|
849
|
-
/**
|
|
850
|
-
* Optional. Configures the image generation aspect ratio for Gemini models.
|
|
851
|
-
*
|
|
852
|
-
* https://ai.google.dev/gemini-api/docs/image-generation#aspect_ratios
|
|
853
|
-
*/
|
|
854
|
-
imageConfig: z4.object({
|
|
855
|
-
aspectRatio: z4.enum([
|
|
856
|
-
"1:1",
|
|
857
|
-
"2:3",
|
|
858
|
-
"3:2",
|
|
859
|
-
"3:4",
|
|
860
|
-
"4:3",
|
|
861
|
-
"4:5",
|
|
862
|
-
"5:4",
|
|
863
|
-
"9:16",
|
|
864
|
-
"16:9",
|
|
865
|
-
"21:9",
|
|
866
|
-
"1:8",
|
|
867
|
-
"8:1",
|
|
868
|
-
"1:4",
|
|
869
|
-
"4:1"
|
|
870
|
-
]).optional(),
|
|
871
|
-
imageSize: z4.enum(["1K", "2K", "4K", "512"]).optional()
|
|
872
|
-
}).optional(),
|
|
873
|
-
/**
|
|
874
|
-
* Optional. Configuration for grounding retrieval.
|
|
875
|
-
* Used to provide location context for Google Maps and Google Search grounding.
|
|
876
|
-
*
|
|
877
|
-
* https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-with-google-maps
|
|
878
|
-
*/
|
|
879
|
-
retrievalConfig: z4.object({
|
|
880
|
-
latLng: z4.object({
|
|
881
|
-
latitude: z4.number(),
|
|
882
|
-
longitude: z4.number()
|
|
883
|
-
}).optional()
|
|
884
|
-
}).optional(),
|
|
885
|
-
/**
|
|
886
|
-
* Optional. When set to true, function call arguments will be streamed
|
|
887
|
-
* incrementally via partialArgs in streaming responses. Only supported
|
|
888
|
-
* on the Vertex AI API (not the Gemini API) and only for Gemini 3+
|
|
889
|
-
* models.
|
|
890
|
-
*
|
|
891
|
-
* @default false
|
|
892
|
-
*
|
|
893
|
-
* https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc
|
|
894
|
-
*/
|
|
895
|
-
streamFunctionCallArguments: z4.boolean().optional(),
|
|
896
|
-
/**
|
|
897
|
-
* Optional. The service tier to use for the request.
|
|
898
|
-
*/
|
|
899
|
-
serviceTier: z4.enum(["standard", "flex", "priority"]).optional()
|
|
900
|
-
})
|
|
901
|
-
)
|
|
902
|
-
);
|
|
903
|
-
|
|
904
|
-
// src/google-prepare-tools.ts
|
|
905
|
-
import {
|
|
906
|
-
UnsupportedFunctionalityError as UnsupportedFunctionalityError2
|
|
907
|
-
} from "@ai-sdk/provider";
|
|
908
|
-
function prepareTools({
|
|
909
|
-
tools,
|
|
910
|
-
toolChoice,
|
|
911
|
-
modelId
|
|
912
|
-
}) {
|
|
913
|
-
var _a, _b;
|
|
914
|
-
tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
|
|
915
|
-
const toolWarnings = [];
|
|
916
|
-
const isLatest = [
|
|
917
|
-
"gemini-flash-latest",
|
|
918
|
-
"gemini-flash-lite-latest",
|
|
919
|
-
"gemini-pro-latest"
|
|
920
|
-
].some((id) => id === modelId);
|
|
921
|
-
const isGemini2orNewer = modelId.includes("gemini-2") || modelId.includes("gemini-3") || modelId.includes("nano-banana") || isLatest;
|
|
922
|
-
const isGemini3orNewer = modelId.includes("gemini-3");
|
|
923
|
-
const supportsFileSearch = modelId.includes("gemini-2.5") || modelId.includes("gemini-3");
|
|
924
|
-
if (tools == null) {
|
|
925
|
-
return { tools: void 0, toolConfig: void 0, toolWarnings };
|
|
926
|
-
}
|
|
927
|
-
const hasFunctionTools = tools.some((tool) => tool.type === "function");
|
|
928
|
-
const hasProviderTools = tools.some((tool) => tool.type === "provider");
|
|
929
|
-
if (hasFunctionTools && hasProviderTools && !isGemini3orNewer) {
|
|
930
|
-
toolWarnings.push({
|
|
931
|
-
type: "unsupported",
|
|
932
|
-
feature: `combination of function and provider-defined tools`
|
|
933
|
-
});
|
|
934
|
-
}
|
|
935
|
-
if (hasProviderTools) {
|
|
936
|
-
const googleTools2 = [];
|
|
937
|
-
const ProviderTools = tools.filter((tool) => tool.type === "provider");
|
|
938
|
-
ProviderTools.forEach((tool) => {
|
|
939
|
-
switch (tool.id) {
|
|
940
|
-
case "google.google_search":
|
|
941
|
-
if (isGemini2orNewer) {
|
|
942
|
-
googleTools2.push({ googleSearch: { ...tool.args } });
|
|
943
|
-
} else {
|
|
944
|
-
toolWarnings.push({
|
|
945
|
-
type: "unsupported",
|
|
946
|
-
feature: `provider-defined tool ${tool.id}`,
|
|
947
|
-
details: "Google Search requires Gemini 2.0 or newer."
|
|
948
|
-
});
|
|
949
|
-
}
|
|
950
|
-
break;
|
|
951
|
-
case "google.enterprise_web_search":
|
|
952
|
-
if (isGemini2orNewer) {
|
|
953
|
-
googleTools2.push({ enterpriseWebSearch: {} });
|
|
954
|
-
} else {
|
|
955
|
-
toolWarnings.push({
|
|
956
|
-
type: "unsupported",
|
|
957
|
-
feature: `provider-defined tool ${tool.id}`,
|
|
958
|
-
details: "Enterprise Web Search requires Gemini 2.0 or newer."
|
|
959
|
-
});
|
|
960
|
-
}
|
|
961
|
-
break;
|
|
962
|
-
case "google.url_context":
|
|
963
|
-
if (isGemini2orNewer) {
|
|
964
|
-
googleTools2.push({ urlContext: {} });
|
|
965
|
-
} else {
|
|
966
|
-
toolWarnings.push({
|
|
967
|
-
type: "unsupported",
|
|
968
|
-
feature: `provider-defined tool ${tool.id}`,
|
|
969
|
-
details: "The URL context tool is not supported with other Gemini models than Gemini 2."
|
|
970
|
-
});
|
|
971
|
-
}
|
|
972
|
-
break;
|
|
973
|
-
case "google.code_execution":
|
|
974
|
-
if (isGemini2orNewer) {
|
|
975
|
-
googleTools2.push({ codeExecution: {} });
|
|
976
|
-
} else {
|
|
977
|
-
toolWarnings.push({
|
|
978
|
-
type: "unsupported",
|
|
979
|
-
feature: `provider-defined tool ${tool.id}`,
|
|
980
|
-
details: "The code execution tool is not supported with other Gemini models than Gemini 2."
|
|
981
|
-
});
|
|
982
|
-
}
|
|
983
|
-
break;
|
|
984
|
-
case "google.file_search":
|
|
985
|
-
if (supportsFileSearch) {
|
|
986
|
-
googleTools2.push({ fileSearch: { ...tool.args } });
|
|
987
|
-
} else {
|
|
988
|
-
toolWarnings.push({
|
|
989
|
-
type: "unsupported",
|
|
990
|
-
feature: `provider-defined tool ${tool.id}`,
|
|
991
|
-
details: "The file search tool is only supported with Gemini 2.5 models and Gemini 3 models."
|
|
992
|
-
});
|
|
993
|
-
}
|
|
994
|
-
break;
|
|
995
|
-
case "google.vertex_rag_store":
|
|
996
|
-
if (isGemini2orNewer) {
|
|
997
|
-
googleTools2.push({
|
|
998
|
-
retrieval: {
|
|
999
|
-
vertex_rag_store: {
|
|
1000
|
-
rag_resources: {
|
|
1001
|
-
rag_corpus: tool.args.ragCorpus
|
|
1002
|
-
},
|
|
1003
|
-
similarity_top_k: tool.args.topK
|
|
1004
|
-
}
|
|
1005
|
-
}
|
|
1006
|
-
});
|
|
1007
|
-
} else {
|
|
1008
|
-
toolWarnings.push({
|
|
1009
|
-
type: "unsupported",
|
|
1010
|
-
feature: `provider-defined tool ${tool.id}`,
|
|
1011
|
-
details: "The RAG store tool is not supported with other Gemini models than Gemini 2."
|
|
1012
|
-
});
|
|
1013
|
-
}
|
|
1014
|
-
break;
|
|
1015
|
-
case "google.google_maps":
|
|
1016
|
-
if (isGemini2orNewer) {
|
|
1017
|
-
googleTools2.push({ googleMaps: {} });
|
|
1018
|
-
} else {
|
|
1019
|
-
toolWarnings.push({
|
|
1020
|
-
type: "unsupported",
|
|
1021
|
-
feature: `provider-defined tool ${tool.id}`,
|
|
1022
|
-
details: "The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."
|
|
1023
|
-
});
|
|
1024
|
-
}
|
|
1025
|
-
break;
|
|
1026
|
-
default:
|
|
1027
|
-
toolWarnings.push({
|
|
1028
|
-
type: "unsupported",
|
|
1029
|
-
feature: `provider-defined tool ${tool.id}`
|
|
1030
|
-
});
|
|
1031
|
-
break;
|
|
1032
|
-
}
|
|
1033
|
-
});
|
|
1034
|
-
if (hasFunctionTools && isGemini3orNewer && googleTools2.length > 0) {
|
|
1035
|
-
const functionDeclarations2 = [];
|
|
1036
|
-
for (const tool of tools) {
|
|
1037
|
-
if (tool.type === "function") {
|
|
1038
|
-
functionDeclarations2.push({
|
|
1039
|
-
name: tool.name,
|
|
1040
|
-
description: (_a = tool.description) != null ? _a : "",
|
|
1041
|
-
parameters: convertJSONSchemaToOpenAPISchema(tool.inputSchema)
|
|
1042
|
-
});
|
|
1043
|
-
}
|
|
1044
|
-
}
|
|
1045
|
-
const combinedToolConfig = {
|
|
1046
|
-
functionCallingConfig: { mode: "VALIDATED" },
|
|
1047
|
-
includeServerSideToolInvocations: true
|
|
1048
|
-
};
|
|
1049
|
-
if (toolChoice != null) {
|
|
1050
|
-
switch (toolChoice.type) {
|
|
1051
|
-
case "auto":
|
|
1052
|
-
break;
|
|
1053
|
-
case "none":
|
|
1054
|
-
combinedToolConfig.functionCallingConfig = { mode: "NONE" };
|
|
1055
|
-
break;
|
|
1056
|
-
case "required":
|
|
1057
|
-
combinedToolConfig.functionCallingConfig = { mode: "ANY" };
|
|
1058
|
-
break;
|
|
1059
|
-
case "tool":
|
|
1060
|
-
combinedToolConfig.functionCallingConfig = {
|
|
1061
|
-
mode: "ANY",
|
|
1062
|
-
allowedFunctionNames: [toolChoice.toolName]
|
|
1063
|
-
};
|
|
1064
|
-
break;
|
|
1065
|
-
}
|
|
1066
|
-
}
|
|
1067
|
-
return {
|
|
1068
|
-
tools: [...googleTools2, { functionDeclarations: functionDeclarations2 }],
|
|
1069
|
-
toolConfig: combinedToolConfig,
|
|
1070
|
-
toolWarnings
|
|
1071
|
-
};
|
|
1072
|
-
}
|
|
1073
|
-
return {
|
|
1074
|
-
tools: googleTools2.length > 0 ? googleTools2 : void 0,
|
|
1075
|
-
toolConfig: void 0,
|
|
1076
|
-
toolWarnings
|
|
1077
|
-
};
|
|
1078
|
-
}
|
|
1079
|
-
const functionDeclarations = [];
|
|
1080
|
-
let hasStrictTools = false;
|
|
1081
|
-
for (const tool of tools) {
|
|
1082
|
-
switch (tool.type) {
|
|
1083
|
-
case "function":
|
|
1084
|
-
functionDeclarations.push({
|
|
1085
|
-
name: tool.name,
|
|
1086
|
-
description: (_b = tool.description) != null ? _b : "",
|
|
1087
|
-
parameters: convertJSONSchemaToOpenAPISchema(tool.inputSchema)
|
|
1088
|
-
});
|
|
1089
|
-
if (tool.strict === true) {
|
|
1090
|
-
hasStrictTools = true;
|
|
1091
|
-
}
|
|
1092
|
-
break;
|
|
1093
|
-
default:
|
|
1094
|
-
toolWarnings.push({
|
|
1095
|
-
type: "unsupported",
|
|
1096
|
-
feature: `function tool ${tool.name}`
|
|
1097
|
-
});
|
|
1098
|
-
break;
|
|
1099
|
-
}
|
|
1100
|
-
}
|
|
1101
|
-
if (toolChoice == null) {
|
|
1102
|
-
return {
|
|
1103
|
-
tools: [{ functionDeclarations }],
|
|
1104
|
-
toolConfig: hasStrictTools ? { functionCallingConfig: { mode: "VALIDATED" } } : void 0,
|
|
1105
|
-
toolWarnings
|
|
1106
|
-
};
|
|
1107
|
-
}
|
|
1108
|
-
const type = toolChoice.type;
|
|
1109
|
-
switch (type) {
|
|
1110
|
-
case "auto":
|
|
1111
|
-
return {
|
|
1112
|
-
tools: [{ functionDeclarations }],
|
|
1113
|
-
toolConfig: {
|
|
1114
|
-
functionCallingConfig: {
|
|
1115
|
-
mode: hasStrictTools ? "VALIDATED" : "AUTO"
|
|
1116
|
-
}
|
|
1117
|
-
},
|
|
1118
|
-
toolWarnings
|
|
1119
|
-
};
|
|
1120
|
-
case "none":
|
|
1121
|
-
return {
|
|
1122
|
-
tools: [{ functionDeclarations }],
|
|
1123
|
-
toolConfig: { functionCallingConfig: { mode: "NONE" } },
|
|
1124
|
-
toolWarnings
|
|
1125
|
-
};
|
|
1126
|
-
case "required":
|
|
1127
|
-
return {
|
|
1128
|
-
tools: [{ functionDeclarations }],
|
|
1129
|
-
toolConfig: {
|
|
1130
|
-
functionCallingConfig: {
|
|
1131
|
-
mode: hasStrictTools ? "VALIDATED" : "ANY"
|
|
1132
|
-
}
|
|
1133
|
-
},
|
|
1134
|
-
toolWarnings
|
|
1135
|
-
};
|
|
1136
|
-
case "tool":
|
|
1137
|
-
return {
|
|
1138
|
-
tools: [{ functionDeclarations }],
|
|
1139
|
-
toolConfig: {
|
|
1140
|
-
functionCallingConfig: {
|
|
1141
|
-
mode: hasStrictTools ? "VALIDATED" : "ANY",
|
|
1142
|
-
allowedFunctionNames: [toolChoice.toolName]
|
|
1143
|
-
}
|
|
1144
|
-
},
|
|
1145
|
-
toolWarnings
|
|
1146
|
-
};
|
|
1147
|
-
default: {
|
|
1148
|
-
const _exhaustiveCheck = type;
|
|
1149
|
-
throw new UnsupportedFunctionalityError2({
|
|
1150
|
-
functionality: `tool choice type: ${_exhaustiveCheck}`
|
|
1151
|
-
});
|
|
1152
|
-
}
|
|
1153
|
-
}
|
|
1154
|
-
}
|
|
1155
|
-
|
|
1156
|
-
// src/google-json-accumulator.ts
|
|
1157
|
-
var GoogleJSONAccumulator = class {
|
|
1158
|
-
constructor() {
|
|
1159
|
-
this.accumulatedArgs = {};
|
|
1160
|
-
this.jsonText = "";
|
|
1161
|
-
/**
|
|
1162
|
-
* Stack representing the currently "open" containers in the JSON output.
|
|
1163
|
-
* Entry 0 is always the root `{` object once the first value is written.
|
|
1164
|
-
*/
|
|
1165
|
-
this.pathStack = [];
|
|
1166
|
-
/**
|
|
1167
|
-
* Whether a string value is currently "open" (willContinue was true),
|
|
1168
|
-
* meaning the closing quote has not yet been emitted.
|
|
1169
|
-
*/
|
|
1170
|
-
this.stringOpen = false;
|
|
1171
|
-
}
|
|
1172
|
-
/**
|
|
1173
|
-
* Input: [{jsonPath:"$.brightness",numberValue:50}]
|
|
1174
|
-
* Output: { currentJSON:{brightness:50}, textDelta:'{"brightness":50' }
|
|
1175
|
-
*/
|
|
1176
|
-
processPartialArgs(partialArgs) {
|
|
1177
|
-
let delta = "";
|
|
1178
|
-
for (const arg of partialArgs) {
|
|
1179
|
-
const rawPath = arg.jsonPath.replace(/^\$\./, "");
|
|
1180
|
-
if (!rawPath) continue;
|
|
1181
|
-
const segments = parsePath(rawPath);
|
|
1182
|
-
const existingValue = getNestedValue(this.accumulatedArgs, segments);
|
|
1183
|
-
const isStringContinuation = arg.stringValue != null && existingValue !== void 0;
|
|
1184
|
-
if (isStringContinuation) {
|
|
1185
|
-
const escaped = JSON.stringify(arg.stringValue).slice(1, -1);
|
|
1186
|
-
setNestedValue(
|
|
1187
|
-
this.accumulatedArgs,
|
|
1188
|
-
segments,
|
|
1189
|
-
existingValue + arg.stringValue
|
|
1190
|
-
);
|
|
1191
|
-
delta += escaped;
|
|
1192
|
-
continue;
|
|
1193
|
-
}
|
|
1194
|
-
const resolved = resolvePartialArgValue(arg);
|
|
1195
|
-
if (resolved == null) continue;
|
|
1196
|
-
setNestedValue(this.accumulatedArgs, segments, resolved.value);
|
|
1197
|
-
delta += this.emitNavigationTo(segments, arg, resolved.json);
|
|
1198
|
-
}
|
|
1199
|
-
this.jsonText += delta;
|
|
1200
|
-
return {
|
|
1201
|
-
currentJSON: this.accumulatedArgs,
|
|
1202
|
-
textDelta: delta
|
|
1203
|
-
};
|
|
1204
|
-
}
|
|
1205
|
-
/**
|
|
1206
|
-
* Input: jsonText='{"brightness":50', accumulatedArgs={brightness:50}
|
|
1207
|
-
* Output: { finalJSON:'{"brightness":50}', closingDelta:'}' }
|
|
1208
|
-
*/
|
|
1209
|
-
finalize() {
|
|
1210
|
-
const finalArgs = JSON.stringify(this.accumulatedArgs);
|
|
1211
|
-
const closingDelta = finalArgs.slice(this.jsonText.length);
|
|
1212
|
-
return { finalJSON: finalArgs, closingDelta };
|
|
1213
|
-
}
|
|
1214
|
-
/**
|
|
1215
|
-
* Input: pathStack=[] (first call) or pathStack=[root,...] (subsequent calls)
|
|
1216
|
-
* Output: '{' (first call) or '' (subsequent calls)
|
|
1217
|
-
*/
|
|
1218
|
-
ensureRoot() {
|
|
1219
|
-
if (this.pathStack.length === 0) {
|
|
1220
|
-
this.pathStack.push({ segment: "", isArray: false, childCount: 0 });
|
|
1221
|
-
return "{";
|
|
1222
|
-
}
|
|
1223
|
-
return "";
|
|
1224
|
-
}
|
|
1225
|
-
/**
|
|
1226
|
-
* Emits the JSON text fragment needed to navigate from the current open
|
|
1227
|
-
* path to the new leaf at `targetSegments`, then writes the value.
|
|
1228
|
-
*
|
|
1229
|
-
* Input: targetSegments=["recipe","name"], arg={jsonPath:"$.recipe.name",stringValue:"Lasagna"}, valueJson='"Lasagna"'
|
|
1230
|
-
* Output: '{"recipe":{"name":"Lasagna"'
|
|
1231
|
-
*/
|
|
1232
|
-
emitNavigationTo(targetSegments, arg, valueJson) {
|
|
1233
|
-
let fragment = "";
|
|
1234
|
-
if (this.stringOpen) {
|
|
1235
|
-
fragment += '"';
|
|
1236
|
-
this.stringOpen = false;
|
|
1237
|
-
}
|
|
1238
|
-
fragment += this.ensureRoot();
|
|
1239
|
-
const targetContainerSegments = targetSegments.slice(0, -1);
|
|
1240
|
-
const leafSegment = targetSegments[targetSegments.length - 1];
|
|
1241
|
-
const commonDepth = this.findCommonStackDepth(targetContainerSegments);
|
|
1242
|
-
fragment += this.closeDownTo(commonDepth);
|
|
1243
|
-
fragment += this.openDownTo(targetContainerSegments, leafSegment);
|
|
1244
|
-
fragment += this.emitLeaf(leafSegment, arg, valueJson);
|
|
1245
|
-
return fragment;
|
|
1246
|
-
}
|
|
1247
|
-
/**
|
|
1248
|
-
* Returns the stack depth to preserve when navigating to a new target
|
|
1249
|
-
* container path. Always >= 1 (the root is never popped).
|
|
1250
|
-
*
|
|
1251
|
-
* Input: stack=[root,"recipe","ingredients",0], target=["recipe","ingredients",1]
|
|
1252
|
-
* Output: 3 (keep root+"recipe"+"ingredients")
|
|
1253
|
-
*/
|
|
1254
|
-
findCommonStackDepth(targetContainer) {
|
|
1255
|
-
const maxDepth = Math.min(
|
|
1256
|
-
this.pathStack.length - 1,
|
|
1257
|
-
targetContainer.length
|
|
1258
|
-
);
|
|
1259
|
-
let common = 0;
|
|
1260
|
-
for (let i = 0; i < maxDepth; i++) {
|
|
1261
|
-
if (this.pathStack[i + 1].segment === targetContainer[i]) {
|
|
1262
|
-
common++;
|
|
1263
|
-
} else {
|
|
1264
|
-
break;
|
|
1265
|
-
}
|
|
1266
|
-
}
|
|
1267
|
-
return common + 1;
|
|
1268
|
-
}
|
|
1269
|
-
/**
|
|
1270
|
-
* Closes containers from the current stack depth back down to `targetDepth`.
|
|
1271
|
-
*
|
|
1272
|
-
* Input: this.pathStack=[root,"recipe","ingredients",0], targetDepth=3
|
|
1273
|
-
* Output: '}'
|
|
1274
|
-
*/
|
|
1275
|
-
closeDownTo(targetDepth) {
|
|
1276
|
-
let fragment = "";
|
|
1277
|
-
while (this.pathStack.length > targetDepth) {
|
|
1278
|
-
const entry = this.pathStack.pop();
|
|
1279
|
-
fragment += entry.isArray ? "]" : "}";
|
|
1280
|
-
}
|
|
1281
|
-
return fragment;
|
|
1282
|
-
}
|
|
1283
|
-
/**
|
|
1284
|
-
* Opens containers from the current stack depth down to the full target
|
|
1285
|
-
* container path, emitting opening `{`, `[`, keys, and commas as needed.
|
|
1286
|
-
* `leafSegment` is used to determine if the innermost container is an array.
|
|
1287
|
-
*
|
|
1288
|
-
* Input: this.pathStack=[root], targetContainer=["recipe","ingredients"], leafSegment=0
|
|
1289
|
-
* Output: '"recipe":{"ingredients":['
|
|
1290
|
-
*/
|
|
1291
|
-
openDownTo(targetContainer, leafSegment) {
|
|
1292
|
-
let fragment = "";
|
|
1293
|
-
const startIdx = this.pathStack.length - 1;
|
|
1294
|
-
for (let i = startIdx; i < targetContainer.length; i++) {
|
|
1295
|
-
const seg = targetContainer[i];
|
|
1296
|
-
const parentEntry = this.pathStack[this.pathStack.length - 1];
|
|
1297
|
-
if (parentEntry.childCount > 0) {
|
|
1298
|
-
fragment += ",";
|
|
1299
|
-
}
|
|
1300
|
-
parentEntry.childCount++;
|
|
1301
|
-
if (typeof seg === "string") {
|
|
1302
|
-
fragment += `${JSON.stringify(seg)}:`;
|
|
1303
|
-
}
|
|
1304
|
-
const childSeg = i + 1 < targetContainer.length ? targetContainer[i + 1] : leafSegment;
|
|
1305
|
-
const isArray = typeof childSeg === "number";
|
|
1306
|
-
fragment += isArray ? "[" : "{";
|
|
1307
|
-
this.pathStack.push({ segment: seg, isArray, childCount: 0 });
|
|
1308
|
-
}
|
|
1309
|
-
return fragment;
|
|
1310
|
-
}
|
|
1311
|
-
/**
|
|
1312
|
-
* Emits the comma, key, and value for a leaf entry in the current container.
|
|
1313
|
-
*
|
|
1314
|
-
* Input: leafSegment="name", arg={stringValue:"Lasagna"}, valueJson='"Lasagna"'
|
|
1315
|
-
* Output: '"name":"Lasagna"' (or ',"name":"Lasagna"' if container.childCount > 0)
|
|
1316
|
-
*/
|
|
1317
|
-
emitLeaf(leafSegment, arg, valueJson) {
|
|
1318
|
-
let fragment = "";
|
|
1319
|
-
const container = this.pathStack[this.pathStack.length - 1];
|
|
1320
|
-
if (container.childCount > 0) {
|
|
1321
|
-
fragment += ",";
|
|
1322
|
-
}
|
|
1323
|
-
container.childCount++;
|
|
1324
|
-
if (typeof leafSegment === "string") {
|
|
1325
|
-
fragment += `${JSON.stringify(leafSegment)}:`;
|
|
1326
|
-
}
|
|
1327
|
-
if (arg.stringValue != null && arg.willContinue) {
|
|
1328
|
-
fragment += valueJson.slice(0, -1);
|
|
1329
|
-
this.stringOpen = true;
|
|
1330
|
-
} else {
|
|
1331
|
-
fragment += valueJson;
|
|
1332
|
-
}
|
|
1333
|
-
return fragment;
|
|
1334
|
-
}
|
|
1335
|
-
};
|
|
1336
|
-
function parsePath(rawPath) {
|
|
1337
|
-
const segments = [];
|
|
1338
|
-
for (const part of rawPath.split(".")) {
|
|
1339
|
-
const bracketIdx = part.indexOf("[");
|
|
1340
|
-
if (bracketIdx === -1) {
|
|
1341
|
-
segments.push(part);
|
|
1342
|
-
} else {
|
|
1343
|
-
if (bracketIdx > 0) segments.push(part.slice(0, bracketIdx));
|
|
1344
|
-
for (const m of part.matchAll(/\[(\d+)\]/g)) {
|
|
1345
|
-
segments.push(parseInt(m[1], 10));
|
|
1346
|
-
}
|
|
1347
|
-
}
|
|
1348
|
-
}
|
|
1349
|
-
return segments;
|
|
1350
|
-
}
|
|
1351
|
-
function getNestedValue(obj, segments) {
|
|
1352
|
-
let current = obj;
|
|
1353
|
-
for (const seg of segments) {
|
|
1354
|
-
if (current == null || typeof current !== "object") return void 0;
|
|
1355
|
-
current = current[seg];
|
|
1356
|
-
}
|
|
1357
|
-
return current;
|
|
1358
|
-
}
|
|
1359
|
-
function setNestedValue(obj, segments, value) {
|
|
1360
|
-
let current = obj;
|
|
1361
|
-
for (let i = 0; i < segments.length - 1; i++) {
|
|
1362
|
-
const seg = segments[i];
|
|
1363
|
-
const nextSeg = segments[i + 1];
|
|
1364
|
-
if (current[seg] == null) {
|
|
1365
|
-
current[seg] = typeof nextSeg === "number" ? [] : {};
|
|
1366
|
-
}
|
|
1367
|
-
current = current[seg];
|
|
1368
|
-
}
|
|
1369
|
-
current[segments[segments.length - 1]] = value;
|
|
1370
|
-
}
|
|
1371
|
-
function resolvePartialArgValue(arg) {
|
|
1372
|
-
var _a, _b;
|
|
1373
|
-
const value = (_b = (_a = arg.stringValue) != null ? _a : arg.numberValue) != null ? _b : arg.boolValue;
|
|
1374
|
-
if (value != null) return { value, json: JSON.stringify(value) };
|
|
1375
|
-
if ("nullValue" in arg) return { value: null, json: "null" };
|
|
1376
|
-
return void 0;
|
|
1377
|
-
}
|
|
1378
|
-
|
|
1379
|
-
// src/map-google-generative-ai-finish-reason.ts
|
|
1380
|
-
function mapGoogleGenerativeAIFinishReason({
|
|
1381
|
-
finishReason,
|
|
1382
|
-
hasToolCalls
|
|
1383
|
-
}) {
|
|
1384
|
-
switch (finishReason) {
|
|
1385
|
-
case "STOP":
|
|
1386
|
-
return hasToolCalls ? "tool-calls" : "stop";
|
|
1387
|
-
case "MAX_TOKENS":
|
|
1388
|
-
return "length";
|
|
1389
|
-
case "IMAGE_SAFETY":
|
|
1390
|
-
case "RECITATION":
|
|
1391
|
-
case "SAFETY":
|
|
1392
|
-
case "BLOCKLIST":
|
|
1393
|
-
case "PROHIBITED_CONTENT":
|
|
1394
|
-
case "SPII":
|
|
1395
|
-
return "content-filter";
|
|
1396
|
-
case "MALFORMED_FUNCTION_CALL":
|
|
1397
|
-
return "error";
|
|
1398
|
-
case "FINISH_REASON_UNSPECIFIED":
|
|
1399
|
-
case "OTHER":
|
|
1400
|
-
default:
|
|
1401
|
-
return "other";
|
|
1402
|
-
}
|
|
1403
|
-
}
|
|
1404
|
-
|
|
1405
|
-
// src/google-generative-ai-language-model.ts
|
|
1406
|
-
var GoogleGenerativeAILanguageModel = class {
|
|
1407
|
-
constructor(modelId, config) {
|
|
1408
|
-
this.specificationVersion = "v4";
|
|
1409
|
-
var _a;
|
|
1410
|
-
this.modelId = modelId;
|
|
1411
|
-
this.config = config;
|
|
1412
|
-
this.generateId = (_a = config.generateId) != null ? _a : generateId;
|
|
1413
|
-
}
|
|
1414
|
-
get provider() {
|
|
1415
|
-
return this.config.provider;
|
|
1416
|
-
}
|
|
1417
|
-
get supportedUrls() {
|
|
1418
|
-
var _a, _b, _c;
|
|
1419
|
-
return (_c = (_b = (_a = this.config).supportedUrls) == null ? void 0 : _b.call(_a)) != null ? _c : {};
|
|
1420
|
-
}
|
|
1421
|
-
async getArgs({
|
|
1422
|
-
prompt,
|
|
1423
|
-
maxOutputTokens,
|
|
1424
|
-
temperature,
|
|
1425
|
-
topP,
|
|
1426
|
-
topK,
|
|
1427
|
-
frequencyPenalty,
|
|
1428
|
-
presencePenalty,
|
|
1429
|
-
stopSequences,
|
|
1430
|
-
responseFormat,
|
|
1431
|
-
seed,
|
|
1432
|
-
tools,
|
|
1433
|
-
toolChoice,
|
|
1434
|
-
reasoning,
|
|
1435
|
-
providerOptions
|
|
1436
|
-
}, { isStreaming = false } = {}) {
|
|
1437
|
-
var _a, _b;
|
|
1438
|
-
const warnings = [];
|
|
1439
|
-
const providerOptionsName = this.config.provider.includes("vertex") ? "vertex" : "google";
|
|
1440
|
-
let googleOptions = await parseProviderOptions2({
|
|
1441
|
-
provider: providerOptionsName,
|
|
1442
|
-
providerOptions,
|
|
1443
|
-
schema: googleLanguageModelOptions
|
|
1444
|
-
});
|
|
1445
|
-
if (googleOptions == null && providerOptionsName !== "google") {
|
|
1446
|
-
googleOptions = await parseProviderOptions2({
|
|
1447
|
-
provider: "google",
|
|
1448
|
-
providerOptions,
|
|
1449
|
-
schema: googleLanguageModelOptions
|
|
1450
|
-
});
|
|
1451
|
-
}
|
|
1452
|
-
const isVertexProvider = this.config.provider.startsWith("google.vertex.");
|
|
1453
|
-
if ((tools == null ? void 0 : tools.some(
|
|
1454
|
-
(tool) => tool.type === "provider" && tool.id === "google.vertex_rag_store"
|
|
1455
|
-
)) && !isVertexProvider) {
|
|
1456
|
-
warnings.push({
|
|
1457
|
-
type: "other",
|
|
1458
|
-
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}).`
|
|
1459
|
-
});
|
|
1460
|
-
}
|
|
1461
|
-
if ((googleOptions == null ? void 0 : googleOptions.streamFunctionCallArguments) && !isVertexProvider) {
|
|
1462
|
-
warnings.push({
|
|
1463
|
-
type: "other",
|
|
1464
|
-
message: `'streamFunctionCallArguments' is only supported on the Vertex AI API and will be ignored with the current Google provider (${this.config.provider}). See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc`
|
|
1465
|
-
});
|
|
1466
|
-
}
|
|
1467
|
-
const isGemmaModel = this.modelId.toLowerCase().startsWith("gemma-");
|
|
1468
|
-
const supportsFunctionResponseParts = this.modelId.startsWith("gemini-3");
|
|
1469
|
-
const { contents, systemInstruction } = convertToGoogleGenerativeAIMessages(
|
|
1470
|
-
prompt,
|
|
1471
|
-
{
|
|
1472
|
-
isGemmaModel,
|
|
1473
|
-
providerOptionsName,
|
|
1474
|
-
supportsFunctionResponseParts
|
|
1475
|
-
}
|
|
1476
|
-
);
|
|
1477
|
-
const {
|
|
1478
|
-
tools: googleTools2,
|
|
1479
|
-
toolConfig: googleToolConfig,
|
|
1480
|
-
toolWarnings
|
|
1481
|
-
} = prepareTools({
|
|
1482
|
-
tools,
|
|
1483
|
-
toolChoice,
|
|
1484
|
-
modelId: this.modelId
|
|
1485
|
-
});
|
|
1486
|
-
const resolvedThinking = resolveThinkingConfig({
|
|
1487
|
-
reasoning,
|
|
1488
|
-
modelId: this.modelId,
|
|
1489
|
-
warnings
|
|
1490
|
-
});
|
|
1491
|
-
const thinkingConfig = (googleOptions == null ? void 0 : googleOptions.thinkingConfig) || resolvedThinking ? { ...resolvedThinking, ...googleOptions == null ? void 0 : googleOptions.thinkingConfig } : void 0;
|
|
1492
|
-
const streamFunctionCallArguments = isStreaming && isVertexProvider ? (_a = googleOptions == null ? void 0 : googleOptions.streamFunctionCallArguments) != null ? _a : false : void 0;
|
|
1493
|
-
const toolConfig = googleToolConfig || streamFunctionCallArguments || (googleOptions == null ? void 0 : googleOptions.retrievalConfig) ? {
|
|
1494
|
-
...googleToolConfig,
|
|
1495
|
-
...streamFunctionCallArguments && {
|
|
1496
|
-
functionCallingConfig: {
|
|
1497
|
-
...googleToolConfig == null ? void 0 : googleToolConfig.functionCallingConfig,
|
|
1498
|
-
streamFunctionCallArguments: true
|
|
1499
|
-
}
|
|
1500
|
-
},
|
|
1501
|
-
...(googleOptions == null ? void 0 : googleOptions.retrievalConfig) && {
|
|
1502
|
-
retrievalConfig: googleOptions.retrievalConfig
|
|
1503
|
-
}
|
|
1504
|
-
} : void 0;
|
|
1505
|
-
return {
|
|
1506
|
-
args: {
|
|
1507
|
-
generationConfig: {
|
|
1508
|
-
// standardized settings:
|
|
1509
|
-
maxOutputTokens,
|
|
1510
|
-
temperature,
|
|
1511
|
-
topK,
|
|
1512
|
-
topP,
|
|
1513
|
-
frequencyPenalty,
|
|
1514
|
-
presencePenalty,
|
|
1515
|
-
stopSequences,
|
|
1516
|
-
seed,
|
|
1517
|
-
// response format:
|
|
1518
|
-
responseMimeType: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? "application/json" : void 0,
|
|
1519
|
-
responseSchema: (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && // Google GenAI does not support all OpenAPI Schema features,
|
|
1520
|
-
// so this is needed as an escape hatch:
|
|
1521
|
-
// TODO convert into provider option
|
|
1522
|
-
((_b = googleOptions == null ? void 0 : googleOptions.structuredOutputs) != null ? _b : true) ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : void 0,
|
|
1523
|
-
...(googleOptions == null ? void 0 : googleOptions.audioTimestamp) && {
|
|
1524
|
-
audioTimestamp: googleOptions.audioTimestamp
|
|
1525
|
-
},
|
|
1526
|
-
// provider options:
|
|
1527
|
-
responseModalities: googleOptions == null ? void 0 : googleOptions.responseModalities,
|
|
1528
|
-
thinkingConfig,
|
|
1529
|
-
...(googleOptions == null ? void 0 : googleOptions.mediaResolution) && {
|
|
1530
|
-
mediaResolution: googleOptions.mediaResolution
|
|
1531
|
-
},
|
|
1532
|
-
...(googleOptions == null ? void 0 : googleOptions.imageConfig) && {
|
|
1533
|
-
imageConfig: googleOptions.imageConfig
|
|
1534
|
-
}
|
|
1535
|
-
},
|
|
1536
|
-
contents,
|
|
1537
|
-
systemInstruction: isGemmaModel ? void 0 : systemInstruction,
|
|
1538
|
-
safetySettings: googleOptions == null ? void 0 : googleOptions.safetySettings,
|
|
1539
|
-
tools: googleTools2,
|
|
1540
|
-
toolConfig,
|
|
1541
|
-
cachedContent: googleOptions == null ? void 0 : googleOptions.cachedContent,
|
|
1542
|
-
labels: googleOptions == null ? void 0 : googleOptions.labels,
|
|
1543
|
-
serviceTier: googleOptions == null ? void 0 : googleOptions.serviceTier
|
|
1544
|
-
},
|
|
1545
|
-
warnings: [...warnings, ...toolWarnings],
|
|
1546
|
-
providerOptionsName
|
|
1547
|
-
};
|
|
1548
|
-
}
|
|
1549
|
-
async doGenerate(options) {
|
|
1550
|
-
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
|
|
1551
|
-
const { args, warnings, providerOptionsName } = await this.getArgs(options);
|
|
1552
|
-
const mergedHeaders = combineHeaders2(
|
|
1553
|
-
await resolve2(this.config.headers),
|
|
1554
|
-
options.headers
|
|
1555
|
-
);
|
|
1556
|
-
const {
|
|
1557
|
-
responseHeaders,
|
|
1558
|
-
value: response,
|
|
1559
|
-
rawValue: rawResponse
|
|
1560
|
-
} = await postJsonToApi2({
|
|
1561
|
-
url: `${this.config.baseURL}/${getModelPath(
|
|
1562
|
-
this.modelId
|
|
1563
|
-
)}:generateContent`,
|
|
1564
|
-
headers: mergedHeaders,
|
|
1565
|
-
body: args,
|
|
1566
|
-
failedResponseHandler: googleFailedResponseHandler,
|
|
1567
|
-
successfulResponseHandler: createJsonResponseHandler2(responseSchema),
|
|
1568
|
-
abortSignal: options.abortSignal,
|
|
1569
|
-
fetch: this.config.fetch
|
|
1570
|
-
});
|
|
1571
|
-
const candidate = response.candidates[0];
|
|
1572
|
-
const content = [];
|
|
1573
|
-
const parts = (_b = (_a = candidate.content) == null ? void 0 : _a.parts) != null ? _b : [];
|
|
1574
|
-
const usageMetadata = response.usageMetadata;
|
|
1575
|
-
let lastCodeExecutionToolCallId;
|
|
1576
|
-
let lastServerToolCallId;
|
|
1577
|
-
for (const part of parts) {
|
|
1578
|
-
if ("executableCode" in part && ((_c = part.executableCode) == null ? void 0 : _c.code)) {
|
|
1579
|
-
const toolCallId = this.config.generateId();
|
|
1580
|
-
lastCodeExecutionToolCallId = toolCallId;
|
|
1581
|
-
content.push({
|
|
1582
|
-
type: "tool-call",
|
|
1583
|
-
toolCallId,
|
|
1584
|
-
toolName: "code_execution",
|
|
1585
|
-
input: JSON.stringify(part.executableCode),
|
|
1586
|
-
providerExecuted: true
|
|
1587
|
-
});
|
|
1588
|
-
} else if ("codeExecutionResult" in part && part.codeExecutionResult) {
|
|
1589
|
-
content.push({
|
|
1590
|
-
type: "tool-result",
|
|
1591
|
-
// Assumes a result directly follows its corresponding call part.
|
|
1592
|
-
toolCallId: lastCodeExecutionToolCallId,
|
|
1593
|
-
toolName: "code_execution",
|
|
1594
|
-
result: {
|
|
1595
|
-
outcome: part.codeExecutionResult.outcome,
|
|
1596
|
-
output: (_d = part.codeExecutionResult.output) != null ? _d : ""
|
|
1597
|
-
}
|
|
1598
|
-
});
|
|
1599
|
-
lastCodeExecutionToolCallId = void 0;
|
|
1600
|
-
} else if ("text" in part && part.text != null) {
|
|
1601
|
-
const thoughtSignatureMetadata = part.thoughtSignature ? {
|
|
1602
|
-
[providerOptionsName]: {
|
|
1603
|
-
thoughtSignature: part.thoughtSignature
|
|
1604
|
-
}
|
|
1605
|
-
} : void 0;
|
|
1606
|
-
if (part.text.length === 0) {
|
|
1607
|
-
if (thoughtSignatureMetadata != null && content.length > 0) {
|
|
1608
|
-
const lastContent = content[content.length - 1];
|
|
1609
|
-
lastContent.providerMetadata = thoughtSignatureMetadata;
|
|
1610
|
-
}
|
|
1611
|
-
} else {
|
|
1612
|
-
content.push({
|
|
1613
|
-
type: part.thought === true ? "reasoning" : "text",
|
|
1614
|
-
text: part.text,
|
|
1615
|
-
providerMetadata: thoughtSignatureMetadata
|
|
1616
|
-
});
|
|
1617
|
-
}
|
|
1618
|
-
} else if ("functionCall" in part && part.functionCall.name != null && part.functionCall.args != null) {
|
|
1619
|
-
content.push({
|
|
1620
|
-
type: "tool-call",
|
|
1621
|
-
toolCallId: this.config.generateId(),
|
|
1622
|
-
toolName: part.functionCall.name,
|
|
1623
|
-
input: JSON.stringify(part.functionCall.args),
|
|
1624
|
-
providerMetadata: part.thoughtSignature ? {
|
|
1625
|
-
[providerOptionsName]: {
|
|
1626
|
-
thoughtSignature: part.thoughtSignature
|
|
1627
|
-
}
|
|
1628
|
-
} : void 0
|
|
1629
|
-
});
|
|
1630
|
-
} else if ("inlineData" in part) {
|
|
1631
|
-
const hasThought = part.thought === true;
|
|
1632
|
-
const hasThoughtSignature = !!part.thoughtSignature;
|
|
1633
|
-
content.push({
|
|
1634
|
-
type: hasThought ? "reasoning-file" : "file",
|
|
1635
|
-
data: part.inlineData.data,
|
|
1636
|
-
mediaType: part.inlineData.mimeType,
|
|
1637
|
-
providerMetadata: hasThoughtSignature ? {
|
|
1638
|
-
[providerOptionsName]: {
|
|
1639
|
-
thoughtSignature: part.thoughtSignature
|
|
1640
|
-
}
|
|
1641
|
-
} : void 0
|
|
1642
|
-
});
|
|
1643
|
-
} else if ("toolCall" in part && part.toolCall) {
|
|
1644
|
-
const toolCallId = (_e = part.toolCall.id) != null ? _e : this.config.generateId();
|
|
1645
|
-
lastServerToolCallId = toolCallId;
|
|
1646
|
-
content.push({
|
|
1647
|
-
type: "tool-call",
|
|
1648
|
-
toolCallId,
|
|
1649
|
-
toolName: `server:${part.toolCall.toolType}`,
|
|
1650
|
-
input: JSON.stringify((_f = part.toolCall.args) != null ? _f : {}),
|
|
1651
|
-
providerExecuted: true,
|
|
1652
|
-
dynamic: true,
|
|
1653
|
-
providerMetadata: part.thoughtSignature ? {
|
|
1654
|
-
[providerOptionsName]: {
|
|
1655
|
-
thoughtSignature: part.thoughtSignature,
|
|
1656
|
-
serverToolCallId: toolCallId,
|
|
1657
|
-
serverToolType: part.toolCall.toolType
|
|
1658
|
-
}
|
|
1659
|
-
} : {
|
|
1660
|
-
[providerOptionsName]: {
|
|
1661
|
-
serverToolCallId: toolCallId,
|
|
1662
|
-
serverToolType: part.toolCall.toolType
|
|
1663
|
-
}
|
|
1664
|
-
}
|
|
1665
|
-
});
|
|
1666
|
-
} else if ("toolResponse" in part && part.toolResponse) {
|
|
1667
|
-
const responseToolCallId = (_g = lastServerToolCallId != null ? lastServerToolCallId : part.toolResponse.id) != null ? _g : this.config.generateId();
|
|
1668
|
-
content.push({
|
|
1669
|
-
type: "tool-result",
|
|
1670
|
-
toolCallId: responseToolCallId,
|
|
1671
|
-
toolName: `server:${part.toolResponse.toolType}`,
|
|
1672
|
-
result: (_h = part.toolResponse.response) != null ? _h : {},
|
|
1673
|
-
providerMetadata: part.thoughtSignature ? {
|
|
1674
|
-
[providerOptionsName]: {
|
|
1675
|
-
thoughtSignature: part.thoughtSignature,
|
|
1676
|
-
serverToolCallId: responseToolCallId,
|
|
1677
|
-
serverToolType: part.toolResponse.toolType
|
|
1678
|
-
}
|
|
1679
|
-
} : {
|
|
1680
|
-
[providerOptionsName]: {
|
|
1681
|
-
serverToolCallId: responseToolCallId,
|
|
1682
|
-
serverToolType: part.toolResponse.toolType
|
|
1683
|
-
}
|
|
1684
|
-
}
|
|
1685
|
-
});
|
|
1686
|
-
lastServerToolCallId = void 0;
|
|
1687
|
-
}
|
|
1688
|
-
}
|
|
1689
|
-
const sources = (_i = extractSources({
|
|
1690
|
-
groundingMetadata: candidate.groundingMetadata,
|
|
1691
|
-
generateId: this.config.generateId
|
|
1692
|
-
})) != null ? _i : [];
|
|
1693
|
-
for (const source of sources) {
|
|
1694
|
-
content.push(source);
|
|
1695
|
-
}
|
|
1696
|
-
return {
|
|
1697
|
-
content,
|
|
1698
|
-
finishReason: {
|
|
1699
|
-
unified: mapGoogleGenerativeAIFinishReason({
|
|
1700
|
-
finishReason: candidate.finishReason,
|
|
1701
|
-
// Only count client-executed tool calls for finish reason determination.
|
|
1702
|
-
hasToolCalls: content.some(
|
|
1703
|
-
(part) => part.type === "tool-call" && !part.providerExecuted
|
|
1704
|
-
)
|
|
1705
|
-
}),
|
|
1706
|
-
raw: (_j = candidate.finishReason) != null ? _j : void 0
|
|
1707
|
-
},
|
|
1708
|
-
usage: convertGoogleGenerativeAIUsage(usageMetadata),
|
|
1709
|
-
warnings,
|
|
1710
|
-
providerMetadata: {
|
|
1711
|
-
[providerOptionsName]: {
|
|
1712
|
-
promptFeedback: (_k = response.promptFeedback) != null ? _k : null,
|
|
1713
|
-
groundingMetadata: (_l = candidate.groundingMetadata) != null ? _l : null,
|
|
1714
|
-
urlContextMetadata: (_m = candidate.urlContextMetadata) != null ? _m : null,
|
|
1715
|
-
safetyRatings: (_n = candidate.safetyRatings) != null ? _n : null,
|
|
1716
|
-
usageMetadata: usageMetadata != null ? usageMetadata : null,
|
|
1717
|
-
finishMessage: (_o = candidate.finishMessage) != null ? _o : null,
|
|
1718
|
-
serviceTier: (_p = response.serviceTier) != null ? _p : null
|
|
1719
|
-
}
|
|
1720
|
-
},
|
|
1721
|
-
request: { body: args },
|
|
1722
|
-
response: {
|
|
1723
|
-
// TODO timestamp, model id, id
|
|
1724
|
-
headers: responseHeaders,
|
|
1725
|
-
body: rawResponse
|
|
1726
|
-
}
|
|
1727
|
-
};
|
|
1728
|
-
}
|
|
1729
|
-
async doStream(options) {
|
|
1730
|
-
const { args, warnings, providerOptionsName } = await this.getArgs(
|
|
1731
|
-
options,
|
|
1732
|
-
{ isStreaming: true }
|
|
1733
|
-
);
|
|
1734
|
-
const headers = combineHeaders2(
|
|
1735
|
-
await resolve2(this.config.headers),
|
|
1736
|
-
options.headers
|
|
1737
|
-
);
|
|
1738
|
-
const { responseHeaders, value: response } = await postJsonToApi2({
|
|
1739
|
-
url: `${this.config.baseURL}/${getModelPath(
|
|
1740
|
-
this.modelId
|
|
1741
|
-
)}:streamGenerateContent?alt=sse`,
|
|
1742
|
-
headers,
|
|
1743
|
-
body: args,
|
|
1744
|
-
failedResponseHandler: googleFailedResponseHandler,
|
|
1745
|
-
successfulResponseHandler: createEventSourceResponseHandler(chunkSchema),
|
|
1746
|
-
abortSignal: options.abortSignal,
|
|
1747
|
-
fetch: this.config.fetch
|
|
1748
|
-
});
|
|
1749
|
-
let finishReason = {
|
|
1750
|
-
unified: "other",
|
|
1751
|
-
raw: void 0
|
|
1752
|
-
};
|
|
1753
|
-
let usage = void 0;
|
|
1754
|
-
let providerMetadata = void 0;
|
|
1755
|
-
let lastGroundingMetadata = null;
|
|
1756
|
-
let lastUrlContextMetadata = null;
|
|
1757
|
-
let serviceTier = null;
|
|
1758
|
-
const generateId3 = this.config.generateId;
|
|
1759
|
-
let hasToolCalls = false;
|
|
1760
|
-
let currentTextBlockId = null;
|
|
1761
|
-
let currentReasoningBlockId = null;
|
|
1762
|
-
let blockCounter = 0;
|
|
1763
|
-
const emittedSourceUrls = /* @__PURE__ */ new Set();
|
|
1764
|
-
let lastCodeExecutionToolCallId;
|
|
1765
|
-
let lastServerToolCallId;
|
|
1766
|
-
const activeStreamingToolCalls = [];
|
|
1767
|
-
return {
|
|
1768
|
-
stream: response.pipeThrough(
|
|
1769
|
-
new TransformStream({
|
|
1770
|
-
start(controller) {
|
|
1771
|
-
controller.enqueue({ type: "stream-start", warnings });
|
|
1772
|
-
},
|
|
1773
|
-
transform(chunk, controller) {
|
|
1774
|
-
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
|
|
1775
|
-
if (options.includeRawChunks) {
|
|
1776
|
-
controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
|
|
1777
|
-
}
|
|
1778
|
-
if (!chunk.success) {
|
|
1779
|
-
controller.enqueue({ type: "error", error: chunk.error });
|
|
1780
|
-
return;
|
|
1781
|
-
}
|
|
1782
|
-
const value = chunk.value;
|
|
1783
|
-
const usageMetadata = value.usageMetadata;
|
|
1784
|
-
if (usageMetadata != null) {
|
|
1785
|
-
usage = usageMetadata;
|
|
1786
|
-
}
|
|
1787
|
-
if (value.serviceTier != null) {
|
|
1788
|
-
serviceTier = value.serviceTier;
|
|
1789
|
-
}
|
|
1790
|
-
const candidate = (_a = value.candidates) == null ? void 0 : _a[0];
|
|
1791
|
-
if (candidate == null) {
|
|
1792
|
-
return;
|
|
1793
|
-
}
|
|
1794
|
-
const content = candidate.content;
|
|
1795
|
-
if (candidate.groundingMetadata != null) {
|
|
1796
|
-
lastGroundingMetadata = candidate.groundingMetadata;
|
|
1797
|
-
}
|
|
1798
|
-
if (candidate.urlContextMetadata != null) {
|
|
1799
|
-
lastUrlContextMetadata = candidate.urlContextMetadata;
|
|
1800
|
-
}
|
|
1801
|
-
const sources = extractSources({
|
|
1802
|
-
groundingMetadata: candidate.groundingMetadata,
|
|
1803
|
-
generateId: generateId3
|
|
1804
|
-
});
|
|
1805
|
-
if (sources != null) {
|
|
1806
|
-
for (const source of sources) {
|
|
1807
|
-
if (source.sourceType === "url" && !emittedSourceUrls.has(source.url)) {
|
|
1808
|
-
emittedSourceUrls.add(source.url);
|
|
1809
|
-
controller.enqueue(source);
|
|
1810
|
-
}
|
|
1811
|
-
}
|
|
1812
|
-
}
|
|
1813
|
-
if (content != null) {
|
|
1814
|
-
const parts = (_b = content.parts) != null ? _b : [];
|
|
1815
|
-
for (const part of parts) {
|
|
1816
|
-
if ("executableCode" in part && ((_c = part.executableCode) == null ? void 0 : _c.code)) {
|
|
1817
|
-
const toolCallId = generateId3();
|
|
1818
|
-
lastCodeExecutionToolCallId = toolCallId;
|
|
1819
|
-
controller.enqueue({
|
|
1820
|
-
type: "tool-call",
|
|
1821
|
-
toolCallId,
|
|
1822
|
-
toolName: "code_execution",
|
|
1823
|
-
input: JSON.stringify(part.executableCode),
|
|
1824
|
-
providerExecuted: true
|
|
1825
|
-
});
|
|
1826
|
-
} else if ("codeExecutionResult" in part && part.codeExecutionResult) {
|
|
1827
|
-
const toolCallId = lastCodeExecutionToolCallId;
|
|
1828
|
-
if (toolCallId) {
|
|
1829
|
-
controller.enqueue({
|
|
1830
|
-
type: "tool-result",
|
|
1831
|
-
toolCallId,
|
|
1832
|
-
toolName: "code_execution",
|
|
1833
|
-
result: {
|
|
1834
|
-
outcome: part.codeExecutionResult.outcome,
|
|
1835
|
-
output: (_d = part.codeExecutionResult.output) != null ? _d : ""
|
|
1836
|
-
}
|
|
1837
|
-
});
|
|
1838
|
-
lastCodeExecutionToolCallId = void 0;
|
|
1839
|
-
}
|
|
1840
|
-
} else if ("text" in part && part.text != null) {
|
|
1841
|
-
const thoughtSignatureMetadata = part.thoughtSignature ? {
|
|
1842
|
-
[providerOptionsName]: {
|
|
1843
|
-
thoughtSignature: part.thoughtSignature
|
|
1844
|
-
}
|
|
1845
|
-
} : void 0;
|
|
1846
|
-
if (part.text.length === 0) {
|
|
1847
|
-
if (thoughtSignatureMetadata != null && currentTextBlockId !== null) {
|
|
1848
|
-
controller.enqueue({
|
|
1849
|
-
type: "text-delta",
|
|
1850
|
-
id: currentTextBlockId,
|
|
1851
|
-
delta: "",
|
|
1852
|
-
providerMetadata: thoughtSignatureMetadata
|
|
1853
|
-
});
|
|
1854
|
-
}
|
|
1855
|
-
} else if (part.thought === true) {
|
|
1856
|
-
if (currentTextBlockId !== null) {
|
|
1857
|
-
controller.enqueue({
|
|
1858
|
-
type: "text-end",
|
|
1859
|
-
id: currentTextBlockId
|
|
1860
|
-
});
|
|
1861
|
-
currentTextBlockId = null;
|
|
1862
|
-
}
|
|
1863
|
-
if (currentReasoningBlockId === null) {
|
|
1864
|
-
currentReasoningBlockId = String(blockCounter++);
|
|
1865
|
-
controller.enqueue({
|
|
1866
|
-
type: "reasoning-start",
|
|
1867
|
-
id: currentReasoningBlockId,
|
|
1868
|
-
providerMetadata: thoughtSignatureMetadata
|
|
1869
|
-
});
|
|
1870
|
-
}
|
|
1871
|
-
controller.enqueue({
|
|
1872
|
-
type: "reasoning-delta",
|
|
1873
|
-
id: currentReasoningBlockId,
|
|
1874
|
-
delta: part.text,
|
|
1875
|
-
providerMetadata: thoughtSignatureMetadata
|
|
1876
|
-
});
|
|
1877
|
-
} else {
|
|
1878
|
-
if (currentReasoningBlockId !== null) {
|
|
1879
|
-
controller.enqueue({
|
|
1880
|
-
type: "reasoning-end",
|
|
1881
|
-
id: currentReasoningBlockId
|
|
1882
|
-
});
|
|
1883
|
-
currentReasoningBlockId = null;
|
|
1884
|
-
}
|
|
1885
|
-
if (currentTextBlockId === null) {
|
|
1886
|
-
currentTextBlockId = String(blockCounter++);
|
|
1887
|
-
controller.enqueue({
|
|
1888
|
-
type: "text-start",
|
|
1889
|
-
id: currentTextBlockId,
|
|
1890
|
-
providerMetadata: thoughtSignatureMetadata
|
|
1891
|
-
});
|
|
1892
|
-
}
|
|
1893
|
-
controller.enqueue({
|
|
1894
|
-
type: "text-delta",
|
|
1895
|
-
id: currentTextBlockId,
|
|
1896
|
-
delta: part.text,
|
|
1897
|
-
providerMetadata: thoughtSignatureMetadata
|
|
1898
|
-
});
|
|
1899
|
-
}
|
|
1900
|
-
} else if ("inlineData" in part) {
|
|
1901
|
-
if (currentTextBlockId !== null) {
|
|
1902
|
-
controller.enqueue({
|
|
1903
|
-
type: "text-end",
|
|
1904
|
-
id: currentTextBlockId
|
|
1905
|
-
});
|
|
1906
|
-
currentTextBlockId = null;
|
|
1907
|
-
}
|
|
1908
|
-
if (currentReasoningBlockId !== null) {
|
|
1909
|
-
controller.enqueue({
|
|
1910
|
-
type: "reasoning-end",
|
|
1911
|
-
id: currentReasoningBlockId
|
|
1912
|
-
});
|
|
1913
|
-
currentReasoningBlockId = null;
|
|
1914
|
-
}
|
|
1915
|
-
const hasThought = part.thought === true;
|
|
1916
|
-
const hasThoughtSignature = !!part.thoughtSignature;
|
|
1917
|
-
const fileMeta = hasThoughtSignature ? {
|
|
1918
|
-
[providerOptionsName]: {
|
|
1919
|
-
thoughtSignature: part.thoughtSignature
|
|
1920
|
-
}
|
|
1921
|
-
} : void 0;
|
|
1922
|
-
controller.enqueue({
|
|
1923
|
-
type: hasThought ? "reasoning-file" : "file",
|
|
1924
|
-
mediaType: part.inlineData.mimeType,
|
|
1925
|
-
data: part.inlineData.data,
|
|
1926
|
-
providerMetadata: fileMeta
|
|
1927
|
-
});
|
|
1928
|
-
} else if ("toolCall" in part && part.toolCall) {
|
|
1929
|
-
const toolCallId = (_e = part.toolCall.id) != null ? _e : generateId3();
|
|
1930
|
-
lastServerToolCallId = toolCallId;
|
|
1931
|
-
const serverMeta = {
|
|
1932
|
-
[providerOptionsName]: {
|
|
1933
|
-
...part.thoughtSignature ? { thoughtSignature: part.thoughtSignature } : {},
|
|
1934
|
-
serverToolCallId: toolCallId,
|
|
1935
|
-
serverToolType: part.toolCall.toolType
|
|
1936
|
-
}
|
|
1937
|
-
};
|
|
1938
|
-
controller.enqueue({
|
|
1939
|
-
type: "tool-call",
|
|
1940
|
-
toolCallId,
|
|
1941
|
-
toolName: `server:${part.toolCall.toolType}`,
|
|
1942
|
-
input: JSON.stringify((_f = part.toolCall.args) != null ? _f : {}),
|
|
1943
|
-
providerExecuted: true,
|
|
1944
|
-
dynamic: true,
|
|
1945
|
-
providerMetadata: serverMeta
|
|
1946
|
-
});
|
|
1947
|
-
} else if ("toolResponse" in part && part.toolResponse) {
|
|
1948
|
-
const responseToolCallId = (_g = lastServerToolCallId != null ? lastServerToolCallId : part.toolResponse.id) != null ? _g : generateId3();
|
|
1949
|
-
const serverMeta = {
|
|
1950
|
-
[providerOptionsName]: {
|
|
1951
|
-
...part.thoughtSignature ? { thoughtSignature: part.thoughtSignature } : {},
|
|
1952
|
-
serverToolCallId: responseToolCallId,
|
|
1953
|
-
serverToolType: part.toolResponse.toolType
|
|
1954
|
-
}
|
|
1955
|
-
};
|
|
1956
|
-
controller.enqueue({
|
|
1957
|
-
type: "tool-result",
|
|
1958
|
-
toolCallId: responseToolCallId,
|
|
1959
|
-
toolName: `server:${part.toolResponse.toolType}`,
|
|
1960
|
-
result: (_h = part.toolResponse.response) != null ? _h : {},
|
|
1961
|
-
providerMetadata: serverMeta
|
|
1962
|
-
});
|
|
1963
|
-
lastServerToolCallId = void 0;
|
|
1964
|
-
}
|
|
1965
|
-
}
|
|
1966
|
-
for (const part of parts) {
|
|
1967
|
-
if (!("functionCall" in part)) continue;
|
|
1968
|
-
const providerMeta = part.thoughtSignature ? {
|
|
1969
|
-
[providerOptionsName]: {
|
|
1970
|
-
thoughtSignature: part.thoughtSignature
|
|
1971
|
-
}
|
|
1972
|
-
} : void 0;
|
|
1973
|
-
const isStreamingChunk = part.functionCall.partialArgs != null || part.functionCall.name != null && part.functionCall.willContinue === true;
|
|
1974
|
-
const isTerminalChunk = part.functionCall.name == null && part.functionCall.args == null && part.functionCall.partialArgs == null && part.functionCall.willContinue == null;
|
|
1975
|
-
const isCompleteCall = part.functionCall.name != null && part.functionCall.args != null && part.functionCall.partialArgs == null;
|
|
1976
|
-
if (isStreamingChunk) {
|
|
1977
|
-
if (part.functionCall.name != null && part.functionCall.willContinue === true) {
|
|
1978
|
-
const toolCallId = generateId3();
|
|
1979
|
-
const accumulator = new GoogleJSONAccumulator();
|
|
1980
|
-
activeStreamingToolCalls.push({
|
|
1981
|
-
toolCallId,
|
|
1982
|
-
toolName: part.functionCall.name,
|
|
1983
|
-
accumulator,
|
|
1984
|
-
providerMetadata: providerMeta
|
|
1985
|
-
});
|
|
1986
|
-
controller.enqueue({
|
|
1987
|
-
type: "tool-input-start",
|
|
1988
|
-
id: toolCallId,
|
|
1989
|
-
toolName: part.functionCall.name,
|
|
1990
|
-
providerMetadata: providerMeta
|
|
1991
|
-
});
|
|
1992
|
-
if (part.functionCall.partialArgs != null) {
|
|
1993
|
-
const { textDelta } = accumulator.processPartialArgs(
|
|
1994
|
-
part.functionCall.partialArgs
|
|
1995
|
-
);
|
|
1996
|
-
if (textDelta.length > 0) {
|
|
1997
|
-
controller.enqueue({
|
|
1998
|
-
type: "tool-input-delta",
|
|
1999
|
-
id: toolCallId,
|
|
2000
|
-
delta: textDelta,
|
|
2001
|
-
providerMetadata: providerMeta
|
|
2002
|
-
});
|
|
2003
|
-
}
|
|
2004
|
-
}
|
|
2005
|
-
} else if (part.functionCall.partialArgs != null && activeStreamingToolCalls.length > 0) {
|
|
2006
|
-
const active = activeStreamingToolCalls[activeStreamingToolCalls.length - 1];
|
|
2007
|
-
const { textDelta } = active.accumulator.processPartialArgs(
|
|
2008
|
-
part.functionCall.partialArgs
|
|
2009
|
-
);
|
|
2010
|
-
if (textDelta.length > 0) {
|
|
2011
|
-
controller.enqueue({
|
|
2012
|
-
type: "tool-input-delta",
|
|
2013
|
-
id: active.toolCallId,
|
|
2014
|
-
delta: textDelta,
|
|
2015
|
-
providerMetadata: providerMeta
|
|
2016
|
-
});
|
|
2017
|
-
}
|
|
2018
|
-
}
|
|
2019
|
-
} else if (isTerminalChunk && activeStreamingToolCalls.length > 0) {
|
|
2020
|
-
const active = activeStreamingToolCalls.pop();
|
|
2021
|
-
const { finalJSON, closingDelta } = active.accumulator.finalize();
|
|
2022
|
-
if (closingDelta.length > 0) {
|
|
2023
|
-
controller.enqueue({
|
|
2024
|
-
type: "tool-input-delta",
|
|
2025
|
-
id: active.toolCallId,
|
|
2026
|
-
delta: closingDelta,
|
|
2027
|
-
providerMetadata: active.providerMetadata
|
|
2028
|
-
});
|
|
2029
|
-
}
|
|
2030
|
-
controller.enqueue({
|
|
2031
|
-
type: "tool-input-end",
|
|
2032
|
-
id: active.toolCallId,
|
|
2033
|
-
providerMetadata: active.providerMetadata
|
|
2034
|
-
});
|
|
2035
|
-
controller.enqueue({
|
|
2036
|
-
type: "tool-call",
|
|
2037
|
-
toolCallId: active.toolCallId,
|
|
2038
|
-
toolName: active.toolName,
|
|
2039
|
-
input: finalJSON,
|
|
2040
|
-
providerMetadata: active.providerMetadata
|
|
2041
|
-
});
|
|
2042
|
-
hasToolCalls = true;
|
|
2043
|
-
} else if (isCompleteCall) {
|
|
2044
|
-
const toolCallId = generateId3();
|
|
2045
|
-
const toolName = part.functionCall.name;
|
|
2046
|
-
const args2 = typeof part.functionCall.args === "string" ? part.functionCall.args : JSON.stringify((_i = part.functionCall.args) != null ? _i : {});
|
|
2047
|
-
controller.enqueue({
|
|
2048
|
-
type: "tool-input-start",
|
|
2049
|
-
id: toolCallId,
|
|
2050
|
-
toolName,
|
|
2051
|
-
providerMetadata: providerMeta
|
|
2052
|
-
});
|
|
2053
|
-
controller.enqueue({
|
|
2054
|
-
type: "tool-input-delta",
|
|
2055
|
-
id: toolCallId,
|
|
2056
|
-
delta: args2,
|
|
2057
|
-
providerMetadata: providerMeta
|
|
2058
|
-
});
|
|
2059
|
-
controller.enqueue({
|
|
2060
|
-
type: "tool-input-end",
|
|
2061
|
-
id: toolCallId,
|
|
2062
|
-
providerMetadata: providerMeta
|
|
2063
|
-
});
|
|
2064
|
-
controller.enqueue({
|
|
2065
|
-
type: "tool-call",
|
|
2066
|
-
toolCallId,
|
|
2067
|
-
toolName,
|
|
2068
|
-
input: args2,
|
|
2069
|
-
providerMetadata: providerMeta
|
|
2070
|
-
});
|
|
2071
|
-
hasToolCalls = true;
|
|
2072
|
-
}
|
|
2073
|
-
}
|
|
2074
|
-
}
|
|
2075
|
-
if (candidate.finishReason != null) {
|
|
2076
|
-
finishReason = {
|
|
2077
|
-
unified: mapGoogleGenerativeAIFinishReason({
|
|
2078
|
-
finishReason: candidate.finishReason,
|
|
2079
|
-
hasToolCalls
|
|
2080
|
-
}),
|
|
2081
|
-
raw: candidate.finishReason
|
|
2082
|
-
};
|
|
2083
|
-
providerMetadata = {
|
|
2084
|
-
[providerOptionsName]: {
|
|
2085
|
-
promptFeedback: (_j = value.promptFeedback) != null ? _j : null,
|
|
2086
|
-
groundingMetadata: lastGroundingMetadata,
|
|
2087
|
-
urlContextMetadata: lastUrlContextMetadata,
|
|
2088
|
-
safetyRatings: (_k = candidate.safetyRatings) != null ? _k : null,
|
|
2089
|
-
usageMetadata: usageMetadata != null ? usageMetadata : null,
|
|
2090
|
-
finishMessage: (_l = candidate.finishMessage) != null ? _l : null,
|
|
2091
|
-
serviceTier
|
|
2092
|
-
}
|
|
2093
|
-
};
|
|
2094
|
-
}
|
|
2095
|
-
},
|
|
2096
|
-
flush(controller) {
|
|
2097
|
-
if (currentTextBlockId !== null) {
|
|
2098
|
-
controller.enqueue({
|
|
2099
|
-
type: "text-end",
|
|
2100
|
-
id: currentTextBlockId
|
|
2101
|
-
});
|
|
2102
|
-
}
|
|
2103
|
-
if (currentReasoningBlockId !== null) {
|
|
2104
|
-
controller.enqueue({
|
|
2105
|
-
type: "reasoning-end",
|
|
2106
|
-
id: currentReasoningBlockId
|
|
2107
|
-
});
|
|
2108
|
-
}
|
|
2109
|
-
controller.enqueue({
|
|
2110
|
-
type: "finish",
|
|
2111
|
-
finishReason,
|
|
2112
|
-
usage: convertGoogleGenerativeAIUsage(usage),
|
|
2113
|
-
providerMetadata
|
|
2114
|
-
});
|
|
2115
|
-
}
|
|
2116
|
-
})
|
|
2117
|
-
),
|
|
2118
|
-
response: { headers: responseHeaders },
|
|
2119
|
-
request: { body: args }
|
|
2120
|
-
};
|
|
2121
|
-
}
|
|
2122
|
-
};
|
|
2123
|
-
function isGemini3Model(modelId) {
|
|
2124
|
-
return /gemini-3[\.\-]/i.test(modelId) || /gemini-3$/i.test(modelId);
|
|
2125
|
-
}
|
|
2126
|
-
function getMaxOutputTokensForGemini25Model() {
|
|
2127
|
-
return 65536;
|
|
2128
|
-
}
|
|
2129
|
-
function getMaxThinkingTokensForGemini25Model(modelId) {
|
|
2130
|
-
const id = modelId.toLowerCase();
|
|
2131
|
-
if (id.includes("2.5-pro") || id.includes("gemini-3-pro-image")) {
|
|
2132
|
-
return 32768;
|
|
2133
|
-
}
|
|
2134
|
-
return 24576;
|
|
2135
|
-
}
|
|
2136
|
-
function resolveThinkingConfig({
|
|
2137
|
-
reasoning,
|
|
2138
|
-
modelId,
|
|
2139
|
-
warnings
|
|
2140
|
-
}) {
|
|
2141
|
-
if (!isCustomReasoning(reasoning)) {
|
|
2142
|
-
return void 0;
|
|
2143
|
-
}
|
|
2144
|
-
if (isGemini3Model(modelId) && !modelId.includes("gemini-3-pro-image")) {
|
|
2145
|
-
return resolveGemini3ThinkingConfig({ reasoning, warnings });
|
|
2146
|
-
}
|
|
2147
|
-
return resolveGemini25ThinkingConfig({ reasoning, modelId, warnings });
|
|
2148
|
-
}
|
|
2149
|
-
function resolveGemini3ThinkingConfig({
|
|
2150
|
-
reasoning,
|
|
2151
|
-
warnings
|
|
2152
|
-
}) {
|
|
2153
|
-
if (reasoning === "none") {
|
|
2154
|
-
return { thinkingLevel: "minimal" };
|
|
2155
|
-
}
|
|
2156
|
-
const thinkingLevel = mapReasoningToProviderEffort({
|
|
2157
|
-
reasoning,
|
|
2158
|
-
effortMap: {
|
|
2159
|
-
minimal: "minimal",
|
|
2160
|
-
low: "low",
|
|
2161
|
-
medium: "medium",
|
|
2162
|
-
high: "high",
|
|
2163
|
-
xhigh: "high"
|
|
2164
|
-
},
|
|
2165
|
-
warnings
|
|
2166
|
-
});
|
|
2167
|
-
if (thinkingLevel == null) {
|
|
2168
|
-
return void 0;
|
|
2169
|
-
}
|
|
2170
|
-
return { thinkingLevel };
|
|
2171
|
-
}
|
|
2172
|
-
function resolveGemini25ThinkingConfig({
|
|
2173
|
-
reasoning,
|
|
2174
|
-
modelId,
|
|
2175
|
-
warnings
|
|
2176
|
-
}) {
|
|
2177
|
-
if (reasoning === "none") {
|
|
2178
|
-
return { thinkingBudget: 0 };
|
|
2179
|
-
}
|
|
2180
|
-
const thinkingBudget = mapReasoningToProviderBudget({
|
|
2181
|
-
reasoning,
|
|
2182
|
-
maxOutputTokens: getMaxOutputTokensForGemini25Model(),
|
|
2183
|
-
maxReasoningBudget: getMaxThinkingTokensForGemini25Model(modelId),
|
|
2184
|
-
minReasoningBudget: 0,
|
|
2185
|
-
warnings
|
|
2186
|
-
});
|
|
2187
|
-
if (thinkingBudget == null) {
|
|
2188
|
-
return void 0;
|
|
2189
|
-
}
|
|
2190
|
-
return { thinkingBudget };
|
|
2191
|
-
}
|
|
2192
|
-
function extractSources({
|
|
2193
|
-
groundingMetadata,
|
|
2194
|
-
generateId: generateId3
|
|
2195
|
-
}) {
|
|
2196
|
-
var _a, _b, _c, _d, _e, _f;
|
|
2197
|
-
if (!(groundingMetadata == null ? void 0 : groundingMetadata.groundingChunks)) {
|
|
2198
|
-
return void 0;
|
|
2199
|
-
}
|
|
2200
|
-
const sources = [];
|
|
2201
|
-
for (const chunk of groundingMetadata.groundingChunks) {
|
|
2202
|
-
if (chunk.web != null) {
|
|
2203
|
-
sources.push({
|
|
2204
|
-
type: "source",
|
|
2205
|
-
sourceType: "url",
|
|
2206
|
-
id: generateId3(),
|
|
2207
|
-
url: chunk.web.uri,
|
|
2208
|
-
title: (_a = chunk.web.title) != null ? _a : void 0
|
|
2209
|
-
});
|
|
2210
|
-
} else if (chunk.image != null) {
|
|
2211
|
-
sources.push({
|
|
2212
|
-
type: "source",
|
|
2213
|
-
sourceType: "url",
|
|
2214
|
-
id: generateId3(),
|
|
2215
|
-
// Google requires attribution to the source URI, not the actual image URI.
|
|
2216
|
-
// TODO: add another type in v7 to allow both the image and source URL to be included separately
|
|
2217
|
-
url: chunk.image.sourceUri,
|
|
2218
|
-
title: (_b = chunk.image.title) != null ? _b : void 0
|
|
2219
|
-
});
|
|
2220
|
-
} else if (chunk.retrievedContext != null) {
|
|
2221
|
-
const uri = chunk.retrievedContext.uri;
|
|
2222
|
-
const fileSearchStore = chunk.retrievedContext.fileSearchStore;
|
|
2223
|
-
if (uri && (uri.startsWith("http://") || uri.startsWith("https://"))) {
|
|
2224
|
-
sources.push({
|
|
2225
|
-
type: "source",
|
|
2226
|
-
sourceType: "url",
|
|
2227
|
-
id: generateId3(),
|
|
2228
|
-
url: uri,
|
|
2229
|
-
title: (_c = chunk.retrievedContext.title) != null ? _c : void 0
|
|
2230
|
-
});
|
|
2231
|
-
} else if (uri) {
|
|
2232
|
-
const title = (_d = chunk.retrievedContext.title) != null ? _d : "Unknown Document";
|
|
2233
|
-
let mediaType = "application/octet-stream";
|
|
2234
|
-
let filename = void 0;
|
|
2235
|
-
if (uri.endsWith(".pdf")) {
|
|
2236
|
-
mediaType = "application/pdf";
|
|
2237
|
-
filename = uri.split("/").pop();
|
|
2238
|
-
} else if (uri.endsWith(".txt")) {
|
|
2239
|
-
mediaType = "text/plain";
|
|
2240
|
-
filename = uri.split("/").pop();
|
|
2241
|
-
} else if (uri.endsWith(".docx")) {
|
|
2242
|
-
mediaType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
|
|
2243
|
-
filename = uri.split("/").pop();
|
|
2244
|
-
} else if (uri.endsWith(".doc")) {
|
|
2245
|
-
mediaType = "application/msword";
|
|
2246
|
-
filename = uri.split("/").pop();
|
|
2247
|
-
} else if (uri.match(/\.(md|markdown)$/)) {
|
|
2248
|
-
mediaType = "text/markdown";
|
|
2249
|
-
filename = uri.split("/").pop();
|
|
2250
|
-
} else {
|
|
2251
|
-
filename = uri.split("/").pop();
|
|
2252
|
-
}
|
|
2253
|
-
sources.push({
|
|
2254
|
-
type: "source",
|
|
2255
|
-
sourceType: "document",
|
|
2256
|
-
id: generateId3(),
|
|
2257
|
-
mediaType,
|
|
2258
|
-
title,
|
|
2259
|
-
filename
|
|
2260
|
-
});
|
|
2261
|
-
} else if (fileSearchStore) {
|
|
2262
|
-
const title = (_e = chunk.retrievedContext.title) != null ? _e : "Unknown Document";
|
|
2263
|
-
sources.push({
|
|
2264
|
-
type: "source",
|
|
2265
|
-
sourceType: "document",
|
|
2266
|
-
id: generateId3(),
|
|
2267
|
-
mediaType: "application/octet-stream",
|
|
2268
|
-
title,
|
|
2269
|
-
filename: fileSearchStore.split("/").pop()
|
|
2270
|
-
});
|
|
2271
|
-
}
|
|
2272
|
-
} else if (chunk.maps != null) {
|
|
2273
|
-
if (chunk.maps.uri) {
|
|
2274
|
-
sources.push({
|
|
2275
|
-
type: "source",
|
|
2276
|
-
sourceType: "url",
|
|
2277
|
-
id: generateId3(),
|
|
2278
|
-
url: chunk.maps.uri,
|
|
2279
|
-
title: (_f = chunk.maps.title) != null ? _f : void 0
|
|
2280
|
-
});
|
|
2281
|
-
}
|
|
2282
|
-
}
|
|
2283
|
-
}
|
|
2284
|
-
return sources.length > 0 ? sources : void 0;
|
|
2285
|
-
}
|
|
2286
|
-
var getGroundingMetadataSchema = () => z5.object({
|
|
2287
|
-
webSearchQueries: z5.array(z5.string()).nullish(),
|
|
2288
|
-
imageSearchQueries: z5.array(z5.string()).nullish(),
|
|
2289
|
-
retrievalQueries: z5.array(z5.string()).nullish(),
|
|
2290
|
-
searchEntryPoint: z5.object({ renderedContent: z5.string() }).nullish(),
|
|
2291
|
-
groundingChunks: z5.array(
|
|
2292
|
-
z5.object({
|
|
2293
|
-
web: z5.object({ uri: z5.string(), title: z5.string().nullish() }).nullish(),
|
|
2294
|
-
image: z5.object({
|
|
2295
|
-
sourceUri: z5.string(),
|
|
2296
|
-
imageUri: z5.string(),
|
|
2297
|
-
title: z5.string().nullish(),
|
|
2298
|
-
domain: z5.string().nullish()
|
|
2299
|
-
}).nullish(),
|
|
2300
|
-
retrievedContext: z5.object({
|
|
2301
|
-
uri: z5.string().nullish(),
|
|
2302
|
-
title: z5.string().nullish(),
|
|
2303
|
-
text: z5.string().nullish(),
|
|
2304
|
-
fileSearchStore: z5.string().nullish()
|
|
2305
|
-
}).nullish(),
|
|
2306
|
-
maps: z5.object({
|
|
2307
|
-
uri: z5.string().nullish(),
|
|
2308
|
-
title: z5.string().nullish(),
|
|
2309
|
-
text: z5.string().nullish(),
|
|
2310
|
-
placeId: z5.string().nullish()
|
|
2311
|
-
}).nullish()
|
|
2312
|
-
})
|
|
2313
|
-
).nullish(),
|
|
2314
|
-
groundingSupports: z5.array(
|
|
2315
|
-
z5.object({
|
|
2316
|
-
segment: z5.object({
|
|
2317
|
-
startIndex: z5.number().nullish(),
|
|
2318
|
-
endIndex: z5.number().nullish(),
|
|
2319
|
-
text: z5.string().nullish()
|
|
2320
|
-
}).nullish(),
|
|
2321
|
-
segment_text: z5.string().nullish(),
|
|
2322
|
-
groundingChunkIndices: z5.array(z5.number()).nullish(),
|
|
2323
|
-
supportChunkIndices: z5.array(z5.number()).nullish(),
|
|
2324
|
-
confidenceScores: z5.array(z5.number()).nullish(),
|
|
2325
|
-
confidenceScore: z5.array(z5.number()).nullish()
|
|
2326
|
-
})
|
|
2327
|
-
).nullish(),
|
|
2328
|
-
retrievalMetadata: z5.union([
|
|
2329
|
-
z5.object({
|
|
2330
|
-
webDynamicRetrievalScore: z5.number()
|
|
2331
|
-
}),
|
|
2332
|
-
z5.object({})
|
|
2333
|
-
]).nullish()
|
|
2334
|
-
});
|
|
2335
|
-
var partialArgSchema = z5.object({
|
|
2336
|
-
jsonPath: z5.string(),
|
|
2337
|
-
stringValue: z5.string().nullish(),
|
|
2338
|
-
numberValue: z5.number().nullish(),
|
|
2339
|
-
boolValue: z5.boolean().nullish(),
|
|
2340
|
-
nullValue: z5.unknown().nullish(),
|
|
2341
|
-
willContinue: z5.boolean().nullish()
|
|
2342
|
-
});
|
|
2343
|
-
var getContentSchema = () => z5.object({
|
|
2344
|
-
parts: z5.array(
|
|
2345
|
-
z5.union([
|
|
2346
|
-
// note: order matters since text can be fully empty
|
|
2347
|
-
z5.object({
|
|
2348
|
-
functionCall: z5.object({
|
|
2349
|
-
name: z5.string().nullish(),
|
|
2350
|
-
args: z5.unknown().nullish(),
|
|
2351
|
-
partialArgs: z5.array(partialArgSchema).nullish(),
|
|
2352
|
-
willContinue: z5.boolean().nullish()
|
|
2353
|
-
}),
|
|
2354
|
-
thoughtSignature: z5.string().nullish()
|
|
2355
|
-
}),
|
|
2356
|
-
z5.object({
|
|
2357
|
-
inlineData: z5.object({
|
|
2358
|
-
mimeType: z5.string(),
|
|
2359
|
-
data: z5.string()
|
|
2360
|
-
}),
|
|
2361
|
-
thought: z5.boolean().nullish(),
|
|
2362
|
-
thoughtSignature: z5.string().nullish()
|
|
2363
|
-
}),
|
|
2364
|
-
z5.object({
|
|
2365
|
-
toolCall: z5.object({
|
|
2366
|
-
toolType: z5.string(),
|
|
2367
|
-
args: z5.unknown().nullish(),
|
|
2368
|
-
id: z5.string()
|
|
2369
|
-
}),
|
|
2370
|
-
thoughtSignature: z5.string().nullish()
|
|
2371
|
-
}),
|
|
2372
|
-
z5.object({
|
|
2373
|
-
toolResponse: z5.object({
|
|
2374
|
-
toolType: z5.string(),
|
|
2375
|
-
response: z5.unknown().nullish(),
|
|
2376
|
-
id: z5.string()
|
|
2377
|
-
}),
|
|
2378
|
-
thoughtSignature: z5.string().nullish()
|
|
2379
|
-
}),
|
|
2380
|
-
z5.object({
|
|
2381
|
-
executableCode: z5.object({
|
|
2382
|
-
language: z5.string(),
|
|
2383
|
-
code: z5.string()
|
|
2384
|
-
}).nullish(),
|
|
2385
|
-
codeExecutionResult: z5.object({
|
|
2386
|
-
outcome: z5.string(),
|
|
2387
|
-
output: z5.string().nullish()
|
|
2388
|
-
}).nullish(),
|
|
2389
|
-
text: z5.string().nullish(),
|
|
2390
|
-
thought: z5.boolean().nullish(),
|
|
2391
|
-
thoughtSignature: z5.string().nullish()
|
|
2392
|
-
})
|
|
2393
|
-
])
|
|
2394
|
-
).nullish()
|
|
2395
|
-
});
|
|
2396
|
-
var getSafetyRatingSchema = () => z5.object({
|
|
2397
|
-
category: z5.string().nullish(),
|
|
2398
|
-
probability: z5.string().nullish(),
|
|
2399
|
-
probabilityScore: z5.number().nullish(),
|
|
2400
|
-
severity: z5.string().nullish(),
|
|
2401
|
-
severityScore: z5.number().nullish(),
|
|
2402
|
-
blocked: z5.boolean().nullish()
|
|
2403
|
-
});
|
|
2404
|
-
var tokenDetailsSchema = z5.array(
|
|
2405
|
-
z5.object({
|
|
2406
|
-
modality: z5.string(),
|
|
2407
|
-
tokenCount: z5.number()
|
|
2408
|
-
})
|
|
2409
|
-
).nullish();
|
|
2410
|
-
var usageSchema = z5.object({
|
|
2411
|
-
cachedContentTokenCount: z5.number().nullish(),
|
|
2412
|
-
thoughtsTokenCount: z5.number().nullish(),
|
|
2413
|
-
promptTokenCount: z5.number().nullish(),
|
|
2414
|
-
candidatesTokenCount: z5.number().nullish(),
|
|
2415
|
-
totalTokenCount: z5.number().nullish(),
|
|
2416
|
-
// https://cloud.google.com/vertex-ai/generative-ai/docs/reference/rest/v1/GenerateContentResponse#TrafficType
|
|
2417
|
-
trafficType: z5.string().nullish(),
|
|
2418
|
-
// https://ai.google.dev/api/generate-content#Modality
|
|
2419
|
-
promptTokensDetails: tokenDetailsSchema,
|
|
2420
|
-
candidatesTokensDetails: tokenDetailsSchema
|
|
2421
|
-
});
|
|
2422
|
-
var getUrlContextMetadataSchema = () => z5.object({
|
|
2423
|
-
urlMetadata: z5.array(
|
|
2424
|
-
z5.object({
|
|
2425
|
-
retrievedUrl: z5.string(),
|
|
2426
|
-
urlRetrievalStatus: z5.string()
|
|
2427
|
-
})
|
|
2428
|
-
).nullish()
|
|
2429
|
-
});
|
|
2430
|
-
var responseSchema = lazySchema5(
|
|
2431
|
-
() => zodSchema5(
|
|
2432
|
-
z5.object({
|
|
2433
|
-
candidates: z5.array(
|
|
2434
|
-
z5.object({
|
|
2435
|
-
content: getContentSchema().nullish().or(z5.object({}).strict()),
|
|
2436
|
-
finishReason: z5.string().nullish(),
|
|
2437
|
-
finishMessage: z5.string().nullish(),
|
|
2438
|
-
safetyRatings: z5.array(getSafetyRatingSchema()).nullish(),
|
|
2439
|
-
groundingMetadata: getGroundingMetadataSchema().nullish(),
|
|
2440
|
-
urlContextMetadata: getUrlContextMetadataSchema().nullish()
|
|
2441
|
-
})
|
|
2442
|
-
),
|
|
2443
|
-
usageMetadata: usageSchema.nullish(),
|
|
2444
|
-
promptFeedback: z5.object({
|
|
2445
|
-
blockReason: z5.string().nullish(),
|
|
2446
|
-
safetyRatings: z5.array(getSafetyRatingSchema()).nullish()
|
|
2447
|
-
}).nullish(),
|
|
2448
|
-
serviceTier: z5.string().nullish()
|
|
2449
|
-
})
|
|
2450
|
-
)
|
|
2451
|
-
);
|
|
2452
|
-
var chunkSchema = lazySchema5(
|
|
2453
|
-
() => zodSchema5(
|
|
2454
|
-
z5.object({
|
|
2455
|
-
candidates: z5.array(
|
|
2456
|
-
z5.object({
|
|
2457
|
-
content: getContentSchema().nullish(),
|
|
2458
|
-
finishReason: z5.string().nullish(),
|
|
2459
|
-
finishMessage: z5.string().nullish(),
|
|
2460
|
-
safetyRatings: z5.array(getSafetyRatingSchema()).nullish(),
|
|
2461
|
-
groundingMetadata: getGroundingMetadataSchema().nullish(),
|
|
2462
|
-
urlContextMetadata: getUrlContextMetadataSchema().nullish()
|
|
2463
|
-
})
|
|
2464
|
-
).nullish(),
|
|
2465
|
-
usageMetadata: usageSchema.nullish(),
|
|
2466
|
-
promptFeedback: z5.object({
|
|
2467
|
-
blockReason: z5.string().nullish(),
|
|
2468
|
-
safetyRatings: z5.array(getSafetyRatingSchema()).nullish()
|
|
2469
|
-
}).nullish(),
|
|
2470
|
-
serviceTier: z5.string().nullish()
|
|
2471
|
-
})
|
|
2472
|
-
)
|
|
2473
|
-
);
|
|
2474
|
-
|
|
2475
|
-
// src/tool/code-execution.ts
|
|
2476
|
-
import { createProviderToolFactoryWithOutputSchema } from "@ai-sdk/provider-utils";
|
|
2477
|
-
import { z as z6 } from "zod/v4";
|
|
2478
|
-
var codeExecution = createProviderToolFactoryWithOutputSchema({
|
|
2479
|
-
id: "google.code_execution",
|
|
2480
|
-
inputSchema: z6.object({
|
|
2481
|
-
language: z6.string().describe("The programming language of the code."),
|
|
2482
|
-
code: z6.string().describe("The code to be executed.")
|
|
2483
|
-
}),
|
|
2484
|
-
outputSchema: z6.object({
|
|
2485
|
-
outcome: z6.string().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),
|
|
2486
|
-
output: z6.string().describe("The output from the code execution.")
|
|
2487
|
-
})
|
|
2488
|
-
});
|
|
2489
|
-
|
|
2490
|
-
// src/tool/enterprise-web-search.ts
|
|
2491
|
-
import {
|
|
2492
|
-
createProviderToolFactory,
|
|
2493
|
-
lazySchema as lazySchema6,
|
|
2494
|
-
zodSchema as zodSchema6
|
|
2495
|
-
} from "@ai-sdk/provider-utils";
|
|
2496
|
-
import { z as z7 } from "zod/v4";
|
|
2497
|
-
var enterpriseWebSearch = createProviderToolFactory({
|
|
2498
|
-
id: "google.enterprise_web_search",
|
|
2499
|
-
inputSchema: lazySchema6(() => zodSchema6(z7.object({})))
|
|
2500
|
-
});
|
|
2501
|
-
|
|
2502
|
-
// src/tool/file-search.ts
|
|
2503
|
-
import {
|
|
2504
|
-
createProviderToolFactory as createProviderToolFactory2,
|
|
2505
|
-
lazySchema as lazySchema7,
|
|
2506
|
-
zodSchema as zodSchema7
|
|
2507
|
-
} from "@ai-sdk/provider-utils";
|
|
2508
|
-
import { z as z8 } from "zod/v4";
|
|
2509
|
-
var fileSearchArgsBaseSchema = z8.object({
|
|
2510
|
-
/** The names of the file_search_stores to retrieve from.
|
|
2511
|
-
* Example: `fileSearchStores/my-file-search-store-123`
|
|
2512
|
-
*/
|
|
2513
|
-
fileSearchStoreNames: z8.array(z8.string()).describe(
|
|
2514
|
-
"The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"
|
|
2515
|
-
),
|
|
2516
|
-
/** The number of file search retrieval chunks to retrieve. */
|
|
2517
|
-
topK: z8.number().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),
|
|
2518
|
-
/** Metadata filter to apply to the file search retrieval documents.
|
|
2519
|
-
* See https://google.aip.dev/160 for the syntax of the filter expression.
|
|
2520
|
-
*/
|
|
2521
|
-
metadataFilter: z8.string().describe(
|
|
2522
|
-
"Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression."
|
|
2523
|
-
).optional()
|
|
2524
|
-
}).passthrough();
|
|
2525
|
-
var fileSearchArgsSchema = lazySchema7(
|
|
2526
|
-
() => zodSchema7(fileSearchArgsBaseSchema)
|
|
2527
|
-
);
|
|
2528
|
-
var fileSearch = createProviderToolFactory2({
|
|
2529
|
-
id: "google.file_search",
|
|
2530
|
-
inputSchema: fileSearchArgsSchema
|
|
2531
|
-
});
|
|
2532
|
-
|
|
2533
|
-
// src/tool/google-maps.ts
|
|
2534
|
-
import {
|
|
2535
|
-
createProviderToolFactory as createProviderToolFactory3,
|
|
2536
|
-
lazySchema as lazySchema8,
|
|
2537
|
-
zodSchema as zodSchema8
|
|
2538
|
-
} from "@ai-sdk/provider-utils";
|
|
2539
|
-
import { z as z9 } from "zod/v4";
|
|
2540
|
-
var googleMaps = createProviderToolFactory3({
|
|
2541
|
-
id: "google.google_maps",
|
|
2542
|
-
inputSchema: lazySchema8(() => zodSchema8(z9.object({})))
|
|
2543
|
-
});
|
|
2544
|
-
|
|
2545
|
-
// src/tool/google-search.ts
|
|
2546
|
-
import {
|
|
2547
|
-
createProviderToolFactory as createProviderToolFactory4,
|
|
2548
|
-
lazySchema as lazySchema9,
|
|
2549
|
-
zodSchema as zodSchema9
|
|
2550
|
-
} from "@ai-sdk/provider-utils";
|
|
2551
|
-
import { z as z10 } from "zod/v4";
|
|
2552
|
-
var googleSearchToolArgsBaseSchema = z10.object({
|
|
2553
|
-
searchTypes: z10.object({
|
|
2554
|
-
webSearch: z10.object({}).optional(),
|
|
2555
|
-
imageSearch: z10.object({}).optional()
|
|
2556
|
-
}).optional(),
|
|
2557
|
-
timeRangeFilter: z10.object({
|
|
2558
|
-
startTime: z10.string(),
|
|
2559
|
-
endTime: z10.string()
|
|
2560
|
-
}).optional()
|
|
2561
|
-
}).passthrough();
|
|
2562
|
-
var googleSearchToolArgsSchema = lazySchema9(
|
|
2563
|
-
() => zodSchema9(googleSearchToolArgsBaseSchema)
|
|
2564
|
-
);
|
|
2565
|
-
var googleSearch = createProviderToolFactory4(
|
|
2566
|
-
{
|
|
2567
|
-
id: "google.google_search",
|
|
2568
|
-
inputSchema: googleSearchToolArgsSchema
|
|
2569
|
-
}
|
|
2570
|
-
);
|
|
2571
|
-
|
|
2572
|
-
// src/tool/url-context.ts
|
|
2573
|
-
import {
|
|
2574
|
-
createProviderToolFactory as createProviderToolFactory5,
|
|
2575
|
-
lazySchema as lazySchema10,
|
|
2576
|
-
zodSchema as zodSchema10
|
|
2577
|
-
} from "@ai-sdk/provider-utils";
|
|
2578
|
-
import { z as z11 } from "zod/v4";
|
|
2579
|
-
var urlContext = createProviderToolFactory5({
|
|
2580
|
-
id: "google.url_context",
|
|
2581
|
-
inputSchema: lazySchema10(() => zodSchema10(z11.object({})))
|
|
2582
|
-
});
|
|
2583
|
-
|
|
2584
|
-
// src/tool/vertex-rag-store.ts
|
|
2585
|
-
import { createProviderToolFactory as createProviderToolFactory6 } from "@ai-sdk/provider-utils";
|
|
2586
|
-
import { z as z12 } from "zod/v4";
|
|
2587
|
-
var vertexRagStore = createProviderToolFactory6({
|
|
2588
|
-
id: "google.vertex_rag_store",
|
|
2589
|
-
inputSchema: z12.object({
|
|
2590
|
-
ragCorpus: z12.string(),
|
|
2591
|
-
topK: z12.number().optional()
|
|
2592
|
-
})
|
|
2593
|
-
});
|
|
2594
|
-
|
|
2595
|
-
// src/google-tools.ts
|
|
2596
|
-
var googleTools = {
|
|
2597
|
-
/**
|
|
2598
|
-
* Creates a Google search tool that gives Google direct access to real-time web content.
|
|
2599
|
-
* Must have name "google_search".
|
|
2600
|
-
*/
|
|
2601
|
-
googleSearch,
|
|
2602
|
-
/**
|
|
2603
|
-
* Creates an Enterprise Web Search tool for grounding responses using a compliance-focused web index.
|
|
2604
|
-
* Designed for highly-regulated industries (finance, healthcare, public sector).
|
|
2605
|
-
* Does not log customer data and supports VPC service controls.
|
|
2606
|
-
* Must have name "enterprise_web_search".
|
|
2607
|
-
*
|
|
2608
|
-
* @note Only available on Vertex AI. Requires Gemini 2.0 or newer.
|
|
2609
|
-
*
|
|
2610
|
-
* @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/web-grounding-enterprise
|
|
2611
|
-
*/
|
|
2612
|
-
enterpriseWebSearch,
|
|
2613
|
-
/**
|
|
2614
|
-
* Creates a Google Maps grounding tool that gives the model access to Google Maps data.
|
|
2615
|
-
* Must have name "google_maps".
|
|
2616
|
-
*
|
|
2617
|
-
* @see https://ai.google.dev/gemini-api/docs/maps-grounding
|
|
2618
|
-
* @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-with-google-maps
|
|
2619
|
-
*/
|
|
2620
|
-
googleMaps,
|
|
2621
|
-
/**
|
|
2622
|
-
* Creates a URL context tool that gives Google direct access to real-time web content.
|
|
2623
|
-
* Must have name "url_context".
|
|
2624
|
-
*/
|
|
2625
|
-
urlContext,
|
|
2626
|
-
/**
|
|
2627
|
-
* Enables Retrieval Augmented Generation (RAG) via the Gemini File Search tool.
|
|
2628
|
-
* Must have name "file_search".
|
|
2629
|
-
*
|
|
2630
|
-
* @param fileSearchStoreNames - Fully-qualified File Search store resource names.
|
|
2631
|
-
* @param metadataFilter - Optional filter expression to restrict the files that can be retrieved.
|
|
2632
|
-
* @param topK - Optional result limit for the number of chunks returned from File Search.
|
|
2633
|
-
*
|
|
2634
|
-
* @see https://ai.google.dev/gemini-api/docs/file-search
|
|
2635
|
-
*/
|
|
2636
|
-
fileSearch,
|
|
2637
|
-
/**
|
|
2638
|
-
* A tool that enables the model to generate and run Python code.
|
|
2639
|
-
* Must have name "code_execution".
|
|
2640
|
-
*
|
|
2641
|
-
* @note Ensure the selected model supports Code Execution.
|
|
2642
|
-
* Multi-tool usage with the code execution tool is typically compatible with Gemini >=2 models.
|
|
2643
|
-
*
|
|
2644
|
-
* @see https://ai.google.dev/gemini-api/docs/code-execution (Google AI)
|
|
2645
|
-
* @see https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/code-execution-api (Vertex AI)
|
|
2646
|
-
*/
|
|
2647
|
-
codeExecution,
|
|
2648
|
-
/**
|
|
2649
|
-
* Creates a Vertex RAG Store tool that enables the model to perform RAG searches against a Vertex RAG Store.
|
|
2650
|
-
* Must have name "vertex_rag_store".
|
|
2651
|
-
*/
|
|
2652
|
-
vertexRagStore
|
|
2653
|
-
};
|
|
2654
|
-
|
|
2655
|
-
// src/google-generative-ai-image-model.ts
|
|
2656
|
-
import {
|
|
2657
|
-
combineHeaders as combineHeaders3,
|
|
2658
|
-
convertToBase64 as convertToBase642,
|
|
2659
|
-
createJsonResponseHandler as createJsonResponseHandler3,
|
|
2660
|
-
generateId as defaultGenerateId,
|
|
2661
|
-
lazySchema as lazySchema11,
|
|
2662
|
-
parseProviderOptions as parseProviderOptions3,
|
|
2663
|
-
postJsonToApi as postJsonToApi3,
|
|
2664
|
-
resolve as resolve3,
|
|
2665
|
-
zodSchema as zodSchema11
|
|
2666
|
-
} from "@ai-sdk/provider-utils";
|
|
2667
|
-
import { z as z13 } from "zod/v4";
|
|
2668
|
-
var GoogleGenerativeAIImageModel = class {
|
|
2669
|
-
constructor(modelId, settings, config) {
|
|
2670
|
-
this.modelId = modelId;
|
|
2671
|
-
this.settings = settings;
|
|
2672
|
-
this.config = config;
|
|
2673
|
-
this.specificationVersion = "v4";
|
|
2674
|
-
}
|
|
2675
|
-
get maxImagesPerCall() {
|
|
2676
|
-
if (this.settings.maxImagesPerCall != null) {
|
|
2677
|
-
return this.settings.maxImagesPerCall;
|
|
2678
|
-
}
|
|
2679
|
-
if (isGeminiModel(this.modelId)) {
|
|
2680
|
-
return 10;
|
|
2681
|
-
}
|
|
2682
|
-
return 4;
|
|
2683
|
-
}
|
|
2684
|
-
get provider() {
|
|
2685
|
-
return this.config.provider;
|
|
2686
|
-
}
|
|
2687
|
-
async doGenerate(options) {
|
|
2688
|
-
if (isGeminiModel(this.modelId)) {
|
|
2689
|
-
return this.doGenerateGemini(options);
|
|
2690
|
-
}
|
|
2691
|
-
return this.doGenerateImagen(options);
|
|
2692
|
-
}
|
|
2693
|
-
async doGenerateImagen(options) {
|
|
2694
|
-
var _a, _b, _c;
|
|
2695
|
-
const {
|
|
2696
|
-
prompt,
|
|
2697
|
-
n = 1,
|
|
2698
|
-
size,
|
|
2699
|
-
aspectRatio = "1:1",
|
|
2700
|
-
seed,
|
|
2701
|
-
providerOptions,
|
|
2702
|
-
headers,
|
|
2703
|
-
abortSignal,
|
|
2704
|
-
files,
|
|
2705
|
-
mask
|
|
2706
|
-
} = options;
|
|
2707
|
-
const warnings = [];
|
|
2708
|
-
if (files != null && files.length > 0) {
|
|
2709
|
-
throw new Error(
|
|
2710
|
-
"Google Generative AI does not support image editing with Imagen models. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities."
|
|
2711
|
-
);
|
|
2712
|
-
}
|
|
2713
|
-
if (mask != null) {
|
|
2714
|
-
throw new Error(
|
|
2715
|
-
"Google Generative AI does not support image editing with masks. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities."
|
|
2716
|
-
);
|
|
2717
|
-
}
|
|
2718
|
-
if (size != null) {
|
|
2719
|
-
warnings.push({
|
|
2720
|
-
type: "unsupported",
|
|
2721
|
-
feature: "size",
|
|
2722
|
-
details: "This model does not support the `size` option. Use `aspectRatio` instead."
|
|
2723
|
-
});
|
|
2724
|
-
}
|
|
2725
|
-
if (seed != null) {
|
|
2726
|
-
warnings.push({
|
|
2727
|
-
type: "unsupported",
|
|
2728
|
-
feature: "seed",
|
|
2729
|
-
details: "This model does not support the `seed` option through this provider."
|
|
2730
|
-
});
|
|
2731
|
-
}
|
|
2732
|
-
const googleOptions = await parseProviderOptions3({
|
|
2733
|
-
provider: "google",
|
|
2734
|
-
providerOptions,
|
|
2735
|
-
schema: googleImageModelOptionsSchema
|
|
2736
|
-
});
|
|
2737
|
-
const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
|
|
2738
|
-
const parameters = {
|
|
2739
|
-
sampleCount: n
|
|
2740
|
-
};
|
|
2741
|
-
if (aspectRatio != null) {
|
|
2742
|
-
parameters.aspectRatio = aspectRatio;
|
|
2743
|
-
}
|
|
2744
|
-
if (googleOptions) {
|
|
2745
|
-
Object.assign(parameters, googleOptions);
|
|
2746
|
-
}
|
|
2747
|
-
const body = {
|
|
2748
|
-
instances: [{ prompt }],
|
|
2749
|
-
parameters
|
|
2750
|
-
};
|
|
2751
|
-
const { responseHeaders, value: response } = await postJsonToApi3({
|
|
2752
|
-
url: `${this.config.baseURL}/models/${this.modelId}:predict`,
|
|
2753
|
-
headers: combineHeaders3(await resolve3(this.config.headers), headers),
|
|
2754
|
-
body,
|
|
2755
|
-
failedResponseHandler: googleFailedResponseHandler,
|
|
2756
|
-
successfulResponseHandler: createJsonResponseHandler3(
|
|
2757
|
-
googleImageResponseSchema
|
|
2758
|
-
),
|
|
2759
|
-
abortSignal,
|
|
2760
|
-
fetch: this.config.fetch
|
|
2761
|
-
});
|
|
2762
|
-
return {
|
|
2763
|
-
images: response.predictions.map(
|
|
2764
|
-
(p) => p.bytesBase64Encoded
|
|
2765
|
-
),
|
|
2766
|
-
warnings,
|
|
2767
|
-
providerMetadata: {
|
|
2768
|
-
google: {
|
|
2769
|
-
images: response.predictions.map(() => ({
|
|
2770
|
-
// Add any prediction-specific metadata here
|
|
2771
|
-
}))
|
|
2772
|
-
}
|
|
2773
|
-
},
|
|
2774
|
-
response: {
|
|
2775
|
-
timestamp: currentDate,
|
|
2776
|
-
modelId: this.modelId,
|
|
2777
|
-
headers: responseHeaders
|
|
2778
|
-
}
|
|
2779
|
-
};
|
|
2780
|
-
}
|
|
2781
|
-
async doGenerateGemini(options) {
|
|
2782
|
-
var _a, _b, _c, _d, _e, _f, _g, _h, _i;
|
|
2783
|
-
const {
|
|
2784
|
-
prompt,
|
|
2785
|
-
n,
|
|
2786
|
-
size,
|
|
2787
|
-
aspectRatio,
|
|
2788
|
-
seed,
|
|
2789
|
-
providerOptions,
|
|
2790
|
-
headers,
|
|
2791
|
-
abortSignal,
|
|
2792
|
-
files,
|
|
2793
|
-
mask
|
|
2794
|
-
} = options;
|
|
2795
|
-
const warnings = [];
|
|
2796
|
-
if (mask != null) {
|
|
2797
|
-
throw new Error(
|
|
2798
|
-
"Gemini image models do not support mask-based image editing."
|
|
2799
|
-
);
|
|
2800
|
-
}
|
|
2801
|
-
if (n != null && n > 1) {
|
|
2802
|
-
throw new Error(
|
|
2803
|
-
"Gemini image models do not support generating a set number of images per call. Use n=1 or omit the n parameter."
|
|
2804
|
-
);
|
|
2805
|
-
}
|
|
2806
|
-
if (size != null) {
|
|
2807
|
-
warnings.push({
|
|
2808
|
-
type: "unsupported",
|
|
2809
|
-
feature: "size",
|
|
2810
|
-
details: "This model does not support the `size` option. Use `aspectRatio` instead."
|
|
2811
|
-
});
|
|
2812
|
-
}
|
|
2813
|
-
const userContent = [];
|
|
2814
|
-
if (prompt != null) {
|
|
2815
|
-
userContent.push({ type: "text", text: prompt });
|
|
2816
|
-
}
|
|
2817
|
-
if (files != null && files.length > 0) {
|
|
2818
|
-
for (const file of files) {
|
|
2819
|
-
if (file.type === "url") {
|
|
2820
|
-
userContent.push({
|
|
2821
|
-
type: "file",
|
|
2822
|
-
data: new URL(file.url),
|
|
2823
|
-
mediaType: "image/*"
|
|
2824
|
-
});
|
|
2825
|
-
} else {
|
|
2826
|
-
userContent.push({
|
|
2827
|
-
type: "file",
|
|
2828
|
-
data: typeof file.data === "string" ? file.data : new Uint8Array(file.data),
|
|
2829
|
-
mediaType: file.mediaType
|
|
2830
|
-
});
|
|
2831
|
-
}
|
|
2832
|
-
}
|
|
2833
|
-
}
|
|
2834
|
-
const languageModelPrompt = [
|
|
2835
|
-
{ role: "user", content: userContent }
|
|
2836
|
-
];
|
|
2837
|
-
const languageModel = new GoogleGenerativeAILanguageModel(this.modelId, {
|
|
2838
|
-
provider: this.config.provider,
|
|
2839
|
-
baseURL: this.config.baseURL,
|
|
2840
|
-
headers: (_a = this.config.headers) != null ? _a : {},
|
|
2841
|
-
fetch: this.config.fetch,
|
|
2842
|
-
generateId: (_b = this.config.generateId) != null ? _b : defaultGenerateId
|
|
2843
|
-
});
|
|
2844
|
-
const result = await languageModel.doGenerate({
|
|
2845
|
-
prompt: languageModelPrompt,
|
|
2846
|
-
seed,
|
|
2847
|
-
providerOptions: {
|
|
2848
|
-
google: {
|
|
2849
|
-
responseModalities: ["IMAGE"],
|
|
2850
|
-
imageConfig: aspectRatio ? {
|
|
2851
|
-
aspectRatio
|
|
2852
|
-
} : void 0,
|
|
2853
|
-
...(_c = providerOptions == null ? void 0 : providerOptions.google) != null ? _c : {}
|
|
2854
|
-
}
|
|
2855
|
-
},
|
|
2856
|
-
headers,
|
|
2857
|
-
abortSignal
|
|
2858
|
-
});
|
|
2859
|
-
const currentDate = (_f = (_e = (_d = this.config._internal) == null ? void 0 : _d.currentDate) == null ? void 0 : _e.call(_d)) != null ? _f : /* @__PURE__ */ new Date();
|
|
2860
|
-
const images = [];
|
|
2861
|
-
for (const part of result.content) {
|
|
2862
|
-
if (part.type === "file" && part.mediaType.startsWith("image/")) {
|
|
2863
|
-
images.push(convertToBase642(part.data));
|
|
2864
|
-
}
|
|
2865
|
-
}
|
|
2866
|
-
return {
|
|
2867
|
-
images,
|
|
2868
|
-
warnings,
|
|
2869
|
-
providerMetadata: {
|
|
2870
|
-
google: {
|
|
2871
|
-
images: images.map(() => ({}))
|
|
2872
|
-
}
|
|
2873
|
-
},
|
|
2874
|
-
response: {
|
|
2875
|
-
timestamp: currentDate,
|
|
2876
|
-
modelId: this.modelId,
|
|
2877
|
-
headers: (_g = result.response) == null ? void 0 : _g.headers
|
|
2878
|
-
},
|
|
2879
|
-
usage: result.usage ? {
|
|
2880
|
-
inputTokens: result.usage.inputTokens.total,
|
|
2881
|
-
outputTokens: result.usage.outputTokens.total,
|
|
2882
|
-
totalTokens: ((_h = result.usage.inputTokens.total) != null ? _h : 0) + ((_i = result.usage.outputTokens.total) != null ? _i : 0)
|
|
2883
|
-
} : void 0
|
|
2884
|
-
};
|
|
2885
|
-
}
|
|
2886
|
-
};
|
|
2887
|
-
function isGeminiModel(modelId) {
|
|
2888
|
-
return modelId.startsWith("gemini-");
|
|
2889
|
-
}
|
|
2890
|
-
var googleImageResponseSchema = lazySchema11(
|
|
2891
|
-
() => zodSchema11(
|
|
2892
|
-
z13.object({
|
|
2893
|
-
predictions: z13.array(z13.object({ bytesBase64Encoded: z13.string() })).default([])
|
|
2894
|
-
})
|
|
2895
|
-
)
|
|
2896
|
-
);
|
|
2897
|
-
var googleImageModelOptionsSchema = lazySchema11(
|
|
2898
|
-
() => zodSchema11(
|
|
2899
|
-
z13.object({
|
|
2900
|
-
personGeneration: z13.enum(["dont_allow", "allow_adult", "allow_all"]).nullish(),
|
|
2901
|
-
aspectRatio: z13.enum(["1:1", "3:4", "4:3", "9:16", "16:9"]).nullish()
|
|
2902
|
-
})
|
|
2903
|
-
)
|
|
2904
|
-
);
|
|
2905
|
-
|
|
2906
|
-
// src/google-generative-ai-files.ts
|
|
2907
|
-
import {
|
|
2908
|
-
AISDKError
|
|
2909
|
-
} from "@ai-sdk/provider";
|
|
2910
|
-
import {
|
|
2911
|
-
combineHeaders as combineHeaders4,
|
|
2912
|
-
createJsonResponseHandler as createJsonResponseHandler4,
|
|
2913
|
-
delay,
|
|
2914
|
-
lazySchema as lazySchema12,
|
|
2915
|
-
parseProviderOptions as parseProviderOptions4,
|
|
2916
|
-
zodSchema as zodSchema12,
|
|
2917
|
-
getFromApi
|
|
2918
|
-
} from "@ai-sdk/provider-utils";
|
|
2919
|
-
import { z as z14 } from "zod/v4";
|
|
2920
|
-
var GoogleGenerativeAIFiles = class {
|
|
2921
|
-
constructor(config) {
|
|
2922
|
-
this.config = config;
|
|
2923
|
-
this.specificationVersion = "v4";
|
|
2924
|
-
}
|
|
2925
|
-
get provider() {
|
|
2926
|
-
return this.config.provider;
|
|
2927
|
-
}
|
|
2928
|
-
async uploadFile(options) {
|
|
2929
|
-
var _a, _b, _c, _d;
|
|
2930
|
-
const googleOptions = await parseProviderOptions4({
|
|
2931
|
-
provider: "google",
|
|
2932
|
-
providerOptions: options.providerOptions,
|
|
2933
|
-
schema: googleFilesUploadOptionsSchema
|
|
2934
|
-
});
|
|
2935
|
-
const resolvedHeaders = this.config.headers();
|
|
2936
|
-
const fetchFn = (_a = this.config.fetch) != null ? _a : globalThis.fetch;
|
|
2937
|
-
const warnings = [];
|
|
2938
|
-
if (options.filename != null) {
|
|
2939
|
-
warnings.push({ type: "unsupported", feature: "filename" });
|
|
2940
|
-
}
|
|
2941
|
-
const data = options.data;
|
|
2942
|
-
const fileBytes = data instanceof Uint8Array ? data : Uint8Array.from(atob(data), (c) => c.charCodeAt(0));
|
|
2943
|
-
const mediaType = options.mediaType;
|
|
2944
|
-
const displayName = googleOptions == null ? void 0 : googleOptions.displayName;
|
|
2945
|
-
const baseOrigin = this.config.baseURL.replace(/\/v1beta$/, "");
|
|
2946
|
-
const initResponse = await fetchFn(`${baseOrigin}/upload/v1beta/files`, {
|
|
2947
|
-
method: "POST",
|
|
2948
|
-
headers: {
|
|
2949
|
-
...resolvedHeaders,
|
|
2950
|
-
"X-Goog-Upload-Protocol": "resumable",
|
|
2951
|
-
"X-Goog-Upload-Command": "start",
|
|
2952
|
-
"X-Goog-Upload-Header-Content-Length": String(fileBytes.length),
|
|
2953
|
-
"X-Goog-Upload-Header-Content-Type": mediaType,
|
|
2954
|
-
"Content-Type": "application/json"
|
|
2955
|
-
},
|
|
2956
|
-
body: JSON.stringify({
|
|
2957
|
-
file: {
|
|
2958
|
-
...displayName != null ? { display_name: displayName } : {}
|
|
2959
|
-
}
|
|
2960
|
-
})
|
|
2961
|
-
});
|
|
2962
|
-
if (!initResponse.ok) {
|
|
2963
|
-
const errorBody = await initResponse.text();
|
|
2964
|
-
throw new AISDKError({
|
|
2965
|
-
name: "GOOGLE_FILES_UPLOAD_ERROR",
|
|
2966
|
-
message: `Failed to initiate resumable upload: ${initResponse.status} ${errorBody}`
|
|
2967
|
-
});
|
|
2968
|
-
}
|
|
2969
|
-
const uploadUrl = initResponse.headers.get("x-goog-upload-url");
|
|
2970
|
-
if (!uploadUrl) {
|
|
2971
|
-
throw new AISDKError({
|
|
2972
|
-
name: "GOOGLE_FILES_UPLOAD_ERROR",
|
|
2973
|
-
message: "No upload URL returned from initiation request"
|
|
2974
|
-
});
|
|
2975
|
-
}
|
|
2976
|
-
const uploadResponse = await fetchFn(uploadUrl, {
|
|
2977
|
-
method: "POST",
|
|
2978
|
-
headers: {
|
|
2979
|
-
"Content-Length": String(fileBytes.length),
|
|
2980
|
-
"X-Goog-Upload-Offset": "0",
|
|
2981
|
-
"X-Goog-Upload-Command": "upload, finalize"
|
|
2982
|
-
},
|
|
2983
|
-
body: fileBytes
|
|
2984
|
-
});
|
|
2985
|
-
if (!uploadResponse.ok) {
|
|
2986
|
-
const errorBody = await uploadResponse.text();
|
|
2987
|
-
throw new AISDKError({
|
|
2988
|
-
name: "GOOGLE_FILES_UPLOAD_ERROR",
|
|
2989
|
-
message: `Failed to upload file data: ${uploadResponse.status} ${errorBody}`
|
|
2990
|
-
});
|
|
2991
|
-
}
|
|
2992
|
-
const uploadResult = await uploadResponse.json();
|
|
2993
|
-
let file = uploadResult.file;
|
|
2994
|
-
const pollIntervalMs = (_b = googleOptions == null ? void 0 : googleOptions.pollIntervalMs) != null ? _b : 2e3;
|
|
2995
|
-
const pollTimeoutMs = (_c = googleOptions == null ? void 0 : googleOptions.pollTimeoutMs) != null ? _c : 3e5;
|
|
2996
|
-
const startTime = Date.now();
|
|
2997
|
-
while (file.state === "PROCESSING") {
|
|
2998
|
-
if (Date.now() - startTime > pollTimeoutMs) {
|
|
2999
|
-
throw new AISDKError({
|
|
3000
|
-
name: "GOOGLE_FILES_UPLOAD_TIMEOUT",
|
|
3001
|
-
message: `File processing timed out after ${pollTimeoutMs}ms`
|
|
3002
|
-
});
|
|
3003
|
-
}
|
|
3004
|
-
await delay(pollIntervalMs);
|
|
3005
|
-
const { value: fileStatus } = await getFromApi({
|
|
3006
|
-
url: `${this.config.baseURL}/${file.name}`,
|
|
3007
|
-
headers: combineHeaders4(resolvedHeaders),
|
|
3008
|
-
successfulResponseHandler: createJsonResponseHandler4(
|
|
3009
|
-
googleFileResponseSchema
|
|
3010
|
-
),
|
|
3011
|
-
failedResponseHandler: googleFailedResponseHandler,
|
|
3012
|
-
fetch: this.config.fetch
|
|
3013
|
-
});
|
|
3014
|
-
file = fileStatus;
|
|
3015
|
-
}
|
|
3016
|
-
if (file.state === "FAILED") {
|
|
3017
|
-
throw new AISDKError({
|
|
3018
|
-
name: "GOOGLE_FILES_UPLOAD_FAILED",
|
|
3019
|
-
message: `File processing failed for ${file.name}`
|
|
3020
|
-
});
|
|
3021
|
-
}
|
|
3022
|
-
return {
|
|
3023
|
-
warnings,
|
|
3024
|
-
providerReference: { google: file.uri },
|
|
3025
|
-
mediaType: (_d = file.mimeType) != null ? _d : options.mediaType,
|
|
3026
|
-
providerMetadata: {
|
|
3027
|
-
google: {
|
|
3028
|
-
name: file.name,
|
|
3029
|
-
displayName: file.displayName,
|
|
3030
|
-
mimeType: file.mimeType,
|
|
3031
|
-
sizeBytes: file.sizeBytes,
|
|
3032
|
-
state: file.state,
|
|
3033
|
-
uri: file.uri,
|
|
3034
|
-
...file.createTime != null ? { createTime: file.createTime } : {},
|
|
3035
|
-
...file.updateTime != null ? { updateTime: file.updateTime } : {},
|
|
3036
|
-
...file.expirationTime != null ? { expirationTime: file.expirationTime } : {},
|
|
3037
|
-
...file.sha256Hash != null ? { sha256Hash: file.sha256Hash } : {}
|
|
3038
|
-
}
|
|
3039
|
-
}
|
|
3040
|
-
};
|
|
3041
|
-
}
|
|
3042
|
-
};
|
|
3043
|
-
var googleFileResponseSchema = lazySchema12(
|
|
3044
|
-
() => zodSchema12(
|
|
3045
|
-
z14.object({
|
|
3046
|
-
name: z14.string(),
|
|
3047
|
-
displayName: z14.string().nullish(),
|
|
3048
|
-
mimeType: z14.string(),
|
|
3049
|
-
sizeBytes: z14.string().nullish(),
|
|
3050
|
-
createTime: z14.string().nullish(),
|
|
3051
|
-
updateTime: z14.string().nullish(),
|
|
3052
|
-
expirationTime: z14.string().nullish(),
|
|
3053
|
-
sha256Hash: z14.string().nullish(),
|
|
3054
|
-
uri: z14.string(),
|
|
3055
|
-
state: z14.string()
|
|
3056
|
-
})
|
|
3057
|
-
)
|
|
3058
|
-
);
|
|
3059
|
-
var googleFilesUploadOptionsSchema = lazySchema12(
|
|
3060
|
-
() => zodSchema12(
|
|
3061
|
-
z14.object({
|
|
3062
|
-
displayName: z14.string().nullish(),
|
|
3063
|
-
pollIntervalMs: z14.number().positive().nullish(),
|
|
3064
|
-
pollTimeoutMs: z14.number().positive().nullish()
|
|
3065
|
-
}).passthrough()
|
|
3066
|
-
)
|
|
3067
|
-
);
|
|
3068
|
-
|
|
3069
|
-
// src/google-generative-ai-video-model.ts
|
|
3070
|
-
import {
|
|
3071
|
-
AISDKError as AISDKError2
|
|
3072
|
-
} from "@ai-sdk/provider";
|
|
3073
|
-
import {
|
|
3074
|
-
combineHeaders as combineHeaders5,
|
|
3075
|
-
convertUint8ArrayToBase64,
|
|
3076
|
-
createJsonResponseHandler as createJsonResponseHandler5,
|
|
3077
|
-
delay as delay2,
|
|
3078
|
-
getFromApi as getFromApi2,
|
|
3079
|
-
lazySchema as lazySchema13,
|
|
3080
|
-
parseProviderOptions as parseProviderOptions5,
|
|
3081
|
-
postJsonToApi as postJsonToApi4,
|
|
3082
|
-
resolve as resolve4,
|
|
3083
|
-
zodSchema as zodSchema13
|
|
3084
|
-
} from "@ai-sdk/provider-utils";
|
|
3085
|
-
import { z as z15 } from "zod/v4";
|
|
3086
|
-
var GoogleGenerativeAIVideoModel = class {
|
|
3087
|
-
constructor(modelId, config) {
|
|
3088
|
-
this.modelId = modelId;
|
|
3089
|
-
this.config = config;
|
|
3090
|
-
this.specificationVersion = "v4";
|
|
3091
|
-
}
|
|
3092
|
-
get provider() {
|
|
3093
|
-
return this.config.provider;
|
|
3094
|
-
}
|
|
3095
|
-
get maxVideosPerCall() {
|
|
3096
|
-
return 4;
|
|
3097
|
-
}
|
|
3098
|
-
async doGenerate(options) {
|
|
3099
|
-
var _a, _b, _c, _d, _e, _f, _g, _h;
|
|
3100
|
-
const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
|
|
3101
|
-
const warnings = [];
|
|
3102
|
-
const googleOptions = await parseProviderOptions5({
|
|
3103
|
-
provider: "google",
|
|
3104
|
-
providerOptions: options.providerOptions,
|
|
3105
|
-
schema: googleVideoModelOptionsSchema
|
|
3106
|
-
});
|
|
3107
|
-
const instances = [{}];
|
|
3108
|
-
const instance = instances[0];
|
|
3109
|
-
if (options.prompt != null) {
|
|
3110
|
-
instance.prompt = options.prompt;
|
|
3111
|
-
}
|
|
3112
|
-
if (options.image != null) {
|
|
3113
|
-
if (options.image.type === "url") {
|
|
3114
|
-
warnings.push({
|
|
3115
|
-
type: "unsupported",
|
|
3116
|
-
feature: "URL-based image input",
|
|
3117
|
-
details: "Google Generative AI video models require base64-encoded images. URL will be ignored."
|
|
3118
|
-
});
|
|
3119
|
-
} else {
|
|
3120
|
-
const base64Data = typeof options.image.data === "string" ? options.image.data : convertUint8ArrayToBase64(options.image.data);
|
|
3121
|
-
instance.image = {
|
|
3122
|
-
inlineData: {
|
|
3123
|
-
mimeType: options.image.mediaType || "image/png",
|
|
3124
|
-
data: base64Data
|
|
3125
|
-
}
|
|
3126
|
-
};
|
|
3127
|
-
}
|
|
3128
|
-
}
|
|
3129
|
-
if ((googleOptions == null ? void 0 : googleOptions.referenceImages) != null) {
|
|
3130
|
-
instance.referenceImages = googleOptions.referenceImages.map((refImg) => {
|
|
3131
|
-
if (refImg.bytesBase64Encoded) {
|
|
3132
|
-
return {
|
|
3133
|
-
inlineData: {
|
|
3134
|
-
mimeType: "image/png",
|
|
3135
|
-
data: refImg.bytesBase64Encoded
|
|
3136
|
-
}
|
|
3137
|
-
};
|
|
3138
|
-
} else if (refImg.gcsUri) {
|
|
3139
|
-
return {
|
|
3140
|
-
gcsUri: refImg.gcsUri
|
|
3141
|
-
};
|
|
3142
|
-
}
|
|
3143
|
-
return refImg;
|
|
3144
|
-
});
|
|
3145
|
-
}
|
|
3146
|
-
const parameters = {
|
|
3147
|
-
sampleCount: options.n
|
|
3148
|
-
};
|
|
3149
|
-
if (options.aspectRatio) {
|
|
3150
|
-
parameters.aspectRatio = options.aspectRatio;
|
|
3151
|
-
}
|
|
3152
|
-
if (options.resolution) {
|
|
3153
|
-
const resolutionMap = {
|
|
3154
|
-
"1280x720": "720p",
|
|
3155
|
-
"1920x1080": "1080p",
|
|
3156
|
-
"3840x2160": "4k"
|
|
3157
|
-
};
|
|
3158
|
-
parameters.resolution = resolutionMap[options.resolution] || options.resolution;
|
|
3159
|
-
}
|
|
3160
|
-
if (options.duration) {
|
|
3161
|
-
parameters.durationSeconds = options.duration;
|
|
3162
|
-
}
|
|
3163
|
-
if (options.seed) {
|
|
3164
|
-
parameters.seed = options.seed;
|
|
3165
|
-
}
|
|
3166
|
-
if (googleOptions != null) {
|
|
3167
|
-
const opts = googleOptions;
|
|
3168
|
-
if (opts.personGeneration !== void 0 && opts.personGeneration !== null) {
|
|
3169
|
-
parameters.personGeneration = opts.personGeneration;
|
|
3170
|
-
}
|
|
3171
|
-
if (opts.negativePrompt !== void 0 && opts.negativePrompt !== null) {
|
|
3172
|
-
parameters.negativePrompt = opts.negativePrompt;
|
|
3173
|
-
}
|
|
3174
|
-
for (const [key, value] of Object.entries(opts)) {
|
|
3175
|
-
if (![
|
|
3176
|
-
"pollIntervalMs",
|
|
3177
|
-
"pollTimeoutMs",
|
|
3178
|
-
"personGeneration",
|
|
3179
|
-
"negativePrompt",
|
|
3180
|
-
"referenceImages"
|
|
3181
|
-
].includes(key)) {
|
|
3182
|
-
parameters[key] = value;
|
|
3183
|
-
}
|
|
3184
|
-
}
|
|
3185
|
-
}
|
|
3186
|
-
const { value: operation } = await postJsonToApi4({
|
|
3187
|
-
url: `${this.config.baseURL}/models/${this.modelId}:predictLongRunning`,
|
|
3188
|
-
headers: combineHeaders5(
|
|
3189
|
-
await resolve4(this.config.headers),
|
|
3190
|
-
options.headers
|
|
3191
|
-
),
|
|
3192
|
-
body: {
|
|
3193
|
-
instances,
|
|
3194
|
-
parameters
|
|
3195
|
-
},
|
|
3196
|
-
successfulResponseHandler: createJsonResponseHandler5(
|
|
3197
|
-
googleOperationSchema
|
|
3198
|
-
),
|
|
3199
|
-
failedResponseHandler: googleFailedResponseHandler,
|
|
3200
|
-
abortSignal: options.abortSignal,
|
|
3201
|
-
fetch: this.config.fetch
|
|
3202
|
-
});
|
|
3203
|
-
const operationName = operation.name;
|
|
3204
|
-
if (!operationName) {
|
|
3205
|
-
throw new AISDKError2({
|
|
3206
|
-
name: "GOOGLE_VIDEO_GENERATION_ERROR",
|
|
3207
|
-
message: "No operation name returned from API"
|
|
3208
|
-
});
|
|
3209
|
-
}
|
|
3210
|
-
const pollIntervalMs = (_d = googleOptions == null ? void 0 : googleOptions.pollIntervalMs) != null ? _d : 1e4;
|
|
3211
|
-
const pollTimeoutMs = (_e = googleOptions == null ? void 0 : googleOptions.pollTimeoutMs) != null ? _e : 6e5;
|
|
3212
|
-
const startTime = Date.now();
|
|
3213
|
-
let finalOperation = operation;
|
|
3214
|
-
let responseHeaders;
|
|
3215
|
-
while (!finalOperation.done) {
|
|
3216
|
-
if (Date.now() - startTime > pollTimeoutMs) {
|
|
3217
|
-
throw new AISDKError2({
|
|
3218
|
-
name: "GOOGLE_VIDEO_GENERATION_TIMEOUT",
|
|
3219
|
-
message: `Video generation timed out after ${pollTimeoutMs}ms`
|
|
3220
|
-
});
|
|
3221
|
-
}
|
|
3222
|
-
await delay2(pollIntervalMs);
|
|
3223
|
-
if ((_f = options.abortSignal) == null ? void 0 : _f.aborted) {
|
|
3224
|
-
throw new AISDKError2({
|
|
3225
|
-
name: "GOOGLE_VIDEO_GENERATION_ABORTED",
|
|
3226
|
-
message: "Video generation request was aborted"
|
|
3227
|
-
});
|
|
3228
|
-
}
|
|
3229
|
-
const { value: statusOperation, responseHeaders: pollHeaders } = await getFromApi2({
|
|
3230
|
-
url: `${this.config.baseURL}/${operationName}`,
|
|
3231
|
-
headers: combineHeaders5(
|
|
3232
|
-
await resolve4(this.config.headers),
|
|
3233
|
-
options.headers
|
|
3234
|
-
),
|
|
3235
|
-
successfulResponseHandler: createJsonResponseHandler5(
|
|
3236
|
-
googleOperationSchema
|
|
3237
|
-
),
|
|
3238
|
-
failedResponseHandler: googleFailedResponseHandler,
|
|
3239
|
-
abortSignal: options.abortSignal,
|
|
3240
|
-
fetch: this.config.fetch
|
|
3241
|
-
});
|
|
3242
|
-
finalOperation = statusOperation;
|
|
3243
|
-
responseHeaders = pollHeaders;
|
|
3244
|
-
}
|
|
3245
|
-
if (finalOperation.error) {
|
|
3246
|
-
throw new AISDKError2({
|
|
3247
|
-
name: "GOOGLE_VIDEO_GENERATION_FAILED",
|
|
3248
|
-
message: `Video generation failed: ${finalOperation.error.message}`
|
|
3249
|
-
});
|
|
3250
|
-
}
|
|
3251
|
-
const response = finalOperation.response;
|
|
3252
|
-
if (!((_g = response == null ? void 0 : response.generateVideoResponse) == null ? void 0 : _g.generatedSamples) || response.generateVideoResponse.generatedSamples.length === 0) {
|
|
3253
|
-
throw new AISDKError2({
|
|
3254
|
-
name: "GOOGLE_VIDEO_GENERATION_ERROR",
|
|
3255
|
-
message: `No videos in response. Response: ${JSON.stringify(finalOperation)}`
|
|
3256
|
-
});
|
|
3257
|
-
}
|
|
3258
|
-
const videos = [];
|
|
3259
|
-
const videoMetadata = [];
|
|
3260
|
-
const resolvedHeaders = await resolve4(this.config.headers);
|
|
3261
|
-
const apiKey = resolvedHeaders == null ? void 0 : resolvedHeaders["x-goog-api-key"];
|
|
3262
|
-
for (const generatedSample of response.generateVideoResponse.generatedSamples) {
|
|
3263
|
-
if ((_h = generatedSample.video) == null ? void 0 : _h.uri) {
|
|
3264
|
-
const urlWithAuth = apiKey ? `${generatedSample.video.uri}${generatedSample.video.uri.includes("?") ? "&" : "?"}key=${apiKey}` : generatedSample.video.uri;
|
|
3265
|
-
videos.push({
|
|
3266
|
-
type: "url",
|
|
3267
|
-
url: urlWithAuth,
|
|
3268
|
-
mediaType: "video/mp4"
|
|
3269
|
-
});
|
|
3270
|
-
videoMetadata.push({
|
|
3271
|
-
uri: generatedSample.video.uri
|
|
3272
|
-
});
|
|
3273
|
-
}
|
|
3274
|
-
}
|
|
3275
|
-
if (videos.length === 0) {
|
|
3276
|
-
throw new AISDKError2({
|
|
3277
|
-
name: "GOOGLE_VIDEO_GENERATION_ERROR",
|
|
3278
|
-
message: "No valid videos in response"
|
|
3279
|
-
});
|
|
3280
|
-
}
|
|
3281
|
-
return {
|
|
3282
|
-
videos,
|
|
3283
|
-
warnings,
|
|
3284
|
-
response: {
|
|
3285
|
-
timestamp: currentDate,
|
|
3286
|
-
modelId: this.modelId,
|
|
3287
|
-
headers: responseHeaders
|
|
3288
|
-
},
|
|
3289
|
-
providerMetadata: {
|
|
3290
|
-
google: {
|
|
3291
|
-
videos: videoMetadata
|
|
3292
|
-
}
|
|
3293
|
-
}
|
|
3294
|
-
};
|
|
3295
|
-
}
|
|
3296
|
-
};
|
|
3297
|
-
var googleOperationSchema = z15.object({
|
|
3298
|
-
name: z15.string().nullish(),
|
|
3299
|
-
done: z15.boolean().nullish(),
|
|
3300
|
-
error: z15.object({
|
|
3301
|
-
code: z15.number().nullish(),
|
|
3302
|
-
message: z15.string(),
|
|
3303
|
-
status: z15.string().nullish()
|
|
3304
|
-
}).nullish(),
|
|
3305
|
-
response: z15.object({
|
|
3306
|
-
generateVideoResponse: z15.object({
|
|
3307
|
-
generatedSamples: z15.array(
|
|
3308
|
-
z15.object({
|
|
3309
|
-
video: z15.object({
|
|
3310
|
-
uri: z15.string().nullish()
|
|
3311
|
-
}).nullish()
|
|
3312
|
-
})
|
|
3313
|
-
).nullish()
|
|
3314
|
-
}).nullish()
|
|
3315
|
-
}).nullish()
|
|
3316
|
-
});
|
|
3317
|
-
var googleVideoModelOptionsSchema = lazySchema13(
|
|
3318
|
-
() => zodSchema13(
|
|
3319
|
-
z15.object({
|
|
3320
|
-
pollIntervalMs: z15.number().positive().nullish(),
|
|
3321
|
-
pollTimeoutMs: z15.number().positive().nullish(),
|
|
3322
|
-
personGeneration: z15.enum(["dont_allow", "allow_adult", "allow_all"]).nullish(),
|
|
3323
|
-
negativePrompt: z15.string().nullish(),
|
|
3324
|
-
referenceImages: z15.array(
|
|
3325
|
-
z15.object({
|
|
3326
|
-
bytesBase64Encoded: z15.string().nullish(),
|
|
3327
|
-
gcsUri: z15.string().nullish()
|
|
3328
|
-
})
|
|
3329
|
-
).nullish()
|
|
3330
|
-
}).passthrough()
|
|
3331
|
-
)
|
|
3332
|
-
);
|
|
3333
|
-
|
|
3334
|
-
// src/google-provider.ts
|
|
3335
|
-
function createGoogleGenerativeAI(options = {}) {
|
|
3336
|
-
var _a, _b;
|
|
3337
|
-
const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://generativelanguage.googleapis.com/v1beta";
|
|
3338
|
-
const providerName = (_b = options.name) != null ? _b : "google.generative-ai";
|
|
3339
|
-
const getHeaders = () => withUserAgentSuffix(
|
|
3340
|
-
{
|
|
3341
|
-
"x-goog-api-key": loadApiKey({
|
|
3342
|
-
apiKey: options.apiKey,
|
|
3343
|
-
environmentVariableName: "GOOGLE_GENERATIVE_AI_API_KEY",
|
|
3344
|
-
description: "Google Generative AI"
|
|
3345
|
-
}),
|
|
3346
|
-
...options.headers
|
|
3347
|
-
},
|
|
3348
|
-
`ai-sdk/google/${VERSION}`
|
|
3349
|
-
);
|
|
3350
|
-
const createChatModel = (modelId) => {
|
|
3351
|
-
var _a2;
|
|
3352
|
-
return new GoogleGenerativeAILanguageModel(modelId, {
|
|
3353
|
-
provider: providerName,
|
|
3354
|
-
baseURL,
|
|
3355
|
-
headers: getHeaders,
|
|
3356
|
-
generateId: (_a2 = options.generateId) != null ? _a2 : generateId2,
|
|
3357
|
-
supportedUrls: () => ({
|
|
3358
|
-
"*": [
|
|
3359
|
-
// Google Generative Language "files" endpoint
|
|
3360
|
-
// e.g. https://generativelanguage.googleapis.com/v1beta/files/...
|
|
3361
|
-
new RegExp(`^${baseURL}/files/.*$`),
|
|
3362
|
-
// YouTube URLs (public or unlisted videos)
|
|
3363
|
-
new RegExp(
|
|
3364
|
-
`^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$`
|
|
3365
|
-
),
|
|
3366
|
-
new RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`)
|
|
3367
|
-
]
|
|
3368
|
-
}),
|
|
3369
|
-
fetch: options.fetch
|
|
3370
|
-
});
|
|
3371
|
-
};
|
|
3372
|
-
const createEmbeddingModel = (modelId) => new GoogleGenerativeAIEmbeddingModel(modelId, {
|
|
3373
|
-
provider: providerName,
|
|
3374
|
-
baseURL,
|
|
3375
|
-
headers: getHeaders,
|
|
3376
|
-
fetch: options.fetch
|
|
3377
|
-
});
|
|
3378
|
-
const createImageModel = (modelId, settings = {}) => new GoogleGenerativeAIImageModel(modelId, settings, {
|
|
3379
|
-
provider: providerName,
|
|
3380
|
-
baseURL,
|
|
3381
|
-
headers: getHeaders,
|
|
3382
|
-
fetch: options.fetch
|
|
3383
|
-
});
|
|
3384
|
-
const createFiles = () => new GoogleGenerativeAIFiles({
|
|
3385
|
-
provider: providerName,
|
|
3386
|
-
baseURL,
|
|
3387
|
-
headers: getHeaders,
|
|
3388
|
-
fetch: options.fetch
|
|
3389
|
-
});
|
|
3390
|
-
const createVideoModel = (modelId) => {
|
|
3391
|
-
var _a2;
|
|
3392
|
-
return new GoogleGenerativeAIVideoModel(modelId, {
|
|
3393
|
-
provider: providerName,
|
|
3394
|
-
baseURL,
|
|
3395
|
-
headers: getHeaders,
|
|
3396
|
-
fetch: options.fetch,
|
|
3397
|
-
generateId: (_a2 = options.generateId) != null ? _a2 : generateId2
|
|
3398
|
-
});
|
|
3399
|
-
};
|
|
3400
|
-
const provider = function(modelId) {
|
|
3401
|
-
if (new.target) {
|
|
3402
|
-
throw new Error(
|
|
3403
|
-
"The Google Generative AI model function cannot be called with the new keyword."
|
|
3404
|
-
);
|
|
3405
|
-
}
|
|
3406
|
-
return createChatModel(modelId);
|
|
3407
|
-
};
|
|
3408
|
-
provider.specificationVersion = "v4";
|
|
3409
|
-
provider.languageModel = createChatModel;
|
|
3410
|
-
provider.chat = createChatModel;
|
|
3411
|
-
provider.generativeAI = createChatModel;
|
|
3412
|
-
provider.embedding = createEmbeddingModel;
|
|
3413
|
-
provider.embeddingModel = createEmbeddingModel;
|
|
3414
|
-
provider.textEmbedding = createEmbeddingModel;
|
|
3415
|
-
provider.textEmbeddingModel = createEmbeddingModel;
|
|
3416
|
-
provider.image = createImageModel;
|
|
3417
|
-
provider.imageModel = createImageModel;
|
|
3418
|
-
provider.video = createVideoModel;
|
|
3419
|
-
provider.videoModel = createVideoModel;
|
|
3420
|
-
provider.files = createFiles;
|
|
3421
|
-
provider.tools = googleTools;
|
|
3422
|
-
return provider;
|
|
3423
|
-
}
|
|
3424
|
-
var google = createGoogleGenerativeAI();
|
|
3425
|
-
export {
|
|
3426
|
-
VERSION,
|
|
3427
|
-
createGoogleGenerativeAI,
|
|
3428
|
-
google
|
|
3429
|
-
};
|
|
3430
|
-
//# sourceMappingURL=index.mjs.map
|