@mastra/server 0.20.1-alpha.3 → 0.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/{chunk-TMU7NSW7.js → chunk-HKW2536J.js} +5852 -2557
  3. package/dist/chunk-HKW2536J.js.map +1 -0
  4. package/dist/{chunk-AFJBHPHA.cjs → chunk-KJJA7GPJ.cjs} +6308 -2994
  5. package/dist/chunk-KJJA7GPJ.cjs.map +1 -0
  6. package/dist/server/handlers/agent-builder.cjs +16 -16
  7. package/dist/server/handlers/agent-builder.js +1 -1
  8. package/dist/server/handlers.cjs +2 -2
  9. package/dist/server/handlers.js +1 -1
  10. package/package.json +6 -6
  11. package/dist/chunk-44GFD2TF.js +0 -419
  12. package/dist/chunk-44GFD2TF.js.map +0 -1
  13. package/dist/chunk-75KU7JB6.cjs +0 -588
  14. package/dist/chunk-75KU7JB6.cjs.map +0 -1
  15. package/dist/chunk-77TGJGDW.cjs +0 -1279
  16. package/dist/chunk-77TGJGDW.cjs.map +0 -1
  17. package/dist/chunk-AFJBHPHA.cjs.map +0 -1
  18. package/dist/chunk-CHDN4NEY.js +0 -1277
  19. package/dist/chunk-CHDN4NEY.js.map +0 -1
  20. package/dist/chunk-EAIAF7Z6.js +0 -571
  21. package/dist/chunk-EAIAF7Z6.js.map +0 -1
  22. package/dist/chunk-TMU7NSW7.js.map +0 -1
  23. package/dist/chunk-WO2SYFUI.js +0 -5945
  24. package/dist/chunk-WO2SYFUI.js.map +0 -1
  25. package/dist/chunk-XCR65STK.cjs +0 -433
  26. package/dist/chunk-XCR65STK.cjs.map +0 -1
  27. package/dist/chunk-YWACVZRO.cjs +0 -5985
  28. package/dist/chunk-YWACVZRO.cjs.map +0 -1
  29. package/dist/dist-36GPHJSB.cjs +0 -2014
  30. package/dist/dist-36GPHJSB.cjs.map +0 -1
  31. package/dist/dist-3WEYC4YO.js +0 -2007
  32. package/dist/dist-3WEYC4YO.js.map +0 -1
  33. package/dist/dist-7MBYKZSM.js +0 -846
  34. package/dist/dist-7MBYKZSM.js.map +0 -1
  35. package/dist/dist-FGYSUA65.cjs +0 -935
  36. package/dist/dist-FGYSUA65.cjs.map +0 -1
  37. package/dist/dist-FNKPY5I5.cjs +0 -1412
  38. package/dist/dist-FNKPY5I5.cjs.map +0 -1
  39. package/dist/dist-H5ZHQKYG.js +0 -3
  40. package/dist/dist-H5ZHQKYG.js.map +0 -1
  41. package/dist/dist-HBUYSRRO.cjs +0 -850
  42. package/dist/dist-HBUYSRRO.cjs.map +0 -1
  43. package/dist/dist-IUCBLZK6.js +0 -1409
  44. package/dist/dist-IUCBLZK6.js.map +0 -1
  45. package/dist/dist-M4HXCUXC.cjs +0 -20
  46. package/dist/dist-M4HXCUXC.cjs.map +0 -1
  47. package/dist/dist-P32YPL35.js +0 -932
  48. package/dist/dist-P32YPL35.js.map +0 -1
@@ -1,1412 +0,0 @@
1
- 'use strict';
2
-
3
- var chunk75KU7JB6_cjs = require('./chunk-75KU7JB6.cjs');
4
- var chunkXCR65STK_cjs = require('./chunk-XCR65STK.cjs');
5
- var v4 = require('zod/v4');
6
-
7
- var googleErrorDataSchema = v4.z.object({
8
- error: v4.z.object({
9
- code: v4.z.number().nullable(),
10
- message: v4.z.string(),
11
- status: v4.z.string()
12
- })
13
- });
14
- var googleFailedResponseHandler = chunk75KU7JB6_cjs.createJsonErrorResponseHandler({
15
- errorSchema: googleErrorDataSchema,
16
- errorToMessage: (data) => data.error.message
17
- });
18
- var googleGenerativeAIEmbeddingProviderOptions = v4.z.object({
19
- /**
20
- * Optional. Optional reduced dimension for the output embedding.
21
- * If set, excessive values in the output embedding are truncated from the end.
22
- */
23
- outputDimensionality: v4.z.number().optional(),
24
- /**
25
- * Optional. Specifies the task type for generating embeddings.
26
- * Supported task types:
27
- * - SEMANTIC_SIMILARITY: Optimized for text similarity.
28
- * - CLASSIFICATION: Optimized for text classification.
29
- * - CLUSTERING: Optimized for clustering texts based on similarity.
30
- * - RETRIEVAL_DOCUMENT: Optimized for document retrieval.
31
- * - RETRIEVAL_QUERY: Optimized for query-based retrieval.
32
- * - QUESTION_ANSWERING: Optimized for answering questions.
33
- * - FACT_VERIFICATION: Optimized for verifying factual information.
34
- * - CODE_RETRIEVAL_QUERY: Optimized for retrieving code blocks based on natural language queries.
35
- */
36
- taskType: v4.z.enum([
37
- "SEMANTIC_SIMILARITY",
38
- "CLASSIFICATION",
39
- "CLUSTERING",
40
- "RETRIEVAL_DOCUMENT",
41
- "RETRIEVAL_QUERY",
42
- "QUESTION_ANSWERING",
43
- "FACT_VERIFICATION",
44
- "CODE_RETRIEVAL_QUERY"
45
- ]).optional()
46
- });
47
- var GoogleGenerativeAIEmbeddingModel = class {
48
- constructor(modelId, config) {
49
- this.specificationVersion = "v2";
50
- this.maxEmbeddingsPerCall = 2048;
51
- this.supportsParallelCalls = true;
52
- this.modelId = modelId;
53
- this.config = config;
54
- }
55
- get provider() {
56
- return this.config.provider;
57
- }
58
- async doEmbed({
59
- values,
60
- headers,
61
- abortSignal,
62
- providerOptions
63
- }) {
64
- const googleOptions = await chunk75KU7JB6_cjs.parseProviderOptions({
65
- provider: "google",
66
- providerOptions,
67
- schema: googleGenerativeAIEmbeddingProviderOptions
68
- });
69
- if (values.length > this.maxEmbeddingsPerCall) {
70
- throw new chunkXCR65STK_cjs.TooManyEmbeddingValuesForCallError({
71
- provider: this.provider,
72
- modelId: this.modelId,
73
- maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
74
- values
75
- });
76
- }
77
- const mergedHeaders = chunk75KU7JB6_cjs.combineHeaders(
78
- await chunk75KU7JB6_cjs.resolve(this.config.headers),
79
- headers
80
- );
81
- if (values.length === 1) {
82
- const {
83
- responseHeaders: responseHeaders2,
84
- value: response2,
85
- rawValue: rawValue2
86
- } = await chunk75KU7JB6_cjs.postJsonToApi({
87
- url: `${this.config.baseURL}/models/${this.modelId}:embedContent`,
88
- headers: mergedHeaders,
89
- body: {
90
- model: `models/${this.modelId}`,
91
- content: {
92
- parts: [{ text: values[0] }]
93
- },
94
- outputDimensionality: googleOptions == null ? void 0 : googleOptions.outputDimensionality,
95
- taskType: googleOptions == null ? void 0 : googleOptions.taskType
96
- },
97
- failedResponseHandler: googleFailedResponseHandler,
98
- successfulResponseHandler: chunk75KU7JB6_cjs.createJsonResponseHandler(
99
- googleGenerativeAISingleEmbeddingResponseSchema
100
- ),
101
- abortSignal,
102
- fetch: this.config.fetch
103
- });
104
- return {
105
- embeddings: [response2.embedding.values],
106
- usage: void 0,
107
- response: { headers: responseHeaders2, body: rawValue2 }
108
- };
109
- }
110
- const {
111
- responseHeaders,
112
- value: response,
113
- rawValue
114
- } = await chunk75KU7JB6_cjs.postJsonToApi({
115
- url: `${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,
116
- headers: mergedHeaders,
117
- body: {
118
- requests: values.map((value) => ({
119
- model: `models/${this.modelId}`,
120
- content: { role: "user", parts: [{ text: value }] },
121
- outputDimensionality: googleOptions == null ? void 0 : googleOptions.outputDimensionality,
122
- taskType: googleOptions == null ? void 0 : googleOptions.taskType
123
- }))
124
- },
125
- failedResponseHandler: googleFailedResponseHandler,
126
- successfulResponseHandler: chunk75KU7JB6_cjs.createJsonResponseHandler(
127
- googleGenerativeAITextEmbeddingResponseSchema
128
- ),
129
- abortSignal,
130
- fetch: this.config.fetch
131
- });
132
- return {
133
- embeddings: response.embeddings.map((item) => item.values),
134
- usage: void 0,
135
- response: { headers: responseHeaders, body: rawValue }
136
- };
137
- }
138
- };
139
- var googleGenerativeAITextEmbeddingResponseSchema = v4.z.object({
140
- embeddings: v4.z.array(v4.z.object({ values: v4.z.array(v4.z.number()) }))
141
- });
142
- var googleGenerativeAISingleEmbeddingResponseSchema = v4.z.object({
143
- embedding: v4.z.object({ values: v4.z.array(v4.z.number()) })
144
- });
145
- function convertJSONSchemaToOpenAPISchema(jsonSchema) {
146
- if (jsonSchema == null || isEmptyObjectSchema(jsonSchema)) {
147
- return void 0;
148
- }
149
- if (typeof jsonSchema === "boolean") {
150
- return { type: "boolean", properties: {} };
151
- }
152
- const {
153
- type,
154
- description,
155
- required,
156
- properties,
157
- items,
158
- allOf,
159
- anyOf,
160
- oneOf,
161
- format,
162
- const: constValue,
163
- minLength,
164
- enum: enumValues
165
- } = jsonSchema;
166
- const result = {};
167
- if (description)
168
- result.description = description;
169
- if (required)
170
- result.required = required;
171
- if (format)
172
- result.format = format;
173
- if (constValue !== void 0) {
174
- result.enum = [constValue];
175
- }
176
- if (type) {
177
- if (Array.isArray(type)) {
178
- if (type.includes("null")) {
179
- result.type = type.filter((t) => t !== "null")[0];
180
- result.nullable = true;
181
- } else {
182
- result.type = type;
183
- }
184
- } else if (type === "null") {
185
- result.type = "null";
186
- } else {
187
- result.type = type;
188
- }
189
- }
190
- if (enumValues !== void 0) {
191
- result.enum = enumValues;
192
- }
193
- if (properties != null) {
194
- result.properties = Object.entries(properties).reduce(
195
- (acc, [key, value]) => {
196
- acc[key] = convertJSONSchemaToOpenAPISchema(value);
197
- return acc;
198
- },
199
- {}
200
- );
201
- }
202
- if (items) {
203
- result.items = Array.isArray(items) ? items.map(convertJSONSchemaToOpenAPISchema) : convertJSONSchemaToOpenAPISchema(items);
204
- }
205
- if (allOf) {
206
- result.allOf = allOf.map(convertJSONSchemaToOpenAPISchema);
207
- }
208
- if (anyOf) {
209
- if (anyOf.some(
210
- (schema) => typeof schema === "object" && (schema == null ? void 0 : schema.type) === "null"
211
- )) {
212
- const nonNullSchemas = anyOf.filter(
213
- (schema) => !(typeof schema === "object" && (schema == null ? void 0 : schema.type) === "null")
214
- );
215
- if (nonNullSchemas.length === 1) {
216
- const converted = convertJSONSchemaToOpenAPISchema(nonNullSchemas[0]);
217
- if (typeof converted === "object") {
218
- result.nullable = true;
219
- Object.assign(result, converted);
220
- }
221
- } else {
222
- result.anyOf = nonNullSchemas.map(convertJSONSchemaToOpenAPISchema);
223
- result.nullable = true;
224
- }
225
- } else {
226
- result.anyOf = anyOf.map(convertJSONSchemaToOpenAPISchema);
227
- }
228
- }
229
- if (oneOf) {
230
- result.oneOf = oneOf.map(convertJSONSchemaToOpenAPISchema);
231
- }
232
- if (minLength !== void 0) {
233
- result.minLength = minLength;
234
- }
235
- return result;
236
- }
237
- function isEmptyObjectSchema(jsonSchema) {
238
- return jsonSchema != null && typeof jsonSchema === "object" && jsonSchema.type === "object" && (jsonSchema.properties == null || Object.keys(jsonSchema.properties).length === 0) && !jsonSchema.additionalProperties;
239
- }
240
- function convertToGoogleGenerativeAIMessages(prompt, options) {
241
- var _a;
242
- const systemInstructionParts = [];
243
- const contents = [];
244
- let systemMessagesAllowed = true;
245
- const isGemmaModel = (_a = options == null ? void 0 : options.isGemmaModel) != null ? _a : false;
246
- for (const { role, content } of prompt) {
247
- switch (role) {
248
- case "system": {
249
- if (!systemMessagesAllowed) {
250
- throw new chunkXCR65STK_cjs.UnsupportedFunctionalityError({
251
- functionality: "system messages are only supported at the beginning of the conversation"
252
- });
253
- }
254
- systemInstructionParts.push({ text: content });
255
- break;
256
- }
257
- case "user": {
258
- systemMessagesAllowed = false;
259
- const parts = [];
260
- for (const part of content) {
261
- switch (part.type) {
262
- case "text": {
263
- parts.push({ text: part.text });
264
- break;
265
- }
266
- case "file": {
267
- const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
268
- parts.push(
269
- part.data instanceof URL ? {
270
- fileData: {
271
- mimeType: mediaType,
272
- fileUri: part.data.toString()
273
- }
274
- } : {
275
- inlineData: {
276
- mimeType: mediaType,
277
- data: chunk75KU7JB6_cjs.convertToBase64(part.data)
278
- }
279
- }
280
- );
281
- break;
282
- }
283
- }
284
- }
285
- contents.push({ role: "user", parts });
286
- break;
287
- }
288
- case "assistant": {
289
- systemMessagesAllowed = false;
290
- contents.push({
291
- role: "model",
292
- parts: content.map((part) => {
293
- var _a2, _b, _c, _d, _e, _f;
294
- switch (part.type) {
295
- case "text": {
296
- return part.text.length === 0 ? void 0 : {
297
- text: part.text,
298
- thoughtSignature: (_b = (_a2 = part.providerOptions) == null ? void 0 : _a2.google) == null ? void 0 : _b.thoughtSignature
299
- };
300
- }
301
- case "reasoning": {
302
- return part.text.length === 0 ? void 0 : {
303
- text: part.text,
304
- thought: true,
305
- thoughtSignature: (_d = (_c = part.providerOptions) == null ? void 0 : _c.google) == null ? void 0 : _d.thoughtSignature
306
- };
307
- }
308
- case "file": {
309
- if (part.mediaType !== "image/png") {
310
- throw new chunkXCR65STK_cjs.UnsupportedFunctionalityError({
311
- functionality: "Only PNG images are supported in assistant messages"
312
- });
313
- }
314
- if (part.data instanceof URL) {
315
- throw new chunkXCR65STK_cjs.UnsupportedFunctionalityError({
316
- functionality: "File data URLs in assistant messages are not supported"
317
- });
318
- }
319
- return {
320
- inlineData: {
321
- mimeType: part.mediaType,
322
- data: chunk75KU7JB6_cjs.convertToBase64(part.data)
323
- }
324
- };
325
- }
326
- case "tool-call": {
327
- return {
328
- functionCall: {
329
- name: part.toolName,
330
- args: part.input
331
- },
332
- thoughtSignature: (_f = (_e = part.providerOptions) == null ? void 0 : _e.google) == null ? void 0 : _f.thoughtSignature
333
- };
334
- }
335
- }
336
- }).filter((part) => part !== void 0)
337
- });
338
- break;
339
- }
340
- case "tool": {
341
- systemMessagesAllowed = false;
342
- contents.push({
343
- role: "user",
344
- parts: content.map((part) => ({
345
- functionResponse: {
346
- name: part.toolName,
347
- response: {
348
- name: part.toolName,
349
- content: part.output.value
350
- }
351
- }
352
- }))
353
- });
354
- break;
355
- }
356
- }
357
- }
358
- if (isGemmaModel && systemInstructionParts.length > 0 && contents.length > 0 && contents[0].role === "user") {
359
- const systemText = systemInstructionParts.map((part) => part.text).join("\n\n");
360
- contents[0].parts.unshift({ text: systemText + "\n\n" });
361
- }
362
- return {
363
- systemInstruction: systemInstructionParts.length > 0 && !isGemmaModel ? { parts: systemInstructionParts } : void 0,
364
- contents
365
- };
366
- }
367
- function getModelPath(modelId) {
368
- return modelId.includes("/") ? modelId : `models/${modelId}`;
369
- }
370
- var googleGenerativeAIProviderOptions = v4.z.object({
371
- responseModalities: v4.z.array(v4.z.enum(["TEXT", "IMAGE"])).optional(),
372
- thinkingConfig: v4.z.object({
373
- thinkingBudget: v4.z.number().optional(),
374
- includeThoughts: v4.z.boolean().optional()
375
- }).optional(),
376
- /**
377
- Optional.
378
- The name of the cached content used as context to serve the prediction.
379
- Format: cachedContents/{cachedContent}
380
- */
381
- cachedContent: v4.z.string().optional(),
382
- /**
383
- * Optional. Enable structured output. Default is true.
384
- *
385
- * This is useful when the JSON Schema contains elements that are
386
- * not supported by the OpenAPI schema version that
387
- * Google Generative AI uses. You can use this to disable
388
- * structured outputs if you need to.
389
- */
390
- structuredOutputs: v4.z.boolean().optional(),
391
- /**
392
- Optional. A list of unique safety settings for blocking unsafe content.
393
- */
394
- safetySettings: v4.z.array(
395
- v4.z.object({
396
- category: v4.z.enum([
397
- "HARM_CATEGORY_UNSPECIFIED",
398
- "HARM_CATEGORY_HATE_SPEECH",
399
- "HARM_CATEGORY_DANGEROUS_CONTENT",
400
- "HARM_CATEGORY_HARASSMENT",
401
- "HARM_CATEGORY_SEXUALLY_EXPLICIT",
402
- "HARM_CATEGORY_CIVIC_INTEGRITY"
403
- ]),
404
- threshold: v4.z.enum([
405
- "HARM_BLOCK_THRESHOLD_UNSPECIFIED",
406
- "BLOCK_LOW_AND_ABOVE",
407
- "BLOCK_MEDIUM_AND_ABOVE",
408
- "BLOCK_ONLY_HIGH",
409
- "BLOCK_NONE",
410
- "OFF"
411
- ])
412
- })
413
- ).optional(),
414
- threshold: v4.z.enum([
415
- "HARM_BLOCK_THRESHOLD_UNSPECIFIED",
416
- "BLOCK_LOW_AND_ABOVE",
417
- "BLOCK_MEDIUM_AND_ABOVE",
418
- "BLOCK_ONLY_HIGH",
419
- "BLOCK_NONE",
420
- "OFF"
421
- ]).optional(),
422
- /**
423
- * Optional. Enables timestamp understanding for audio-only files.
424
- *
425
- * https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/audio-understanding
426
- */
427
- audioTimestamp: v4.z.boolean().optional(),
428
- /**
429
- * Optional. Defines labels used in billing reports. Available on Vertex AI only.
430
- *
431
- * https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/add-labels-to-api-calls
432
- */
433
- labels: v4.z.record(v4.z.string(), v4.z.string()).optional()
434
- });
435
- function prepareTools({
436
- tools,
437
- toolChoice,
438
- modelId
439
- }) {
440
- var _a;
441
- tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
442
- const toolWarnings = [];
443
- const isGemini2 = modelId.includes("gemini-2");
444
- const supportsDynamicRetrieval = modelId.includes("gemini-1.5-flash") && !modelId.includes("-8b");
445
- if (tools == null) {
446
- return { tools: void 0, toolConfig: void 0, toolWarnings };
447
- }
448
- const hasFunctionTools = tools.some((tool) => tool.type === "function");
449
- const hasProviderDefinedTools = tools.some(
450
- (tool) => tool.type === "provider-defined"
451
- );
452
- if (hasFunctionTools && hasProviderDefinedTools) {
453
- toolWarnings.push({
454
- type: "unsupported-tool",
455
- tool: tools.find((tool) => tool.type === "function"),
456
- details: "Cannot mix function tools with provider-defined tools in the same request. Please use either function tools or provider-defined tools, but not both."
457
- });
458
- }
459
- if (hasProviderDefinedTools) {
460
- const googleTools2 = {};
461
- const providerDefinedTools = tools.filter(
462
- (tool) => tool.type === "provider-defined"
463
- );
464
- providerDefinedTools.forEach((tool) => {
465
- switch (tool.id) {
466
- case "google.google_search":
467
- if (isGemini2) {
468
- googleTools2.googleSearch = {};
469
- } else if (supportsDynamicRetrieval) {
470
- googleTools2.googleSearchRetrieval = {
471
- dynamicRetrievalConfig: {
472
- mode: tool.args.mode,
473
- dynamicThreshold: tool.args.dynamicThreshold
474
- }
475
- };
476
- } else {
477
- googleTools2.googleSearchRetrieval = {};
478
- }
479
- break;
480
- case "google.url_context":
481
- if (isGemini2) {
482
- googleTools2.urlContext = {};
483
- } else {
484
- toolWarnings.push({
485
- type: "unsupported-tool",
486
- tool,
487
- details: "The URL context tool is not supported with other Gemini models than Gemini 2."
488
- });
489
- }
490
- break;
491
- case "google.code_execution":
492
- if (isGemini2) {
493
- googleTools2.codeExecution = {};
494
- } else {
495
- toolWarnings.push({
496
- type: "unsupported-tool",
497
- tool,
498
- details: "The code execution tools is not supported with other Gemini models than Gemini 2."
499
- });
500
- }
501
- break;
502
- default:
503
- toolWarnings.push({ type: "unsupported-tool", tool });
504
- break;
505
- }
506
- });
507
- return {
508
- tools: Object.keys(googleTools2).length > 0 ? googleTools2 : void 0,
509
- toolConfig: void 0,
510
- toolWarnings
511
- };
512
- }
513
- const functionDeclarations = [];
514
- for (const tool of tools) {
515
- switch (tool.type) {
516
- case "function":
517
- functionDeclarations.push({
518
- name: tool.name,
519
- description: (_a = tool.description) != null ? _a : "",
520
- parameters: convertJSONSchemaToOpenAPISchema(tool.inputSchema)
521
- });
522
- break;
523
- default:
524
- toolWarnings.push({ type: "unsupported-tool", tool });
525
- break;
526
- }
527
- }
528
- if (toolChoice == null) {
529
- return {
530
- tools: { functionDeclarations },
531
- toolConfig: void 0,
532
- toolWarnings
533
- };
534
- }
535
- const type = toolChoice.type;
536
- switch (type) {
537
- case "auto":
538
- return {
539
- tools: { functionDeclarations },
540
- toolConfig: { functionCallingConfig: { mode: "AUTO" } },
541
- toolWarnings
542
- };
543
- case "none":
544
- return {
545
- tools: { functionDeclarations },
546
- toolConfig: { functionCallingConfig: { mode: "NONE" } },
547
- toolWarnings
548
- };
549
- case "required":
550
- return {
551
- tools: { functionDeclarations },
552
- toolConfig: { functionCallingConfig: { mode: "ANY" } },
553
- toolWarnings
554
- };
555
- case "tool":
556
- return {
557
- tools: { functionDeclarations },
558
- toolConfig: {
559
- functionCallingConfig: {
560
- mode: "ANY",
561
- allowedFunctionNames: [toolChoice.toolName]
562
- }
563
- },
564
- toolWarnings
565
- };
566
- default: {
567
- const _exhaustiveCheck = type;
568
- throw new chunkXCR65STK_cjs.UnsupportedFunctionalityError({
569
- functionality: `tool choice type: ${_exhaustiveCheck}`
570
- });
571
- }
572
- }
573
- }
574
- function mapGoogleGenerativeAIFinishReason({
575
- finishReason,
576
- hasToolCalls
577
- }) {
578
- switch (finishReason) {
579
- case "STOP":
580
- return hasToolCalls ? "tool-calls" : "stop";
581
- case "MAX_TOKENS":
582
- return "length";
583
- case "IMAGE_SAFETY":
584
- case "RECITATION":
585
- case "SAFETY":
586
- case "BLOCKLIST":
587
- case "PROHIBITED_CONTENT":
588
- case "SPII":
589
- return "content-filter";
590
- case "FINISH_REASON_UNSPECIFIED":
591
- case "OTHER":
592
- return "other";
593
- case "MALFORMED_FUNCTION_CALL":
594
- return "error";
595
- default:
596
- return "unknown";
597
- }
598
- }
599
- var groundingChunkSchema = v4.z.object({
600
- web: v4.z.object({ uri: v4.z.string(), title: v4.z.string() }).nullish(),
601
- retrievedContext: v4.z.object({ uri: v4.z.string(), title: v4.z.string() }).nullish()
602
- });
603
- var groundingMetadataSchema = v4.z.object({
604
- webSearchQueries: v4.z.array(v4.z.string()).nullish(),
605
- retrievalQueries: v4.z.array(v4.z.string()).nullish(),
606
- searchEntryPoint: v4.z.object({ renderedContent: v4.z.string() }).nullish(),
607
- groundingChunks: v4.z.array(groundingChunkSchema).nullish(),
608
- groundingSupports: v4.z.array(
609
- v4.z.object({
610
- segment: v4.z.object({
611
- startIndex: v4.z.number().nullish(),
612
- endIndex: v4.z.number().nullish(),
613
- text: v4.z.string().nullish()
614
- }),
615
- segment_text: v4.z.string().nullish(),
616
- groundingChunkIndices: v4.z.array(v4.z.number()).nullish(),
617
- supportChunkIndices: v4.z.array(v4.z.number()).nullish(),
618
- confidenceScores: v4.z.array(v4.z.number()).nullish(),
619
- confidenceScore: v4.z.array(v4.z.number()).nullish()
620
- })
621
- ).nullish(),
622
- retrievalMetadata: v4.z.union([
623
- v4.z.object({
624
- webDynamicRetrievalScore: v4.z.number()
625
- }),
626
- v4.z.object({})
627
- ]).nullish()
628
- });
629
- var googleSearch = chunk75KU7JB6_cjs.createProviderDefinedToolFactory({
630
- id: "google.google_search",
631
- name: "google_search",
632
- inputSchema: v4.z.object({
633
- mode: v4.z.enum(["MODE_DYNAMIC", "MODE_UNSPECIFIED"]).default("MODE_UNSPECIFIED"),
634
- dynamicThreshold: v4.z.number().default(1)
635
- })
636
- });
637
- var urlMetadataSchema = v4.z.object({
638
- retrievedUrl: v4.z.string(),
639
- urlRetrievalStatus: v4.z.string()
640
- });
641
- var urlContextMetadataSchema = v4.z.object({
642
- urlMetadata: v4.z.array(urlMetadataSchema)
643
- });
644
- var urlContext = chunk75KU7JB6_cjs.createProviderDefinedToolFactory({
645
- id: "google.url_context",
646
- name: "url_context",
647
- inputSchema: v4.z.object({})
648
- });
649
- var GoogleGenerativeAILanguageModel = class {
650
- constructor(modelId, config) {
651
- this.specificationVersion = "v2";
652
- var _a;
653
- this.modelId = modelId;
654
- this.config = config;
655
- this.generateId = (_a = config.generateId) != null ? _a : chunk75KU7JB6_cjs.generateId;
656
- }
657
- get provider() {
658
- return this.config.provider;
659
- }
660
- get supportedUrls() {
661
- var _a, _b, _c;
662
- return (_c = (_b = (_a = this.config).supportedUrls) == null ? void 0 : _b.call(_a)) != null ? _c : {};
663
- }
664
- async getArgs({
665
- prompt,
666
- maxOutputTokens,
667
- temperature,
668
- topP,
669
- topK,
670
- frequencyPenalty,
671
- presencePenalty,
672
- stopSequences,
673
- responseFormat,
674
- seed,
675
- tools,
676
- toolChoice,
677
- providerOptions
678
- }) {
679
- var _a, _b;
680
- const warnings = [];
681
- const googleOptions = await chunk75KU7JB6_cjs.parseProviderOptions({
682
- provider: "google",
683
- providerOptions,
684
- schema: googleGenerativeAIProviderOptions
685
- });
686
- if (((_a = googleOptions == null ? void 0 : googleOptions.thinkingConfig) == null ? void 0 : _a.includeThoughts) === true && !this.config.provider.startsWith("google.vertex.")) {
687
- warnings.push({
688
- type: "other",
689
- message: `The 'includeThoughts' option is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`
690
- });
691
- }
692
- const isGemmaModel = this.modelId.toLowerCase().startsWith("gemma-");
693
- const { contents, systemInstruction } = convertToGoogleGenerativeAIMessages(
694
- prompt,
695
- { isGemmaModel }
696
- );
697
- const {
698
- tools: googleTools2,
699
- toolConfig: googleToolConfig,
700
- toolWarnings
701
- } = prepareTools({
702
- tools,
703
- toolChoice,
704
- modelId: this.modelId
705
- });
706
- return {
707
- args: {
708
- generationConfig: {
709
- // standardized settings:
710
- maxOutputTokens,
711
- temperature,
712
- topK,
713
- topP,
714
- frequencyPenalty,
715
- presencePenalty,
716
- stopSequences,
717
- seed,
718
- // response format:
719
- responseMimeType: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? "application/json" : void 0,
720
- responseSchema: (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && // Google GenAI does not support all OpenAPI Schema features,
721
- // so this is needed as an escape hatch:
722
- // TODO convert into provider option
723
- ((_b = googleOptions == null ? void 0 : googleOptions.structuredOutputs) != null ? _b : true) ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : void 0,
724
- ...(googleOptions == null ? void 0 : googleOptions.audioTimestamp) && {
725
- audioTimestamp: googleOptions.audioTimestamp
726
- },
727
- // provider options:
728
- responseModalities: googleOptions == null ? void 0 : googleOptions.responseModalities,
729
- thinkingConfig: googleOptions == null ? void 0 : googleOptions.thinkingConfig
730
- },
731
- contents,
732
- systemInstruction: isGemmaModel ? void 0 : systemInstruction,
733
- safetySettings: googleOptions == null ? void 0 : googleOptions.safetySettings,
734
- tools: googleTools2,
735
- toolConfig: googleToolConfig,
736
- cachedContent: googleOptions == null ? void 0 : googleOptions.cachedContent,
737
- labels: googleOptions == null ? void 0 : googleOptions.labels
738
- },
739
- warnings: [...warnings, ...toolWarnings]
740
- };
741
- }
742
- async doGenerate(options) {
743
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
744
- const { args, warnings } = await this.getArgs(options);
745
- const body = JSON.stringify(args);
746
- const mergedHeaders = chunk75KU7JB6_cjs.combineHeaders(
747
- await chunk75KU7JB6_cjs.resolve(this.config.headers),
748
- options.headers
749
- );
750
- const {
751
- responseHeaders,
752
- value: response,
753
- rawValue: rawResponse
754
- } = await chunk75KU7JB6_cjs.postJsonToApi({
755
- url: `${this.config.baseURL}/${getModelPath(
756
- this.modelId
757
- )}:generateContent`,
758
- headers: mergedHeaders,
759
- body: args,
760
- failedResponseHandler: googleFailedResponseHandler,
761
- successfulResponseHandler: chunk75KU7JB6_cjs.createJsonResponseHandler(responseSchema),
762
- abortSignal: options.abortSignal,
763
- fetch: this.config.fetch
764
- });
765
- const candidate = response.candidates[0];
766
- const content = [];
767
- const parts = (_b = (_a = candidate.content) == null ? void 0 : _a.parts) != null ? _b : [];
768
- const usageMetadata = response.usageMetadata;
769
- let lastCodeExecutionToolCallId;
770
- for (const part of parts) {
771
- if ("executableCode" in part && ((_c = part.executableCode) == null ? void 0 : _c.code)) {
772
- const toolCallId = this.config.generateId();
773
- lastCodeExecutionToolCallId = toolCallId;
774
- content.push({
775
- type: "tool-call",
776
- toolCallId,
777
- toolName: "code_execution",
778
- input: JSON.stringify(part.executableCode),
779
- providerExecuted: true
780
- });
781
- } else if ("codeExecutionResult" in part && part.codeExecutionResult) {
782
- content.push({
783
- type: "tool-result",
784
- // Assumes a result directly follows its corresponding call part.
785
- toolCallId: lastCodeExecutionToolCallId,
786
- toolName: "code_execution",
787
- result: {
788
- outcome: part.codeExecutionResult.outcome,
789
- output: part.codeExecutionResult.output
790
- },
791
- providerExecuted: true
792
- });
793
- lastCodeExecutionToolCallId = void 0;
794
- } else if ("text" in part && part.text != null && part.text.length > 0) {
795
- content.push({
796
- type: part.thought === true ? "reasoning" : "text",
797
- text: part.text,
798
- providerMetadata: part.thoughtSignature ? { google: { thoughtSignature: part.thoughtSignature } } : void 0
799
- });
800
- } else if ("functionCall" in part) {
801
- content.push({
802
- type: "tool-call",
803
- toolCallId: this.config.generateId(),
804
- toolName: part.functionCall.name,
805
- input: JSON.stringify(part.functionCall.args),
806
- providerMetadata: part.thoughtSignature ? { google: { thoughtSignature: part.thoughtSignature } } : void 0
807
- });
808
- } else if ("inlineData" in part) {
809
- content.push({
810
- type: "file",
811
- data: part.inlineData.data,
812
- mediaType: part.inlineData.mimeType
813
- });
814
- }
815
- }
816
- const sources = (_d = extractSources({
817
- groundingMetadata: candidate.groundingMetadata,
818
- generateId: this.config.generateId
819
- })) != null ? _d : [];
820
- for (const source of sources) {
821
- content.push(source);
822
- }
823
- return {
824
- content,
825
- finishReason: mapGoogleGenerativeAIFinishReason({
826
- finishReason: candidate.finishReason,
827
- hasToolCalls: content.some((part) => part.type === "tool-call")
828
- }),
829
- usage: {
830
- inputTokens: (_e = usageMetadata == null ? void 0 : usageMetadata.promptTokenCount) != null ? _e : void 0,
831
- outputTokens: (_f = usageMetadata == null ? void 0 : usageMetadata.candidatesTokenCount) != null ? _f : void 0,
832
- totalTokens: (_g = usageMetadata == null ? void 0 : usageMetadata.totalTokenCount) != null ? _g : void 0,
833
- reasoningTokens: (_h = usageMetadata == null ? void 0 : usageMetadata.thoughtsTokenCount) != null ? _h : void 0,
834
- cachedInputTokens: (_i = usageMetadata == null ? void 0 : usageMetadata.cachedContentTokenCount) != null ? _i : void 0
835
- },
836
- warnings,
837
- providerMetadata: {
838
- google: {
839
- groundingMetadata: (_j = candidate.groundingMetadata) != null ? _j : null,
840
- urlContextMetadata: (_k = candidate.urlContextMetadata) != null ? _k : null,
841
- safetyRatings: (_l = candidate.safetyRatings) != null ? _l : null,
842
- usageMetadata: usageMetadata != null ? usageMetadata : null
843
- }
844
- },
845
- request: { body },
846
- response: {
847
- // TODO timestamp, model id, id
848
- headers: responseHeaders,
849
- body: rawResponse
850
- }
851
- };
852
- }
853
- async doStream(options) {
854
- const { args, warnings } = await this.getArgs(options);
855
- const body = JSON.stringify(args);
856
- const headers = chunk75KU7JB6_cjs.combineHeaders(
857
- await chunk75KU7JB6_cjs.resolve(this.config.headers),
858
- options.headers
859
- );
860
- const { responseHeaders, value: response } = await chunk75KU7JB6_cjs.postJsonToApi({
861
- url: `${this.config.baseURL}/${getModelPath(
862
- this.modelId
863
- )}:streamGenerateContent?alt=sse`,
864
- headers,
865
- body: args,
866
- failedResponseHandler: googleFailedResponseHandler,
867
- successfulResponseHandler: chunk75KU7JB6_cjs.createEventSourceResponseHandler(chunkSchema),
868
- abortSignal: options.abortSignal,
869
- fetch: this.config.fetch
870
- });
871
- let finishReason = "unknown";
872
- const usage = {
873
- inputTokens: void 0,
874
- outputTokens: void 0,
875
- totalTokens: void 0
876
- };
877
- let providerMetadata = void 0;
878
- const generateId3 = this.config.generateId;
879
- let hasToolCalls = false;
880
- let currentTextBlockId = null;
881
- let currentReasoningBlockId = null;
882
- let blockCounter = 0;
883
- const emittedSourceUrls = /* @__PURE__ */ new Set();
884
- let lastCodeExecutionToolCallId;
885
- return {
886
- stream: response.pipeThrough(
887
- new TransformStream({
888
- start(controller) {
889
- controller.enqueue({ type: "stream-start", warnings });
890
- },
891
- transform(chunk, controller) {
892
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
893
- if (options.includeRawChunks) {
894
- controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
895
- }
896
- if (!chunk.success) {
897
- controller.enqueue({ type: "error", error: chunk.error });
898
- return;
899
- }
900
- const value = chunk.value;
901
- const usageMetadata = value.usageMetadata;
902
- if (usageMetadata != null) {
903
- usage.inputTokens = (_a = usageMetadata.promptTokenCount) != null ? _a : void 0;
904
- usage.outputTokens = (_b = usageMetadata.candidatesTokenCount) != null ? _b : void 0;
905
- usage.totalTokens = (_c = usageMetadata.totalTokenCount) != null ? _c : void 0;
906
- usage.reasoningTokens = (_d = usageMetadata.thoughtsTokenCount) != null ? _d : void 0;
907
- usage.cachedInputTokens = (_e = usageMetadata.cachedContentTokenCount) != null ? _e : void 0;
908
- }
909
- const candidate = (_f = value.candidates) == null ? void 0 : _f[0];
910
- if (candidate == null) {
911
- return;
912
- }
913
- const content = candidate.content;
914
- const sources = extractSources({
915
- groundingMetadata: candidate.groundingMetadata,
916
- generateId: generateId3
917
- });
918
- if (sources != null) {
919
- for (const source of sources) {
920
- if (source.sourceType === "url" && !emittedSourceUrls.has(source.url)) {
921
- emittedSourceUrls.add(source.url);
922
- controller.enqueue(source);
923
- }
924
- }
925
- }
926
- if (content != null) {
927
- const parts = (_g = content.parts) != null ? _g : [];
928
- for (const part of parts) {
929
- if ("executableCode" in part && ((_h = part.executableCode) == null ? void 0 : _h.code)) {
930
- const toolCallId = generateId3();
931
- lastCodeExecutionToolCallId = toolCallId;
932
- controller.enqueue({
933
- type: "tool-call",
934
- toolCallId,
935
- toolName: "code_execution",
936
- input: JSON.stringify(part.executableCode),
937
- providerExecuted: true
938
- });
939
- hasToolCalls = true;
940
- } else if ("codeExecutionResult" in part && part.codeExecutionResult) {
941
- const toolCallId = lastCodeExecutionToolCallId;
942
- if (toolCallId) {
943
- controller.enqueue({
944
- type: "tool-result",
945
- toolCallId,
946
- toolName: "code_execution",
947
- result: {
948
- outcome: part.codeExecutionResult.outcome,
949
- output: part.codeExecutionResult.output
950
- },
951
- providerExecuted: true
952
- });
953
- lastCodeExecutionToolCallId = void 0;
954
- }
955
- } else if ("text" in part && part.text != null && part.text.length > 0) {
956
- if (part.thought === true) {
957
- if (currentTextBlockId !== null) {
958
- controller.enqueue({
959
- type: "text-end",
960
- id: currentTextBlockId
961
- });
962
- currentTextBlockId = null;
963
- }
964
- if (currentReasoningBlockId === null) {
965
- currentReasoningBlockId = String(blockCounter++);
966
- controller.enqueue({
967
- type: "reasoning-start",
968
- id: currentReasoningBlockId,
969
- providerMetadata: part.thoughtSignature ? {
970
- google: {
971
- thoughtSignature: part.thoughtSignature
972
- }
973
- } : void 0
974
- });
975
- }
976
- controller.enqueue({
977
- type: "reasoning-delta",
978
- id: currentReasoningBlockId,
979
- delta: part.text,
980
- providerMetadata: part.thoughtSignature ? {
981
- google: { thoughtSignature: part.thoughtSignature }
982
- } : void 0
983
- });
984
- } else {
985
- if (currentReasoningBlockId !== null) {
986
- controller.enqueue({
987
- type: "reasoning-end",
988
- id: currentReasoningBlockId
989
- });
990
- currentReasoningBlockId = null;
991
- }
992
- if (currentTextBlockId === null) {
993
- currentTextBlockId = String(blockCounter++);
994
- controller.enqueue({
995
- type: "text-start",
996
- id: currentTextBlockId,
997
- providerMetadata: part.thoughtSignature ? {
998
- google: {
999
- thoughtSignature: part.thoughtSignature
1000
- }
1001
- } : void 0
1002
- });
1003
- }
1004
- controller.enqueue({
1005
- type: "text-delta",
1006
- id: currentTextBlockId,
1007
- delta: part.text,
1008
- providerMetadata: part.thoughtSignature ? {
1009
- google: { thoughtSignature: part.thoughtSignature }
1010
- } : void 0
1011
- });
1012
- }
1013
- }
1014
- }
1015
- const inlineDataParts = getInlineDataParts(content.parts);
1016
- if (inlineDataParts != null) {
1017
- for (const part of inlineDataParts) {
1018
- controller.enqueue({
1019
- type: "file",
1020
- mediaType: part.inlineData.mimeType,
1021
- data: part.inlineData.data
1022
- });
1023
- }
1024
- }
1025
- const toolCallDeltas = getToolCallsFromParts({
1026
- parts: content.parts,
1027
- generateId: generateId3
1028
- });
1029
- if (toolCallDeltas != null) {
1030
- for (const toolCall of toolCallDeltas) {
1031
- controller.enqueue({
1032
- type: "tool-input-start",
1033
- id: toolCall.toolCallId,
1034
- toolName: toolCall.toolName,
1035
- providerMetadata: toolCall.providerMetadata
1036
- });
1037
- controller.enqueue({
1038
- type: "tool-input-delta",
1039
- id: toolCall.toolCallId,
1040
- delta: toolCall.args,
1041
- providerMetadata: toolCall.providerMetadata
1042
- });
1043
- controller.enqueue({
1044
- type: "tool-input-end",
1045
- id: toolCall.toolCallId,
1046
- providerMetadata: toolCall.providerMetadata
1047
- });
1048
- controller.enqueue({
1049
- type: "tool-call",
1050
- toolCallId: toolCall.toolCallId,
1051
- toolName: toolCall.toolName,
1052
- input: toolCall.args,
1053
- providerMetadata: toolCall.providerMetadata
1054
- });
1055
- hasToolCalls = true;
1056
- }
1057
- }
1058
- }
1059
- if (candidate.finishReason != null) {
1060
- finishReason = mapGoogleGenerativeAIFinishReason({
1061
- finishReason: candidate.finishReason,
1062
- hasToolCalls
1063
- });
1064
- providerMetadata = {
1065
- google: {
1066
- groundingMetadata: (_i = candidate.groundingMetadata) != null ? _i : null,
1067
- urlContextMetadata: (_j = candidate.urlContextMetadata) != null ? _j : null,
1068
- safetyRatings: (_k = candidate.safetyRatings) != null ? _k : null
1069
- }
1070
- };
1071
- if (usageMetadata != null) {
1072
- providerMetadata.google.usageMetadata = usageMetadata;
1073
- }
1074
- }
1075
- },
1076
- flush(controller) {
1077
- if (currentTextBlockId !== null) {
1078
- controller.enqueue({
1079
- type: "text-end",
1080
- id: currentTextBlockId
1081
- });
1082
- }
1083
- if (currentReasoningBlockId !== null) {
1084
- controller.enqueue({
1085
- type: "reasoning-end",
1086
- id: currentReasoningBlockId
1087
- });
1088
- }
1089
- controller.enqueue({
1090
- type: "finish",
1091
- finishReason,
1092
- usage,
1093
- providerMetadata
1094
- });
1095
- }
1096
- })
1097
- ),
1098
- response: { headers: responseHeaders },
1099
- request: { body }
1100
- };
1101
- }
1102
- };
1103
- function getToolCallsFromParts({
1104
- parts,
1105
- generateId: generateId3
1106
- }) {
1107
- const functionCallParts = parts == null ? void 0 : parts.filter(
1108
- (part) => "functionCall" in part
1109
- );
1110
- return functionCallParts == null || functionCallParts.length === 0 ? void 0 : functionCallParts.map((part) => ({
1111
- type: "tool-call",
1112
- toolCallId: generateId3(),
1113
- toolName: part.functionCall.name,
1114
- args: JSON.stringify(part.functionCall.args),
1115
- providerMetadata: part.thoughtSignature ? { google: { thoughtSignature: part.thoughtSignature } } : void 0
1116
- }));
1117
- }
1118
- function getInlineDataParts(parts) {
1119
- return parts == null ? void 0 : parts.filter(
1120
- (part) => "inlineData" in part
1121
- );
1122
- }
1123
- function extractSources({
1124
- groundingMetadata,
1125
- generateId: generateId3
1126
- }) {
1127
- var _a;
1128
- return (_a = groundingMetadata == null ? void 0 : groundingMetadata.groundingChunks) == null ? void 0 : _a.filter(
1129
- (chunk) => chunk.web != null
1130
- ).map((chunk) => ({
1131
- type: "source",
1132
- sourceType: "url",
1133
- id: generateId3(),
1134
- url: chunk.web.uri,
1135
- title: chunk.web.title
1136
- }));
1137
- }
1138
- var contentSchema = v4.z.object({
1139
- parts: v4.z.array(
1140
- v4.z.union([
1141
- // note: order matters since text can be fully empty
1142
- v4.z.object({
1143
- functionCall: v4.z.object({
1144
- name: v4.z.string(),
1145
- args: v4.z.unknown()
1146
- }),
1147
- thoughtSignature: v4.z.string().nullish()
1148
- }),
1149
- v4.z.object({
1150
- inlineData: v4.z.object({
1151
- mimeType: v4.z.string(),
1152
- data: v4.z.string()
1153
- })
1154
- }),
1155
- v4.z.object({
1156
- executableCode: v4.z.object({
1157
- language: v4.z.string(),
1158
- code: v4.z.string()
1159
- }).nullish(),
1160
- codeExecutionResult: v4.z.object({
1161
- outcome: v4.z.string(),
1162
- output: v4.z.string()
1163
- }).nullish(),
1164
- text: v4.z.string().nullish(),
1165
- thought: v4.z.boolean().nullish(),
1166
- thoughtSignature: v4.z.string().nullish()
1167
- })
1168
- ])
1169
- ).nullish()
1170
- });
1171
- var safetyRatingSchema = v4.z.object({
1172
- category: v4.z.string().nullish(),
1173
- probability: v4.z.string().nullish(),
1174
- probabilityScore: v4.z.number().nullish(),
1175
- severity: v4.z.string().nullish(),
1176
- severityScore: v4.z.number().nullish(),
1177
- blocked: v4.z.boolean().nullish()
1178
- });
1179
- var usageSchema = v4.z.object({
1180
- cachedContentTokenCount: v4.z.number().nullish(),
1181
- thoughtsTokenCount: v4.z.number().nullish(),
1182
- promptTokenCount: v4.z.number().nullish(),
1183
- candidatesTokenCount: v4.z.number().nullish(),
1184
- totalTokenCount: v4.z.number().nullish()
1185
- });
1186
- var responseSchema = v4.z.object({
1187
- candidates: v4.z.array(
1188
- v4.z.object({
1189
- content: contentSchema.nullish().or(v4.z.object({}).strict()),
1190
- finishReason: v4.z.string().nullish(),
1191
- safetyRatings: v4.z.array(safetyRatingSchema).nullish(),
1192
- groundingMetadata: groundingMetadataSchema.nullish(),
1193
- urlContextMetadata: urlContextMetadataSchema.nullish()
1194
- })
1195
- ),
1196
- usageMetadata: usageSchema.nullish()
1197
- });
1198
- var chunkSchema = v4.z.object({
1199
- candidates: v4.z.array(
1200
- v4.z.object({
1201
- content: contentSchema.nullish(),
1202
- finishReason: v4.z.string().nullish(),
1203
- safetyRatings: v4.z.array(safetyRatingSchema).nullish(),
1204
- groundingMetadata: groundingMetadataSchema.nullish(),
1205
- urlContextMetadata: urlContextMetadataSchema.nullish()
1206
- })
1207
- ).nullish(),
1208
- usageMetadata: usageSchema.nullish()
1209
- });
1210
- var codeExecution = chunk75KU7JB6_cjs.createProviderDefinedToolFactoryWithOutputSchema({
1211
- id: "google.code_execution",
1212
- name: "code_execution",
1213
- inputSchema: v4.z.object({
1214
- language: v4.z.string().describe("The programming language of the code."),
1215
- code: v4.z.string().describe("The code to be executed.")
1216
- }),
1217
- outputSchema: v4.z.object({
1218
- outcome: v4.z.string().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),
1219
- output: v4.z.string().describe("The output from the code execution.")
1220
- })
1221
- });
1222
- var googleTools = {
1223
- /**
1224
- * Creates a Google search tool that gives Google direct access to real-time web content.
1225
- * Must have name "google_search".
1226
- */
1227
- googleSearch,
1228
- /**
1229
- * Creates a URL context tool that gives Google direct access to real-time web content.
1230
- * Must have name "url_context".
1231
- */
1232
- urlContext,
1233
- /**
1234
- * A tool that enables the model to generate and run Python code.
1235
- * Must have name "code_execution".
1236
- *
1237
- * @note Ensure the selected model supports Code Execution.
1238
- * Multi-tool usage with the code execution tool is typically compatible with Gemini >=2 models.
1239
- *
1240
- * @see https://ai.google.dev/gemini-api/docs/code-execution (Google AI)
1241
- * @see https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/code-execution-api (Vertex AI)
1242
- */
1243
- codeExecution
1244
- };
1245
- var GoogleGenerativeAIImageModel = class {
1246
- constructor(modelId, settings, config) {
1247
- this.modelId = modelId;
1248
- this.settings = settings;
1249
- this.config = config;
1250
- this.specificationVersion = "v2";
1251
- }
1252
- get maxImagesPerCall() {
1253
- var _a;
1254
- return (_a = this.settings.maxImagesPerCall) != null ? _a : 4;
1255
- }
1256
- get provider() {
1257
- return this.config.provider;
1258
- }
1259
- async doGenerate(options) {
1260
- var _a, _b, _c;
1261
- const {
1262
- prompt,
1263
- n = 1,
1264
- size = "1024x1024",
1265
- aspectRatio = "1:1",
1266
- seed,
1267
- providerOptions,
1268
- headers,
1269
- abortSignal
1270
- } = options;
1271
- const warnings = [];
1272
- if (size != null) {
1273
- warnings.push({
1274
- type: "unsupported-setting",
1275
- setting: "size",
1276
- details: "This model does not support the `size` option. Use `aspectRatio` instead."
1277
- });
1278
- }
1279
- if (seed != null) {
1280
- warnings.push({
1281
- type: "unsupported-setting",
1282
- setting: "seed",
1283
- details: "This model does not support the `seed` option through this provider."
1284
- });
1285
- }
1286
- const googleOptions = await chunk75KU7JB6_cjs.parseProviderOptions({
1287
- provider: "google",
1288
- providerOptions,
1289
- schema: googleImageProviderOptionsSchema
1290
- });
1291
- const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
1292
- const parameters = {
1293
- sampleCount: n
1294
- };
1295
- if (aspectRatio != null) {
1296
- parameters.aspectRatio = aspectRatio;
1297
- }
1298
- if (googleOptions) {
1299
- Object.assign(parameters, googleOptions);
1300
- }
1301
- const body = {
1302
- instances: [{ prompt }],
1303
- parameters
1304
- };
1305
- const { responseHeaders, value: response } = await chunk75KU7JB6_cjs.postJsonToApi({
1306
- url: `${this.config.baseURL}/models/${this.modelId}:predict`,
1307
- headers: chunk75KU7JB6_cjs.combineHeaders(await chunk75KU7JB6_cjs.resolve(this.config.headers), headers),
1308
- body,
1309
- failedResponseHandler: googleFailedResponseHandler,
1310
- successfulResponseHandler: chunk75KU7JB6_cjs.createJsonResponseHandler(
1311
- googleImageResponseSchema
1312
- ),
1313
- abortSignal,
1314
- fetch: this.config.fetch
1315
- });
1316
- return {
1317
- images: response.predictions.map(
1318
- (p) => p.bytesBase64Encoded
1319
- ),
1320
- warnings: warnings != null ? warnings : [],
1321
- providerMetadata: {
1322
- google: {
1323
- images: response.predictions.map((prediction) => ({
1324
- // Add any prediction-specific metadata here
1325
- }))
1326
- }
1327
- },
1328
- response: {
1329
- timestamp: currentDate,
1330
- modelId: this.modelId,
1331
- headers: responseHeaders
1332
- }
1333
- };
1334
- }
1335
- };
1336
- var googleImageResponseSchema = v4.z.object({
1337
- predictions: v4.z.array(v4.z.object({ bytesBase64Encoded: v4.z.string() })).default([])
1338
- });
1339
- var googleImageProviderOptionsSchema = v4.z.object({
1340
- personGeneration: v4.z.enum(["dont_allow", "allow_adult", "allow_all"]).nullish(),
1341
- aspectRatio: v4.z.enum(["1:1", "3:4", "4:3", "9:16", "16:9"]).nullish()
1342
- });
1343
- function createGoogleGenerativeAI(options = {}) {
1344
- var _a;
1345
- const baseURL = (_a = chunk75KU7JB6_cjs.withoutTrailingSlash(options.baseURL)) != null ? _a : "https://generativelanguage.googleapis.com/v1beta";
1346
- const getHeaders = () => ({
1347
- "x-goog-api-key": chunk75KU7JB6_cjs.loadApiKey({
1348
- apiKey: options.apiKey,
1349
- environmentVariableName: "GOOGLE_GENERATIVE_AI_API_KEY",
1350
- description: "Google Generative AI"
1351
- }),
1352
- ...options.headers
1353
- });
1354
- const createChatModel = (modelId) => {
1355
- var _a2;
1356
- return new GoogleGenerativeAILanguageModel(modelId, {
1357
- provider: "google.generative-ai",
1358
- baseURL,
1359
- headers: getHeaders,
1360
- generateId: (_a2 = options.generateId) != null ? _a2 : chunk75KU7JB6_cjs.generateId,
1361
- supportedUrls: () => ({
1362
- "*": [
1363
- // Google Generative Language "files" endpoint
1364
- // e.g. https://generativelanguage.googleapis.com/v1beta/files/...
1365
- new RegExp(`^${baseURL}/files/.*$`),
1366
- // YouTube URLs (public or unlisted videos)
1367
- new RegExp(
1368
- `^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$`
1369
- ),
1370
- new RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`)
1371
- ]
1372
- }),
1373
- fetch: options.fetch
1374
- });
1375
- };
1376
- const createEmbeddingModel = (modelId) => new GoogleGenerativeAIEmbeddingModel(modelId, {
1377
- provider: "google.generative-ai",
1378
- baseURL,
1379
- headers: getHeaders,
1380
- fetch: options.fetch
1381
- });
1382
- const createImageModel = (modelId, settings = {}) => new GoogleGenerativeAIImageModel(modelId, settings, {
1383
- provider: "google.generative-ai",
1384
- baseURL,
1385
- headers: getHeaders,
1386
- fetch: options.fetch
1387
- });
1388
- const provider = function(modelId) {
1389
- if (new.target) {
1390
- throw new Error(
1391
- "The Google Generative AI model function cannot be called with the new keyword."
1392
- );
1393
- }
1394
- return createChatModel(modelId);
1395
- };
1396
- provider.languageModel = createChatModel;
1397
- provider.chat = createChatModel;
1398
- provider.generativeAI = createChatModel;
1399
- provider.embedding = createEmbeddingModel;
1400
- provider.textEmbedding = createEmbeddingModel;
1401
- provider.textEmbeddingModel = createEmbeddingModel;
1402
- provider.image = createImageModel;
1403
- provider.imageModel = createImageModel;
1404
- provider.tools = googleTools;
1405
- return provider;
1406
- }
1407
- var google = createGoogleGenerativeAI();
1408
-
1409
- exports.createGoogleGenerativeAI = createGoogleGenerativeAI;
1410
- exports.google = google;
1411
- //# sourceMappingURL=dist-FNKPY5I5.cjs.map
1412
- //# sourceMappingURL=dist-FNKPY5I5.cjs.map