Marcos commited on
Commit
20fc799
·
1 Parent(s): ea05406

backendupdated

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. {backend → backend-old}/azureTtsService.js +0 -0
  2. backend-old/index.js +447 -0
  3. backend-old/node_modules/.bin/mime +1 -0
  4. backend-old/node_modules/.bin/nodemon +1 -0
  5. backend-old/node_modules/.bin/nodetouch +1 -0
  6. backend-old/node_modules/.bin/nopt +1 -0
  7. backend-old/node_modules/.bin/openai +1 -0
  8. backend-old/node_modules/.bin/semver +1 -0
  9. backend-old/node_modules/.package-lock.json +1458 -0
  10. backend-old/node_modules/@google/generative-ai/LICENSE +202 -0
  11. backend-old/node_modules/@google/generative-ai/README.md +20 -0
  12. backend-old/node_modules/@google/generative-ai/dist/generative-ai.d.ts +1395 -0
  13. backend-old/node_modules/@google/generative-ai/dist/index.js +1530 -0
  14. backend-old/node_modules/@google/generative-ai/dist/index.js.map +1 -0
  15. backend-old/node_modules/@google/generative-ai/dist/index.mjs +1520 -0
  16. backend-old/node_modules/@google/generative-ai/dist/index.mjs.map +1 -0
  17. backend-old/node_modules/@google/generative-ai/dist/scripts/check-format.d.ts +17 -0
  18. backend-old/node_modules/@google/generative-ai/dist/scripts/format-patterns.d.ts +18 -0
  19. backend-old/node_modules/@google/generative-ai/dist/scripts/license.d.ts +17 -0
  20. backend-old/node_modules/@google/generative-ai/dist/scripts/run-format.d.ts +17 -0
  21. backend-old/node_modules/@google/generative-ai/dist/server/index.js +838 -0
  22. backend-old/node_modules/@google/generative-ai/dist/server/index.js.map +1 -0
  23. backend-old/node_modules/@google/generative-ai/dist/server/index.mjs +835 -0
  24. backend-old/node_modules/@google/generative-ai/dist/server/index.mjs.map +1 -0
  25. backend-old/node_modules/@google/generative-ai/dist/server/scripts/check-format.d.ts +17 -0
  26. backend-old/node_modules/@google/generative-ai/dist/server/scripts/format-patterns.d.ts +18 -0
  27. backend-old/node_modules/@google/generative-ai/dist/server/scripts/license.d.ts +17 -0
  28. backend-old/node_modules/@google/generative-ai/dist/server/scripts/run-format.d.ts +17 -0
  29. backend-old/node_modules/@google/generative-ai/dist/server/server.d.ts +875 -0
  30. backend-old/node_modules/@google/generative-ai/dist/server/src/errors.d.ts +57 -0
  31. backend-old/node_modules/@google/generative-ai/dist/server/src/gen-ai.d.ts +36 -0
  32. backend-old/node_modules/@google/generative-ai/dist/server/src/index.d.ts +19 -0
  33. backend-old/node_modules/@google/generative-ai/dist/server/src/methods/chat-session-helpers.d.ts +22 -0
  34. backend-old/node_modules/@google/generative-ai/dist/server/src/methods/chat-session.d.ts +57 -0
  35. backend-old/node_modules/@google/generative-ai/dist/server/src/methods/count-tokens.d.ts +18 -0
  36. backend-old/node_modules/@google/generative-ai/dist/server/src/methods/embed-content.d.ts +19 -0
  37. backend-old/node_modules/@google/generative-ai/dist/server/src/methods/generate-content.d.ts +19 -0
  38. backend-old/node_modules/@google/generative-ai/dist/server/src/models/generative-model.d.ts +83 -0
  39. backend-old/node_modules/@google/generative-ai/dist/server/src/requests/request-helpers.d.ts +22 -0
  40. backend-old/node_modules/@google/generative-ai/dist/server/src/requests/request.d.ts +46 -0
  41. backend-old/node_modules/@google/generative-ai/dist/server/src/requests/response-helpers.d.ts +31 -0
  42. backend-old/node_modules/@google/generative-ai/dist/server/src/requests/stream-reader.d.ts +37 -0
  43. backend-old/node_modules/@google/generative-ai/dist/server/src/server/cache-manager.d.ts +47 -0
  44. backend-old/node_modules/@google/generative-ai/dist/server/src/server/constants.d.ts +24 -0
  45. backend-old/node_modules/@google/generative-ai/dist/server/src/server/file-manager.d.ts +57 -0
  46. backend-old/node_modules/@google/generative-ai/dist/server/src/server/index.d.ts +19 -0
  47. backend-old/node_modules/@google/generative-ai/dist/server/src/server/request.d.ts +42 -0
  48. backend-old/node_modules/@google/generative-ai/dist/server/types/content.d.ts +230 -0
  49. backend-old/node_modules/@google/generative-ai/dist/server/types/enums.d.ts +120 -0
  50. backend-old/node_modules/@google/generative-ai/dist/server/types/function-calling.d.ts +241 -0
{backend → backend-old}/azureTtsService.js RENAMED
File without changes
backend-old/index.js ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { exec, spawn } from "child_process";
2
+ import cors from "cors";
3
+ import dotenv from "dotenv";
4
+ import voice from "elevenlabs-node";
5
+ import express from "express";
6
+ import { promises as fs } from "fs";
7
+ import { GoogleGenerativeAI } from "@google/generative-ai";
8
+ import path from "path";
9
+ import { fileURLToPath } from "url";
10
+ import * as sdk from "microsoft-cognitiveservices-speech-sdk";
11
+ import { synthesizeSpeechWithVisemes } from "./azureTtsService.js";
12
+ dotenv.config();
13
+
14
+
15
+
16
+ // Validate environment and API keys
17
+ console.log(`Node environment: ${process.env.NODE_ENV}`);
18
+ console.log(`Running on port: ${process.env.PORT || 3000}`);
19
+
20
+ // Check for required API keys
21
+ const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
22
+ const ELEVEN_LABS_API_KEY = process.env.ELEVEN_LABS_API_KEY;
23
+
24
+ // Azure Speech Configuration - Using hardcoded values directly
25
+ const AZURE_SPEECH_KEY = "dd32a86f9b52496b9504bddadb2a5602"; // Hardcoded value
26
+ const AZURE_SPEECH_REGION = "westeurope"; // Hardcoded value
27
+
28
+ console.log(`Gemini API Key: ${GEMINI_API_KEY ? 'Present' : 'Missing'}`);
29
+ console.log(`ElevenLabs API Key: ${ELEVEN_LABS_API_KEY ? 'Present' : 'Missing'}`);
30
+ console.log(`Azure Speech Key: Present (Hardcoded)`);
31
+ console.log(`Azure Speech Region: Present (Hardcoded)`);
32
+
33
+ // Para obter o diretório atual do arquivo em ESM
34
+ const __filename = fileURLToPath(import.meta.url);
35
+ const __dirname = path.dirname(__filename);
36
+
37
+ // Simple in-memory store for conversation history
38
+ let conversationHistory = [];
39
+ const MAX_HISTORY_LENGTH = 6; // Keep only the last 6 messages (3 exchanges) for faster processing
40
+
41
+ // Function to prune conversation history to keep it under the limit
42
+ function pruneConversationHistory(history) {
43
+ if (history.length <= MAX_HISTORY_LENGTH) return history;
44
+ return history.slice(history.length - MAX_HISTORY_LENGTH);
45
+ }
46
+
47
+ // System instructions for Gemini
48
+ const systemInstructions = `Eres una amiga virtual que se llama Alice, un avatar virtual con cuerpo completo. IMPORTANTE: Responde en español de forma EXTREMADAMENTE BREVE (máximo 10-15 palabras). Usa frases simples y directas. ¡Sé siempre muy animada y expresiva en tus movimientos! NO utilices caracteres especiales, emoticones, emojis o cualquier formato que no sea texto simple. Mantén tus respuestas directas para que la conversación fluya naturalmente. Adicionalmente, sugiere una facialExpression y una animation ADECUADAS Y VARIADAS para tu respuesta, en formato JSON al final de tu respuesta principal.
49
+
50
+ Lista de facialExpression disponibles: smile, sad, angry, surprised, funnyFace, default, wink, skeptical, thoughtful, excited, fearful, bored.
51
+ Lista de animation disponibles: Talking_0, Talking_1, Talking_2, Crying, Laughing, Rumba, Idle, Terrified, Angry, Wave, Nod, ShakeHead, Shrug, Think, Celebrate, Sigh, Facepalm, Explain_Gesture.
52
+
53
+ Ejemplo de formato: { "facialExpression": "smile", "animation": "Talking_1" }.
54
+
55
+ Por favor, escucha el audio del usuario para responder.`;
56
+
57
+
58
+ // Azure Viseme Mapping (from user's script)
59
+ const azureVisemeToCharacterMap = {
60
+ 0: "X", 1: "C", 2: "C", 3: "C", 4: "C", 5: "C", 6: "C", 7: "C", 8: "C",
61
+ 9: "C", 10: "C", 11: "C", 12: "D", 13: "D", 14: "D", 15: "D", 16: "D",
62
+ 17: "D", 18: "D", 19: "D", 20: "D", 21: "B"
63
+ };
64
+
65
+ const geminiAPIKey = process.env.GEMINI_API_KEY;
66
+ if (!geminiAPIKey) {
67
+ console.warn("GEMINI_API_KEY not found in .env file. Voice chat with Gemini will not work.");
68
+ }
69
+ const genAI = new GoogleGenerativeAI(geminiAPIKey || "YOUR_GEMINI_API_KEY_FALLBACK"); // Added fallback to prevent crash if key is missing
70
+
71
+ // Define the models to try in order of preference
72
+ const geminiModels = [
73
+ "gemini-2.0-flash", // Fastest: 0.6950 seconds
74
+ "gemini-2.0-flash-lite-001", // Second: 0.8450 seconds
75
+ "gemini-1.5-flash" // Third: 1.3020 seconds
76
+ ];
77
+
78
+ // Optimized generation config for faster responses
79
+ const optimizedGenerationConfig = {
80
+ maxOutputTokens: 100, // Limit output size for faster generation
81
+ temperature: 0.4, // Lower temperature = more deterministic and typically faster
82
+ topP: 0.8, // Slightly lower than default for more focused outputs
83
+ topK: 20, // Limits token selection for faster inference
84
+ candidateCount: 1, // Only generate one response
85
+ presencePenalty: 0.1, // Slight penalty for repeated topics
86
+ stopSequences: ["."], // Encourages shorter responses
87
+ responseMimeType: "text/plain" // Optimize for plain text responses
88
+ };
89
+
90
+ // Initial model
91
+ const geminiModel = genAI.getGenerativeModel({
92
+ model: geminiModels[0],
93
+ generationConfig: optimizedGenerationConfig
94
+ });
95
+
96
+ const elevenLabsApiKey = process.env.ELEVEN_LABS_API_KEY;
97
+ const voiceID = "Xb7hH8MSUJpSbSDYk0k2"; // Adam voice - default voice that works with all accounts
98
+
99
+ const app = express();
100
+ app.use(express.json({ limit: "50mb" }));
101
+ app.use(cors());
102
+ const port = process.env.PORT || 3000;
103
+
104
+ // Define API routes before static file serving
105
+ app.get("/health", (req, res) => {
106
+ res.status(200).json({ status: "OK", message: "API is up and running" });
107
+ });
108
+
109
+ app.get("/voices", async (req, res) => {
110
+ res.send(await voice.getVoices(elevenLabsApiKey));
111
+ });
112
+
113
+ const readJsonTranscript = async (file) => {
114
+ const data = await fs.readFile(file, "utf8");
115
+ return JSON.parse(data);
116
+ };
117
+
118
+ const audioFileToBase64 = async (file) => {
119
+ const data = await fs.readFile(file);
120
+ return data.toString("base64");
121
+ };
122
+
123
+ app.post("/voice-chat", async (req, res) => {
124
+ if (!geminiAPIKey) {
125
+ return res.status(500).send({ error: "Gemini API key not configured." });
126
+ }
127
+
128
+ const { audio: audioFloatArray, sampleRate } = req.body;
129
+
130
+ if (!audioFloatArray || !sampleRate) {
131
+ return res.status(400).send({ error: "Missing audio data or sampleRate." });
132
+ }
133
+
134
+ try {
135
+ const pcmData = floatTo16BitPCM(audioFloatArray);
136
+ const wavBuffer = createWavBuffer(pcmData, sampleRate);
137
+ const audioBase64 = wavBuffer.toString("base64");
138
+
139
+ const partsForGemini = [];
140
+ // If history is empty, it's the first meaningful user interaction in this session.
141
+ // Prepend system instructions as part of the first user message to Gemini.
142
+ if (conversationHistory.length === 0) {
143
+ partsForGemini.push({ text: systemInstructions });
144
+ }
145
+ partsForGemini.push({ inlineData: { data: audioBase64, mimeType: "audio/wav" } });
146
+
147
+ // Try to send the message with a retry mechanism for Gemini models
148
+ let result;
149
+ let retryCount = 0;
150
+ const maxRetries = 3; // Try the entire model cycle up to 3 times
151
+ let modelIndex = 0;
152
+ let currentModel;
153
+ let success = false;
154
+
155
+ while (retryCount < maxRetries && !success) {
156
+ // Reset model index if we've gone through all models
157
+ if (modelIndex >= geminiModels.length) {
158
+ modelIndex = 0;
159
+ retryCount++;
160
+ if (retryCount >= maxRetries) break;
161
+ }
162
+
163
+ currentModel = geminiModels[modelIndex];
164
+ console.log(`Attempt ${retryCount+1}/${maxRetries}, trying model: ${currentModel}`);
165
+
166
+ try {
167
+ // Get a new model instance with the current model
168
+ const modelInstance = genAI.getGenerativeModel({
169
+ model: currentModel,
170
+ generationConfig: optimizedGenerationConfig
171
+ });
172
+ const chat = modelInstance.startChat({
173
+ history: conversationHistory,
174
+ });
175
+
176
+ result = await chat.sendMessage(partsForGemini);
177
+ success = true; // If we got here, it worked!
178
+
179
+ // Update conversation history after the call
180
+ conversationHistory = await chat.getHistory();
181
+ // Prune history to keep only recent messages
182
+ conversationHistory = pruneConversationHistory(conversationHistory);
183
+ console.log(`Successfully used model: ${currentModel}`);
184
+ break;
185
+
186
+ } catch (error) {
187
+ console.error(`Error with model ${currentModel}:`, error.message || error);
188
+ // Try the next model
189
+ modelIndex++;
190
+ }
191
+ }
192
+
193
+ if (!success || !result) {
194
+ throw new Error(`Failed to get a response from any Gemini model after ${maxRetries} complete retry cycles`);
195
+ }
196
+
197
+ const response = result.response;
198
+ const geminiTextRaw = response.text();
199
+
200
+ console.log("Gemini Raw Response:", geminiTextRaw);
201
+ console.log("Updated Conversation History Length:", conversationHistory.length);
202
+
203
+ let geminiTextForTTS = geminiTextRaw; // Text that will be sent to TTS
204
+ let facialExpression = "default";
205
+ let animation = "Idle";
206
+
207
+ try {
208
+ // More robustly find and extract the JSON part, accounting for potential markdown code blocks
209
+ // Regex to find a JSON object, possibly wrapped in markdown ```json ... ``` or ``` ... ```
210
+ const jsonBlockRegex = /```(?:json)?\s*(\{[^\}]*\})\s*```|(\{[^\}]*\})/s;
211
+ const jsonMatch = geminiTextRaw.match(jsonBlockRegex);
212
+
213
+ let jsonString = null;
214
+ let textPart = geminiTextRaw;
215
+
216
+ if (jsonMatch) {
217
+ // Prioritize the JSON found within a markdown block, otherwise take the standalone JSON
218
+ jsonString = jsonMatch[1] || jsonMatch[2];
219
+ if (jsonString) {
220
+ try {
221
+ console.log("Found JSON string for suggestions:", jsonString);
222
+ const suggestions = JSON.parse(jsonString);
223
+ if (suggestions.facialExpression) facialExpression = suggestions.facialExpression;
224
+ if (suggestions.animation) animation = suggestions.animation;
225
+
226
+ // Remove the entire matched block (markdown + JSON or just JSON) from the original text
227
+ textPart = geminiTextRaw.replace(jsonMatch[0], "").trim();
228
+ } catch (parseError) {
229
+ console.warn("Could not parse JSON from Gemini response:", parseError);
230
+ // If JSON parsing fails, assume the entire response is text
231
+ textPart = geminiTextRaw.trim();
232
+ }
233
+ } else {
234
+ // Should not happen if jsonMatch is true, but as a fallback
235
+ textPart = geminiTextRaw.trim();
236
+ }
237
+ } else {
238
+ // If no JSON-like structure is found, the whole response is considered text for TTS.
239
+ textPart = geminiTextRaw.trim();
240
+ }
241
+ geminiTextForTTS = textPart;
242
+
243
+ } catch (e) {
244
+ console.warn("Error processing facial expression/animation from Gemini response:", e);
245
+ // Keep geminiTextForTTS as the original raw text, trimmed, in case of unexpected errors.
246
+ geminiTextForTTS = geminiTextRaw.trim();
247
+ }
248
+
249
+ if (!geminiTextForTTS || geminiTextForTTS.trim() === "") {
250
+ geminiTextForTTS = "No pude procesar el audio, ¿puedes repetirlo por favor?";
251
+ facialExpression = "sad";
252
+ animation = "Talking_0";
253
+ }
254
+
255
+ // 3. Prepare message for existing TTS/Lipsync pipeline
256
+ let messagesToProcess = [
257
+ {
258
+ text: geminiTextForTTS, // Use the cleaned text for TTS
259
+ facialExpression: facialExpression,
260
+ animation: animation,
261
+ // audio and lipsync will be added by the loop below
262
+ },
263
+ ];
264
+
265
+ // 4. Process the messages
266
+ for (let i = 0; i < messagesToProcess.length; i++) {
267
+ const message = messagesToProcess[i];
268
+ const textInput = message.text;
269
+
270
+ if (!textInput || textInput.trim() === "") {
271
+ console.warn("Skipping TTS for empty message from Gemini at index " + i);
272
+ message.audio = ""; // Or a silent audio base64
273
+ message.lipsync = { metadata: { version: 1 }, mouthCues: [{ start: 0, end: 1, value: "X" }] }; // Empty lipsync
274
+ continue;
275
+ }
276
+
277
+ try {
278
+ // Use the Spanish language and Elena voice from Argentina
279
+ const language = "es-AR";
280
+ const voiceName = "es-AR-ElenaNeural";
281
+
282
+ // Use the imported synthesizeSpeechWithVisemes function
283
+ const azureResult = await synthesizeSpeechWithVisemes(textInput, language, voiceName);
284
+
285
+ // Convert the result to the expected format
286
+ message.audio = azureResult.audioData.toString('base64'); // Convert Buffer to base64
287
+ message.lipsync = { mouthCues: azureResult.mouthCues }; // Extract mouth cues
288
+
289
+ } catch (azureError) {
290
+ console.error("Error in Azure TTS/Viseme generation for message: " + textInput, azureError);
291
+ // Fallback if Azure TTS or lipsync fails
292
+ message.text = "Lo siento, tuve un problema al generar mi respuesta con Azure.";
293
+ message.audio = "";
294
+ message.lipsync = { metadata: { version: 1, generator: "fallback-azure-error" }, mouthCues: [{ start: 0, end: 1, value: "X" }] };
295
+ message.facialExpression = "sad";
296
+ message.animation = "Idle";
297
+ }
298
+ }
299
+ res.send({ messages: messagesToProcess });
300
+
301
+ } catch (error) {
302
+ console.error("Error in /voice-chat endpoint:", error);
303
+ // Generic error response
304
+ const fallbackMessage = {
305
+ text: "Ups, algo salió mal en el servidor.",
306
+ audio: "", // Consider having a pre-recorded base64 audio for errors
307
+ lipsync: { metadata: { version: 1 }, mouthCues: [{ start: 0, end: 0.5, value: "X" }] },
308
+ facialExpression: "sad",
309
+ animation: "Idle",
310
+ };
311
+ res.status(500).send({ messages: [fallbackMessage] });
312
+ }
313
+ });
314
+
315
+ // Helper function to convert float array to 16-bit PCM WAV buffer - optimized version
316
+ function floatTo16BitPCM(floatArray) {
317
+ // Pre-allocate the array for better performance
318
+ const pcmArray = new Int16Array(floatArray.length);
319
+
320
+ // Process the array in chunks for better performance
321
+ const CHUNK_SIZE = 1024;
322
+ for (let i = 0; i < floatArray.length; i += CHUNK_SIZE) {
323
+ const end = Math.min(i + CHUNK_SIZE, floatArray.length);
324
+ for (let j = i; j < end; j++) {
325
+ // Clamp values between -1 and 1, then scale to 16-bit range
326
+ // Use faster conditional approach instead of Math.max/min
327
+ const s = floatArray[j] < -1 ? -1 : (floatArray[j] > 1 ? 1 : floatArray[j]);
328
+ // Use bit shifting for faster integer conversion when appropriate
329
+ pcmArray[j] = s < 0 ? s * 0x8000 : s * 0x7FFF;
330
+ }
331
+ }
332
+
333
+ return pcmArray;
334
+ }
335
+
336
+ function createWavBuffer(pcmData, sampleRate) {
337
+ const numChannels = 1;
338
+ const bitsPerSample = 16;
339
+ const blockAlign = numChannels * (bitsPerSample / 8);
340
+ const byteRate = sampleRate * blockAlign;
341
+ const dataSize = pcmData.length * (bitsPerSample / 8);
342
+ const bufferSize = 44 + dataSize; // 44 bytes for WAV header
343
+
344
+ // Pre-allocate a buffer of the exact needed size
345
+ const buffer = Buffer.alloc(bufferSize);
346
+ let offset = 0;
347
+
348
+ // Write header in fewer operations by using strings directly
349
+ buffer.write("RIFF", offset); offset += 4;
350
+ buffer.writeUInt32LE(36 + dataSize, offset); offset += 4;
351
+ buffer.write("WAVE", offset); offset += 4;
352
+ buffer.write("fmt ", offset); offset += 4;
353
+
354
+ // Write format chunk in a single operation if possible
355
+ buffer.writeUInt32LE(16, offset); offset += 4; // Subchunk1Size (16 for PCM)
356
+ buffer.writeUInt16LE(1, offset); offset += 2; // AudioFormat (1 for PCM)
357
+ buffer.writeUInt16LE(numChannels, offset); offset += 2;
358
+ buffer.writeUInt32LE(sampleRate, offset); offset += 4;
359
+ buffer.writeUInt32LE(byteRate, offset); offset += 4;
360
+ buffer.writeUInt16LE(blockAlign, offset); offset += 2;
361
+ buffer.writeUInt16LE(bitsPerSample, offset); offset += 2;
362
+
363
+ // Write data subchunk
364
+ buffer.write("data", offset); offset += 4;
365
+ buffer.writeUInt32LE(dataSize, offset); offset += 4;
366
+
367
+ // Write PCM data in larger chunks for better performance
368
+ const CHUNK_SIZE = 1024;
369
+ for (let i = 0; i < pcmData.length; i += CHUNK_SIZE) {
370
+ const end = Math.min(i + CHUNK_SIZE, pcmData.length);
371
+ for (let j = i; j < end; j++) {
372
+ buffer.writeInt16LE(pcmData[j], offset);
373
+ offset += 2;
374
+ }
375
+ }
376
+
377
+ return buffer;
378
+ }
379
+
380
+ // Create directory for audio files if it doesn't exist
381
+ try {
382
+ const audiosPath = path.join(__dirname, 'audios');
383
+ try {
384
+ await fs.access(audiosPath);
385
+ } catch {
386
+ await fs.mkdir(audiosPath, { recursive: true });
387
+ console.log('Created audios directory');
388
+ }
389
+ } catch (err) {
390
+ console.error('Failed to create audios directory:', err);
391
+ }
392
+
393
+ // Create public directory if it doesn't exist
394
+ try {
395
+ const publicPath = path.join(__dirname, 'public');
396
+ try {
397
+ await fs.access(publicPath);
398
+ } catch {
399
+ await fs.mkdir(publicPath, { recursive: true });
400
+ console.log('Created public directory');
401
+ }
402
+ } catch (err) {
403
+ console.error('Failed to create public directory:', err);
404
+ }
405
+
406
+ // Serve static files from the public directory (frontend build)
407
+ app.use(express.static(path.join(__dirname, 'public')));
408
+
409
+ // Add more detailed logging for debugging deployment issues
410
+ console.log(`Static files being served from: ${path.join(__dirname, 'public')}`);
411
+ try {
412
+ const publicFiles = await fs.readdir(path.join(__dirname, 'public'));
413
+ console.log(`Public directory contents: ${publicFiles.join(', ')}`);
414
+ if (publicFiles.includes('index.html')) {
415
+ console.log('Found index.html in public directory');
416
+ } else {
417
+ console.warn('WARNING: index.html not found in public directory!');
418
+ }
419
+ } catch (err) {
420
+ console.error(`Error reading public directory: ${err.message}`);
421
+ }
422
+
423
+ // Fallback to serve index.html for all routes (for SPA routing)
424
+ app.get("*", (req, res) => {
425
+ console.log(`Serving index.html for path: ${req.path}`);
426
+ res.sendFile(path.join(__dirname, 'public', 'index.html'));
427
+ });
428
+
429
+ // Handle 404s for resources that don't exist
430
+ app.use((req, res, next) => {
431
+ console.log(`404 for: ${req.path}`);
432
+ res.status(404).send('Resource not found');
433
+ });
434
+
435
+ // Start the server
436
+ app.listen(port, '0.0.0.0', () => {
437
+ console.log(`=============================================================`);
438
+ console.log(`Virtual Girlfriend server is running at:`);
439
+ console.log(`- Local: http://localhost:${port}`);
440
+ console.log(`- Network: http://0.0.0.0:${port}`);
441
+ console.log(`=============================================================`);
442
+ console.log(`- Environment: ${process.env.NODE_ENV || 'development'}`);
443
+ console.log(`- Node version: ${process.version}`);
444
+ console.log(`- Platform: ${process.platform} ${process.arch}`);
445
+ console.log(`- Working directory: ${__dirname}`);
446
+ console.log(`=============================================================`);
447
+ });
backend-old/node_modules/.bin/mime ADDED
@@ -0,0 +1 @@
 
 
1
+ ../mime/cli.js
backend-old/node_modules/.bin/nodemon ADDED
@@ -0,0 +1 @@
 
 
1
+ ../nodemon/bin/nodemon.js
backend-old/node_modules/.bin/nodetouch ADDED
@@ -0,0 +1 @@
 
 
1
+ ../touch/bin/nodetouch.js
backend-old/node_modules/.bin/nopt ADDED
@@ -0,0 +1 @@
 
 
1
+ ../nopt/bin/nopt.js
backend-old/node_modules/.bin/openai ADDED
@@ -0,0 +1 @@
 
 
1
+ ../openai/bin/cli
backend-old/node_modules/.bin/semver ADDED
@@ -0,0 +1 @@
 
 
1
+ ../semver/bin/semver.js
backend-old/node_modules/.package-lock.json ADDED
@@ -0,0 +1,1458 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "r3f-virtual-girlfriend-backend",
3
+ "version": "1.0.0",
4
+ "lockfileVersion": 3,
5
+ "requires": true,
6
+ "packages": {
7
+ "node_modules/@google/generative-ai": {
8
+ "version": "0.24.1",
9
+ "resolved": "https://registry.npmjs.org/@google/generative-ai/-/generative-ai-0.24.1.tgz",
10
+ "integrity": "sha512-MqO+MLfM6kjxcKoy0p1wRzG3b4ZZXtPI+z2IE26UogS2Cm/XHO+7gGRBh6gcJsOiIVoH93UwKvW4HdgiOZCy9Q==",
11
+ "license": "Apache-2.0",
12
+ "engines": {
13
+ "node": ">=18.0.0"
14
+ }
15
+ },
16
+ "node_modules/@types/node": {
17
+ "version": "18.19.10",
18
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.10.tgz",
19
+ "integrity": "sha512-IZD8kAM02AW1HRDTPOlz3npFava678pr8Ie9Vp8uRhBROXAv8MXT2pCnGZZAKYdromsNQLHQcfWQ6EOatVLtqA==",
20
+ "license": "MIT",
21
+ "dependencies": {
22
+ "undici-types": "~5.26.4"
23
+ }
24
+ },
25
+ "node_modules/@types/node-fetch": {
26
+ "version": "2.6.11",
27
+ "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.11.tgz",
28
+ "integrity": "sha512-24xFj9R5+rfQJLRyM56qh+wnVSYhyXC2tkoBndtY0U+vubqNsYXGjufB2nn8Q6gt0LrARwL6UBtMCSVCwl4B1g==",
29
+ "license": "MIT",
30
+ "dependencies": {
31
+ "@types/node": "*",
32
+ "form-data": "^4.0.0"
33
+ }
34
+ },
35
+ "node_modules/abbrev": {
36
+ "version": "1.1.1",
37
+ "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz",
38
+ "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==",
39
+ "dev": true,
40
+ "license": "ISC"
41
+ },
42
+ "node_modules/abort-controller": {
43
+ "version": "3.0.0",
44
+ "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",
45
+ "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==",
46
+ "license": "MIT",
47
+ "dependencies": {
48
+ "event-target-shim": "^5.0.0"
49
+ },
50
+ "engines": {
51
+ "node": ">=6.5"
52
+ }
53
+ },
54
+ "node_modules/accepts": {
55
+ "version": "1.3.8",
56
+ "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
57
+ "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==",
58
+ "license": "MIT",
59
+ "dependencies": {
60
+ "mime-types": "~2.1.34",
61
+ "negotiator": "0.6.3"
62
+ },
63
+ "engines": {
64
+ "node": ">= 0.6"
65
+ }
66
+ },
67
+ "node_modules/agentkeepalive": {
68
+ "version": "4.5.0",
69
+ "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.5.0.tgz",
70
+ "integrity": "sha512-5GG/5IbQQpC9FpkRGsSvZI5QYeSCzlJHdpBQntCsuTOxhKD8lqKhrleg2Yi7yvMIf82Ycmmqln9U8V9qwEiJew==",
71
+ "license": "MIT",
72
+ "dependencies": {
73
+ "humanize-ms": "^1.2.1"
74
+ },
75
+ "engines": {
76
+ "node": ">= 8.0.0"
77
+ }
78
+ },
79
+ "node_modules/anymatch": {
80
+ "version": "3.1.3",
81
+ "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz",
82
+ "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==",
83
+ "dev": true,
84
+ "license": "ISC",
85
+ "dependencies": {
86
+ "normalize-path": "^3.0.0",
87
+ "picomatch": "^2.0.4"
88
+ },
89
+ "engines": {
90
+ "node": ">= 8"
91
+ }
92
+ },
93
+ "node_modules/array-flatten": {
94
+ "version": "1.1.1",
95
+ "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
96
+ "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",
97
+ "license": "MIT"
98
+ },
99
+ "node_modules/asynckit": {
100
+ "version": "0.4.0",
101
+ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
102
+ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
103
+ "license": "MIT"
104
+ },
105
+ "node_modules/axios": {
106
+ "version": "1.5.1",
107
+ "resolved": "https://registry.npmjs.org/axios/-/axios-1.5.1.tgz",
108
+ "integrity": "sha512-Q28iYCWzNHjAm+yEAot5QaAMxhMghWLFVf7rRdwhUI+c2jix2DUXjAHXVi+s1ibs3mjPO/cCgbA++3BjD0vP/A==",
109
+ "license": "MIT",
110
+ "dependencies": {
111
+ "follow-redirects": "^1.15.0",
112
+ "form-data": "^4.0.0",
113
+ "proxy-from-env": "^1.1.0"
114
+ }
115
+ },
116
+ "node_modules/balanced-match": {
117
+ "version": "1.0.2",
118
+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
119
+ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
120
+ "dev": true,
121
+ "license": "MIT"
122
+ },
123
+ "node_modules/base-64": {
124
+ "version": "0.1.0",
125
+ "resolved": "https://registry.npmjs.org/base-64/-/base-64-0.1.0.tgz",
126
+ "integrity": "sha512-Y5gU45svrR5tI2Vt/X9GPd3L0HNIKzGu202EjxrXMpuc2V2CiKgemAbUUsqYmZJvPtCXoUKjNZwBJzsNScUbXA=="
127
+ },
128
+ "node_modules/binary-extensions": {
129
+ "version": "2.2.0",
130
+ "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz",
131
+ "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==",
132
+ "dev": true,
133
+ "license": "MIT",
134
+ "engines": {
135
+ "node": ">=8"
136
+ }
137
+ },
138
+ "node_modules/body-parser": {
139
+ "version": "1.20.1",
140
+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.1.tgz",
141
+ "integrity": "sha512-jWi7abTbYwajOytWCQc37VulmWiRae5RyTpaCyDcS5/lMdtwSz5lOpDE67srw/HYe35f1z3fDQw+3txg7gNtWw==",
142
+ "license": "MIT",
143
+ "dependencies": {
144
+ "bytes": "3.1.2",
145
+ "content-type": "~1.0.4",
146
+ "debug": "2.6.9",
147
+ "depd": "2.0.0",
148
+ "destroy": "1.2.0",
149
+ "http-errors": "2.0.0",
150
+ "iconv-lite": "0.4.24",
151
+ "on-finished": "2.4.1",
152
+ "qs": "6.11.0",
153
+ "raw-body": "2.5.1",
154
+ "type-is": "~1.6.18",
155
+ "unpipe": "1.0.0"
156
+ },
157
+ "engines": {
158
+ "node": ">= 0.8",
159
+ "npm": "1.2.8000 || >= 1.4.16"
160
+ }
161
+ },
162
+ "node_modules/brace-expansion": {
163
+ "version": "1.1.11",
164
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
165
+ "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
166
+ "dev": true,
167
+ "license": "MIT",
168
+ "dependencies": {
169
+ "balanced-match": "^1.0.0",
170
+ "concat-map": "0.0.1"
171
+ }
172
+ },
173
+ "node_modules/braces": {
174
+ "version": "3.0.2",
175
+ "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz",
176
+ "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==",
177
+ "dev": true,
178
+ "license": "MIT",
179
+ "dependencies": {
180
+ "fill-range": "^7.0.1"
181
+ },
182
+ "engines": {
183
+ "node": ">=8"
184
+ }
185
+ },
186
+ "node_modules/bytes": {
187
+ "version": "3.1.2",
188
+ "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
189
+ "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
190
+ "license": "MIT",
191
+ "engines": {
192
+ "node": ">= 0.8"
193
+ }
194
+ },
195
+ "node_modules/call-bind": {
196
+ "version": "1.0.2",
197
+ "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz",
198
+ "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==",
199
+ "license": "MIT",
200
+ "dependencies": {
201
+ "function-bind": "^1.1.1",
202
+ "get-intrinsic": "^1.0.2"
203
+ },
204
+ "funding": {
205
+ "url": "https://github.com/sponsors/ljharb"
206
+ }
207
+ },
208
+ "node_modules/charenc": {
209
+ "version": "0.0.2",
210
+ "resolved": "https://registry.npmjs.org/charenc/-/charenc-0.0.2.tgz",
211
+ "integrity": "sha512-yrLQ/yVUFXkzg7EDQsPieE/53+0RlaWTs+wBrvW36cyilJ2SaDWfl4Yj7MtLTXleV9uEKefbAGUPv2/iWSooRA==",
212
+ "license": "BSD-3-Clause",
213
+ "engines": {
214
+ "node": "*"
215
+ }
216
+ },
217
+ "node_modules/chokidar": {
218
+ "version": "3.5.3",
219
+ "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz",
220
+ "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==",
221
+ "dev": true,
222
+ "funding": [
223
+ {
224
+ "type": "individual",
225
+ "url": "https://paulmillr.com/funding/"
226
+ }
227
+ ],
228
+ "license": "MIT",
229
+ "dependencies": {
230
+ "anymatch": "~3.1.2",
231
+ "braces": "~3.0.2",
232
+ "glob-parent": "~5.1.2",
233
+ "is-binary-path": "~2.1.0",
234
+ "is-glob": "~4.0.1",
235
+ "normalize-path": "~3.0.0",
236
+ "readdirp": "~3.6.0"
237
+ },
238
+ "engines": {
239
+ "node": ">= 8.10.0"
240
+ },
241
+ "optionalDependencies": {
242
+ "fsevents": "~2.3.2"
243
+ }
244
+ },
245
+ "node_modules/combined-stream": {
246
+ "version": "1.0.8",
247
+ "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
248
+ "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
249
+ "license": "MIT",
250
+ "dependencies": {
251
+ "delayed-stream": "~1.0.0"
252
+ },
253
+ "engines": {
254
+ "node": ">= 0.8"
255
+ }
256
+ },
257
+ "node_modules/concat-map": {
258
+ "version": "0.0.1",
259
+ "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
260
+ "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
261
+ "dev": true,
262
+ "license": "MIT"
263
+ },
264
+ "node_modules/content-disposition": {
265
+ "version": "0.5.4",
266
+ "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
267
+ "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==",
268
+ "license": "MIT",
269
+ "dependencies": {
270
+ "safe-buffer": "5.2.1"
271
+ },
272
+ "engines": {
273
+ "node": ">= 0.6"
274
+ }
275
+ },
276
+ "node_modules/content-type": {
277
+ "version": "1.0.5",
278
+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
279
+ "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
280
+ "license": "MIT",
281
+ "engines": {
282
+ "node": ">= 0.6"
283
+ }
284
+ },
285
+ "node_modules/cookie": {
286
+ "version": "0.5.0",
287
+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.5.0.tgz",
288
+ "integrity": "sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==",
289
+ "license": "MIT",
290
+ "engines": {
291
+ "node": ">= 0.6"
292
+ }
293
+ },
294
+ "node_modules/cookie-signature": {
295
+ "version": "1.0.6",
296
+ "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
297
+ "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==",
298
+ "license": "MIT"
299
+ },
300
+ "node_modules/cors": {
301
+ "version": "2.8.5",
302
+ "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz",
303
+ "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==",
304
+ "license": "MIT",
305
+ "dependencies": {
306
+ "object-assign": "^4",
307
+ "vary": "^1"
308
+ },
309
+ "engines": {
310
+ "node": ">= 0.10"
311
+ }
312
+ },
313
+ "node_modules/crypt": {
314
+ "version": "0.0.2",
315
+ "resolved": "https://registry.npmjs.org/crypt/-/crypt-0.0.2.tgz",
316
+ "integrity": "sha512-mCxBlsHFYh9C+HVpiEacem8FEBnMXgU9gy4zmNC+SXAZNB/1idgp/aulFJ4FgCi7GPEVbfyng092GqL2k2rmow==",
317
+ "license": "BSD-3-Clause",
318
+ "engines": {
319
+ "node": "*"
320
+ }
321
+ },
322
+ "node_modules/debug": {
323
+ "version": "2.6.9",
324
+ "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
325
+ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
326
+ "license": "MIT",
327
+ "dependencies": {
328
+ "ms": "2.0.0"
329
+ }
330
+ },
331
+ "node_modules/delayed-stream": {
332
+ "version": "1.0.0",
333
+ "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
334
+ "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
335
+ "license": "MIT",
336
+ "engines": {
337
+ "node": ">=0.4.0"
338
+ }
339
+ },
340
+ "node_modules/depd": {
341
+ "version": "2.0.0",
342
+ "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
343
+ "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
344
+ "license": "MIT",
345
+ "engines": {
346
+ "node": ">= 0.8"
347
+ }
348
+ },
349
+ "node_modules/destroy": {
350
+ "version": "1.2.0",
351
+ "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz",
352
+ "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",
353
+ "license": "MIT",
354
+ "engines": {
355
+ "node": ">= 0.8",
356
+ "npm": "1.2.8000 || >= 1.4.16"
357
+ }
358
+ },
359
+ "node_modules/digest-fetch": {
360
+ "version": "1.3.0",
361
+ "resolved": "https://registry.npmjs.org/digest-fetch/-/digest-fetch-1.3.0.tgz",
362
+ "integrity": "sha512-CGJuv6iKNM7QyZlM2T3sPAdZWd/p9zQiRNS9G+9COUCwzWFTs0Xp8NF5iePx7wtvhDykReiRRrSeNb4oMmB8lA==",
363
+ "license": "ISC",
364
+ "dependencies": {
365
+ "base-64": "^0.1.0",
366
+ "md5": "^2.3.0"
367
+ }
368
+ },
369
+ "node_modules/dotenv": {
370
+ "version": "16.3.1",
371
+ "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.3.1.tgz",
372
+ "integrity": "sha512-IPzF4w4/Rd94bA9imS68tZBaYyBWSCE47V1RGuMrB94iyTOIEwRmVL2x/4An+6mETpLrKJ5hQkB8W4kFAadeIQ==",
373
+ "license": "BSD-2-Clause",
374
+ "engines": {
375
+ "node": ">=12"
376
+ },
377
+ "funding": {
378
+ "url": "https://github.com/motdotla/dotenv?sponsor=1"
379
+ }
380
+ },
381
+ "node_modules/ee-first": {
382
+ "version": "1.1.1",
383
+ "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
384
+ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
385
+ "license": "MIT"
386
+ },
387
+ "node_modules/elevenlabs-node": {
388
+ "version": "1.2.0",
389
+ "resolved": "https://registry.npmjs.org/elevenlabs-node/-/elevenlabs-node-1.2.0.tgz",
390
+ "integrity": "sha512-T5ITXXG0lmLKzWjqz4zH3HtNRqAFkMt7mriWAw11fakS417LQkJPIPj4566znGK79E9xmZVVwzf2D0WBxkVzmw==",
391
+ "license": "MIT",
392
+ "dependencies": {
393
+ "axios": "^1.4.0",
394
+ "fs-extra": "^11.1.1"
395
+ }
396
+ },
397
+ "node_modules/encodeurl": {
398
+ "version": "1.0.2",
399
+ "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz",
400
+ "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==",
401
+ "license": "MIT",
402
+ "engines": {
403
+ "node": ">= 0.8"
404
+ }
405
+ },
406
+ "node_modules/escape-html": {
407
+ "version": "1.0.3",
408
+ "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
409
+ "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
410
+ "license": "MIT"
411
+ },
412
+ "node_modules/etag": {
413
+ "version": "1.8.1",
414
+ "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
415
+ "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
416
+ "license": "MIT",
417
+ "engines": {
418
+ "node": ">= 0.6"
419
+ }
420
+ },
421
+ "node_modules/event-target-shim": {
422
+ "version": "5.0.1",
423
+ "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
424
+ "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==",
425
+ "license": "MIT",
426
+ "engines": {
427
+ "node": ">=6"
428
+ }
429
+ },
430
+ "node_modules/express": {
431
+ "version": "4.18.2",
432
+ "resolved": "https://registry.npmjs.org/express/-/express-4.18.2.tgz",
433
+ "integrity": "sha512-5/PsL6iGPdfQ/lKM1UuielYgv3BUoJfz1aUwU9vHZ+J7gyvwdQXFEBIEIaxeGf0GIcreATNyBExtalisDbuMqQ==",
434
+ "license": "MIT",
435
+ "dependencies": {
436
+ "accepts": "~1.3.8",
437
+ "array-flatten": "1.1.1",
438
+ "body-parser": "1.20.1",
439
+ "content-disposition": "0.5.4",
440
+ "content-type": "~1.0.4",
441
+ "cookie": "0.5.0",
442
+ "cookie-signature": "1.0.6",
443
+ "debug": "2.6.9",
444
+ "depd": "2.0.0",
445
+ "encodeurl": "~1.0.2",
446
+ "escape-html": "~1.0.3",
447
+ "etag": "~1.8.1",
448
+ "finalhandler": "1.2.0",
449
+ "fresh": "0.5.2",
450
+ "http-errors": "2.0.0",
451
+ "merge-descriptors": "1.0.1",
452
+ "methods": "~1.1.2",
453
+ "on-finished": "2.4.1",
454
+ "parseurl": "~1.3.3",
455
+ "path-to-regexp": "0.1.7",
456
+ "proxy-addr": "~2.0.7",
457
+ "qs": "6.11.0",
458
+ "range-parser": "~1.2.1",
459
+ "safe-buffer": "5.2.1",
460
+ "send": "0.18.0",
461
+ "serve-static": "1.15.0",
462
+ "setprototypeof": "1.2.0",
463
+ "statuses": "2.0.1",
464
+ "type-is": "~1.6.18",
465
+ "utils-merge": "1.0.1",
466
+ "vary": "~1.1.2"
467
+ },
468
+ "engines": {
469
+ "node": ">= 0.10.0"
470
+ }
471
+ },
472
+ "node_modules/fill-range": {
473
+ "version": "7.0.1",
474
+ "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz",
475
+ "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==",
476
+ "dev": true,
477
+ "license": "MIT",
478
+ "dependencies": {
479
+ "to-regex-range": "^5.0.1"
480
+ },
481
+ "engines": {
482
+ "node": ">=8"
483
+ }
484
+ },
485
+ "node_modules/finalhandler": {
486
+ "version": "1.2.0",
487
+ "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.2.0.tgz",
488
+ "integrity": "sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg==",
489
+ "license": "MIT",
490
+ "dependencies": {
491
+ "debug": "2.6.9",
492
+ "encodeurl": "~1.0.2",
493
+ "escape-html": "~1.0.3",
494
+ "on-finished": "2.4.1",
495
+ "parseurl": "~1.3.3",
496
+ "statuses": "2.0.1",
497
+ "unpipe": "~1.0.0"
498
+ },
499
+ "engines": {
500
+ "node": ">= 0.8"
501
+ }
502
+ },
503
+ "node_modules/follow-redirects": {
504
+ "version": "1.15.3",
505
+ "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.3.tgz",
506
+ "integrity": "sha512-1VzOtuEM8pC9SFU1E+8KfTjZyMztRsgEfwQl44z8A25uy13jSzTj6dyK2Df52iV0vgHCfBwLhDWevLn95w5v6Q==",
507
+ "funding": [
508
+ {
509
+ "type": "individual",
510
+ "url": "https://github.com/sponsors/RubenVerborgh"
511
+ }
512
+ ],
513
+ "license": "MIT",
514
+ "engines": {
515
+ "node": ">=4.0"
516
+ },
517
+ "peerDependenciesMeta": {
518
+ "debug": {
519
+ "optional": true
520
+ }
521
+ }
522
+ },
523
+ "node_modules/form-data": {
524
+ "version": "4.0.0",
525
+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz",
526
+ "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==",
527
+ "license": "MIT",
528
+ "dependencies": {
529
+ "asynckit": "^0.4.0",
530
+ "combined-stream": "^1.0.8",
531
+ "mime-types": "^2.1.12"
532
+ },
533
+ "engines": {
534
+ "node": ">= 6"
535
+ }
536
+ },
537
+ "node_modules/form-data-encoder": {
538
+ "version": "1.7.2",
539
+ "resolved": "https://registry.npmjs.org/form-data-encoder/-/form-data-encoder-1.7.2.tgz",
540
+ "integrity": "sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==",
541
+ "license": "MIT"
542
+ },
543
+ "node_modules/formdata-node": {
544
+ "version": "4.4.1",
545
+ "resolved": "https://registry.npmjs.org/formdata-node/-/formdata-node-4.4.1.tgz",
546
+ "integrity": "sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==",
547
+ "license": "MIT",
548
+ "dependencies": {
549
+ "node-domexception": "1.0.0",
550
+ "web-streams-polyfill": "4.0.0-beta.3"
551
+ },
552
+ "engines": {
553
+ "node": ">= 12.20"
554
+ }
555
+ },
556
+ "node_modules/formdata-node/node_modules/web-streams-polyfill": {
557
+ "version": "4.0.0-beta.3",
558
+ "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-4.0.0-beta.3.tgz",
559
+ "integrity": "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==",
560
+ "license": "MIT",
561
+ "engines": {
562
+ "node": ">= 14"
563
+ }
564
+ },
565
+ "node_modules/forwarded": {
566
+ "version": "0.2.0",
567
+ "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
568
+ "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
569
+ "license": "MIT",
570
+ "engines": {
571
+ "node": ">= 0.6"
572
+ }
573
+ },
574
+ "node_modules/fresh": {
575
+ "version": "0.5.2",
576
+ "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
577
+ "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==",
578
+ "license": "MIT",
579
+ "engines": {
580
+ "node": ">= 0.6"
581
+ }
582
+ },
583
+ "node_modules/fs-extra": {
584
+ "version": "11.1.1",
585
+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.1.1.tgz",
586
+ "integrity": "sha512-MGIE4HOvQCeUCzmlHs0vXpih4ysz4wg9qiSAu6cd42lVwPbTM1TjV7RusoyQqMmk/95gdQZX72u+YW+c3eEpFQ==",
587
+ "license": "MIT",
588
+ "dependencies": {
589
+ "graceful-fs": "^4.2.0",
590
+ "jsonfile": "^6.0.1",
591
+ "universalify": "^2.0.0"
592
+ },
593
+ "engines": {
594
+ "node": ">=14.14"
595
+ }
596
+ },
597
+ "node_modules/function-bind": {
598
+ "version": "1.1.1",
599
+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz",
600
+ "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==",
601
+ "license": "MIT"
602
+ },
603
+ "node_modules/get-intrinsic": {
604
+ "version": "1.2.1",
605
+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.1.tgz",
606
+ "integrity": "sha512-2DcsyfABl+gVHEfCOaTrWgyt+tb6MSEGmKq+kI5HwLbIYgjgmMcV8KQ41uaKz1xxUcn9tJtgFbQUEVcEbd0FYw==",
607
+ "license": "MIT",
608
+ "dependencies": {
609
+ "function-bind": "^1.1.1",
610
+ "has": "^1.0.3",
611
+ "has-proto": "^1.0.1",
612
+ "has-symbols": "^1.0.3"
613
+ },
614
+ "funding": {
615
+ "url": "https://github.com/sponsors/ljharb"
616
+ }
617
+ },
618
+ "node_modules/glob-parent": {
619
+ "version": "5.1.2",
620
+ "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
621
+ "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
622
+ "dev": true,
623
+ "license": "ISC",
624
+ "dependencies": {
625
+ "is-glob": "^4.0.1"
626
+ },
627
+ "engines": {
628
+ "node": ">= 6"
629
+ }
630
+ },
631
+ "node_modules/graceful-fs": {
632
+ "version": "4.2.11",
633
+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
634
+ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
635
+ "license": "ISC"
636
+ },
637
+ "node_modules/has": {
638
+ "version": "1.0.4",
639
+ "resolved": "https://registry.npmjs.org/has/-/has-1.0.4.tgz",
640
+ "integrity": "sha512-qdSAmqLF6209RFj4VVItywPMbm3vWylknmB3nvNiUIs72xAimcM8nVYxYr7ncvZq5qzk9MKIZR8ijqD/1QuYjQ==",
641
+ "license": "MIT",
642
+ "engines": {
643
+ "node": ">= 0.4.0"
644
+ }
645
+ },
646
+ "node_modules/has-flag": {
647
+ "version": "3.0.0",
648
+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz",
649
+ "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==",
650
+ "dev": true,
651
+ "license": "MIT",
652
+ "engines": {
653
+ "node": ">=4"
654
+ }
655
+ },
656
+ "node_modules/has-proto": {
657
+ "version": "1.0.1",
658
+ "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.1.tgz",
659
+ "integrity": "sha512-7qE+iP+O+bgF9clE5+UoBFzE65mlBiVj3tKCrlNQ0Ogwm0BjpT/gK4SlLYDMybDh5I3TCTKnPPa0oMG7JDYrhg==",
660
+ "license": "MIT",
661
+ "engines": {
662
+ "node": ">= 0.4"
663
+ },
664
+ "funding": {
665
+ "url": "https://github.com/sponsors/ljharb"
666
+ }
667
+ },
668
+ "node_modules/has-symbols": {
669
+ "version": "1.0.3",
670
+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz",
671
+ "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==",
672
+ "license": "MIT",
673
+ "engines": {
674
+ "node": ">= 0.4"
675
+ },
676
+ "funding": {
677
+ "url": "https://github.com/sponsors/ljharb"
678
+ }
679
+ },
680
+ "node_modules/http-errors": {
681
+ "version": "2.0.0",
682
+ "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz",
683
+ "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==",
684
+ "license": "MIT",
685
+ "dependencies": {
686
+ "depd": "2.0.0",
687
+ "inherits": "2.0.4",
688
+ "setprototypeof": "1.2.0",
689
+ "statuses": "2.0.1",
690
+ "toidentifier": "1.0.1"
691
+ },
692
+ "engines": {
693
+ "node": ">= 0.8"
694
+ }
695
+ },
696
+ "node_modules/humanize-ms": {
697
+ "version": "1.2.1",
698
+ "resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz",
699
+ "integrity": "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==",
700
+ "license": "MIT",
701
+ "dependencies": {
702
+ "ms": "^2.0.0"
703
+ }
704
+ },
705
+ "node_modules/iconv-lite": {
706
+ "version": "0.4.24",
707
+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
708
+ "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
709
+ "license": "MIT",
710
+ "dependencies": {
711
+ "safer-buffer": ">= 2.1.2 < 3"
712
+ },
713
+ "engines": {
714
+ "node": ">=0.10.0"
715
+ }
716
+ },
717
+ "node_modules/ignore-by-default": {
718
+ "version": "1.0.1",
719
+ "resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz",
720
+ "integrity": "sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA==",
721
+ "dev": true,
722
+ "license": "ISC"
723
+ },
724
+ "node_modules/inherits": {
725
+ "version": "2.0.4",
726
+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
727
+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
728
+ "license": "ISC"
729
+ },
730
+ "node_modules/ipaddr.js": {
731
+ "version": "1.9.1",
732
+ "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
733
+ "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
734
+ "license": "MIT",
735
+ "engines": {
736
+ "node": ">= 0.10"
737
+ }
738
+ },
739
+ "node_modules/is-binary-path": {
740
+ "version": "2.1.0",
741
+ "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz",
742
+ "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==",
743
+ "dev": true,
744
+ "license": "MIT",
745
+ "dependencies": {
746
+ "binary-extensions": "^2.0.0"
747
+ },
748
+ "engines": {
749
+ "node": ">=8"
750
+ }
751
+ },
752
+ "node_modules/is-buffer": {
753
+ "version": "1.1.6",
754
+ "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz",
755
+ "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==",
756
+ "license": "MIT"
757
+ },
758
+ "node_modules/is-extglob": {
759
+ "version": "2.1.1",
760
+ "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
761
+ "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
762
+ "dev": true,
763
+ "license": "MIT",
764
+ "engines": {
765
+ "node": ">=0.10.0"
766
+ }
767
+ },
768
+ "node_modules/is-glob": {
769
+ "version": "4.0.3",
770
+ "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
771
+ "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
772
+ "dev": true,
773
+ "license": "MIT",
774
+ "dependencies": {
775
+ "is-extglob": "^2.1.1"
776
+ },
777
+ "engines": {
778
+ "node": ">=0.10.0"
779
+ }
780
+ },
781
+ "node_modules/is-number": {
782
+ "version": "7.0.0",
783
+ "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz",
784
+ "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",
785
+ "dev": true,
786
+ "license": "MIT",
787
+ "engines": {
788
+ "node": ">=0.12.0"
789
+ }
790
+ },
791
+ "node_modules/jsonfile": {
792
+ "version": "6.1.0",
793
+ "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz",
794
+ "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==",
795
+ "license": "MIT",
796
+ "dependencies": {
797
+ "universalify": "^2.0.0"
798
+ },
799
+ "optionalDependencies": {
800
+ "graceful-fs": "^4.1.6"
801
+ }
802
+ },
803
+ "node_modules/lru-cache": {
804
+ "version": "6.0.0",
805
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
806
+ "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",
807
+ "dev": true,
808
+ "license": "ISC",
809
+ "dependencies": {
810
+ "yallist": "^4.0.0"
811
+ },
812
+ "engines": {
813
+ "node": ">=10"
814
+ }
815
+ },
816
+ "node_modules/md5": {
817
+ "version": "2.3.0",
818
+ "resolved": "https://registry.npmjs.org/md5/-/md5-2.3.0.tgz",
819
+ "integrity": "sha512-T1GITYmFaKuO91vxyoQMFETst+O71VUPEU3ze5GNzDm0OWdP8v1ziTaAEPUr/3kLsY3Sftgz242A1SetQiDL7g==",
820
+ "license": "BSD-3-Clause",
821
+ "dependencies": {
822
+ "charenc": "0.0.2",
823
+ "crypt": "0.0.2",
824
+ "is-buffer": "~1.1.6"
825
+ }
826
+ },
827
+ "node_modules/media-typer": {
828
+ "version": "0.3.0",
829
+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
830
+ "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",
831
+ "license": "MIT",
832
+ "engines": {
833
+ "node": ">= 0.6"
834
+ }
835
+ },
836
+ "node_modules/merge-descriptors": {
837
+ "version": "1.0.1",
838
+ "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz",
839
+ "integrity": "sha512-cCi6g3/Zr1iqQi6ySbseM1Xvooa98N0w31jzUYrXPX2xqObmFGHJ0tQ5u74H3mVh7wLouTseZyYIq39g8cNp1w==",
840
+ "license": "MIT"
841
+ },
842
+ "node_modules/methods": {
843
+ "version": "1.1.2",
844
+ "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz",
845
+ "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==",
846
+ "license": "MIT",
847
+ "engines": {
848
+ "node": ">= 0.6"
849
+ }
850
+ },
851
+ "node_modules/mime": {
852
+ "version": "1.6.0",
853
+ "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
854
+ "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==",
855
+ "license": "MIT",
856
+ "bin": {
857
+ "mime": "cli.js"
858
+ },
859
+ "engines": {
860
+ "node": ">=4"
861
+ }
862
+ },
863
+ "node_modules/mime-db": {
864
+ "version": "1.52.0",
865
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
866
+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
867
+ "license": "MIT",
868
+ "engines": {
869
+ "node": ">= 0.6"
870
+ }
871
+ },
872
+ "node_modules/mime-types": {
873
+ "version": "2.1.35",
874
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
875
+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
876
+ "license": "MIT",
877
+ "dependencies": {
878
+ "mime-db": "1.52.0"
879
+ },
880
+ "engines": {
881
+ "node": ">= 0.6"
882
+ }
883
+ },
884
+ "node_modules/minimatch": {
885
+ "version": "3.1.2",
886
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
887
+ "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
888
+ "dev": true,
889
+ "license": "ISC",
890
+ "dependencies": {
891
+ "brace-expansion": "^1.1.7"
892
+ },
893
+ "engines": {
894
+ "node": "*"
895
+ }
896
+ },
897
+ "node_modules/ms": {
898
+ "version": "2.0.0",
899
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
900
+ "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
901
+ "license": "MIT"
902
+ },
903
+ "node_modules/negotiator": {
904
+ "version": "0.6.3",
905
+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
906
+ "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==",
907
+ "license": "MIT",
908
+ "engines": {
909
+ "node": ">= 0.6"
910
+ }
911
+ },
912
+ "node_modules/node-domexception": {
913
+ "version": "1.0.0",
914
+ "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",
915
+ "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==",
916
+ "deprecated": "Use your platform's native DOMException instead",
917
+ "funding": [
918
+ {
919
+ "type": "github",
920
+ "url": "https://github.com/sponsors/jimmywarting"
921
+ },
922
+ {
923
+ "type": "github",
924
+ "url": "https://paypal.me/jimmywarting"
925
+ }
926
+ ],
927
+ "license": "MIT",
928
+ "engines": {
929
+ "node": ">=10.5.0"
930
+ }
931
+ },
932
+ "node_modules/node-fetch": {
933
+ "version": "2.7.0",
934
+ "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
935
+ "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",
936
+ "license": "MIT",
937
+ "dependencies": {
938
+ "whatwg-url": "^5.0.0"
939
+ },
940
+ "engines": {
941
+ "node": "4.x || >=6.0.0"
942
+ },
943
+ "peerDependencies": {
944
+ "encoding": "^0.1.0"
945
+ },
946
+ "peerDependenciesMeta": {
947
+ "encoding": {
948
+ "optional": true
949
+ }
950
+ }
951
+ },
952
+ "node_modules/nodemon": {
953
+ "version": "3.0.1",
954
+ "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.0.1.tgz",
955
+ "integrity": "sha512-g9AZ7HmkhQkqXkRc20w+ZfQ73cHLbE8hnPbtaFbFtCumZsjyMhKk9LajQ07U5Ux28lvFjZ5X7HvWR1xzU8jHVw==",
956
+ "dev": true,
957
+ "license": "MIT",
958
+ "dependencies": {
959
+ "chokidar": "^3.5.2",
960
+ "debug": "^3.2.7",
961
+ "ignore-by-default": "^1.0.1",
962
+ "minimatch": "^3.1.2",
963
+ "pstree.remy": "^1.1.8",
964
+ "semver": "^7.5.3",
965
+ "simple-update-notifier": "^2.0.0",
966
+ "supports-color": "^5.5.0",
967
+ "touch": "^3.1.0",
968
+ "undefsafe": "^2.0.5"
969
+ },
970
+ "bin": {
971
+ "nodemon": "bin/nodemon.js"
972
+ },
973
+ "engines": {
974
+ "node": ">=10"
975
+ },
976
+ "funding": {
977
+ "type": "opencollective",
978
+ "url": "https://opencollective.com/nodemon"
979
+ }
980
+ },
981
+ "node_modules/nodemon/node_modules/debug": {
982
+ "version": "3.2.7",
983
+ "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz",
984
+ "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==",
985
+ "dev": true,
986
+ "license": "MIT",
987
+ "dependencies": {
988
+ "ms": "^2.1.1"
989
+ }
990
+ },
991
+ "node_modules/nodemon/node_modules/ms": {
992
+ "version": "2.1.3",
993
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
994
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
995
+ "dev": true,
996
+ "license": "MIT"
997
+ },
998
+ "node_modules/nopt": {
999
+ "version": "1.0.10",
1000
+ "resolved": "https://registry.npmjs.org/nopt/-/nopt-1.0.10.tgz",
1001
+ "integrity": "sha512-NWmpvLSqUrgrAC9HCuxEvb+PSloHpqVu+FqcO4eeF2h5qYRhA7ev6KvelyQAKtegUbC6RypJnlEOhd8vloNKYg==",
1002
+ "dev": true,
1003
+ "license": "MIT",
1004
+ "dependencies": {
1005
+ "abbrev": "1"
1006
+ },
1007
+ "bin": {
1008
+ "nopt": "bin/nopt.js"
1009
+ },
1010
+ "engines": {
1011
+ "node": "*"
1012
+ }
1013
+ },
1014
+ "node_modules/normalize-path": {
1015
+ "version": "3.0.0",
1016
+ "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
1017
+ "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==",
1018
+ "dev": true,
1019
+ "license": "MIT",
1020
+ "engines": {
1021
+ "node": ">=0.10.0"
1022
+ }
1023
+ },
1024
+ "node_modules/object-assign": {
1025
+ "version": "4.1.1",
1026
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
1027
+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
1028
+ "license": "MIT",
1029
+ "engines": {
1030
+ "node": ">=0.10.0"
1031
+ }
1032
+ },
1033
+ "node_modules/object-inspect": {
1034
+ "version": "1.12.3",
1035
+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.12.3.tgz",
1036
+ "integrity": "sha512-geUvdk7c+eizMNUDkRpW1wJwgfOiOeHbxBR/hLXK1aT6zmVSO0jsQcs7fj6MGw89jC/cjGfLcNOrtMYtGqm81g==",
1037
+ "license": "MIT",
1038
+ "funding": {
1039
+ "url": "https://github.com/sponsors/ljharb"
1040
+ }
1041
+ },
1042
+ "node_modules/on-finished": {
1043
+ "version": "2.4.1",
1044
+ "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
1045
+ "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
1046
+ "license": "MIT",
1047
+ "dependencies": {
1048
+ "ee-first": "1.1.1"
1049
+ },
1050
+ "engines": {
1051
+ "node": ">= 0.8"
1052
+ }
1053
+ },
1054
+ "node_modules/openai": {
1055
+ "version": "4.26.0",
1056
+ "resolved": "https://registry.npmjs.org/openai/-/openai-4.26.0.tgz",
1057
+ "integrity": "sha512-HPC7tgYdeP38F3uHA5WgnoXZyGbAp9jgcIo23p6It+q/07u4C+NZ8xHKlMShsPbDDmFRpPsa3vdbXYpbhJH3eg==",
1058
+ "license": "Apache-2.0",
1059
+ "dependencies": {
1060
+ "@types/node": "^18.11.18",
1061
+ "@types/node-fetch": "^2.6.4",
1062
+ "abort-controller": "^3.0.0",
1063
+ "agentkeepalive": "^4.2.1",
1064
+ "digest-fetch": "^1.3.0",
1065
+ "form-data-encoder": "1.7.2",
1066
+ "formdata-node": "^4.3.2",
1067
+ "node-fetch": "^2.6.7",
1068
+ "web-streams-polyfill": "^3.2.1"
1069
+ },
1070
+ "bin": {
1071
+ "openai": "bin/cli"
1072
+ }
1073
+ },
1074
+ "node_modules/parseurl": {
1075
+ "version": "1.3.3",
1076
+ "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
1077
+ "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
1078
+ "license": "MIT",
1079
+ "engines": {
1080
+ "node": ">= 0.8"
1081
+ }
1082
+ },
1083
+ "node_modules/path-to-regexp": {
1084
+ "version": "0.1.7",
1085
+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz",
1086
+ "integrity": "sha512-5DFkuoqlv1uYQKxy8omFBeJPQcdoE07Kv2sferDCrAq1ohOU+MSDswDIbnx3YAM60qIOnYa53wBhXW0EbMonrQ==",
1087
+ "license": "MIT"
1088
+ },
1089
+ "node_modules/picomatch": {
1090
+ "version": "2.3.1",
1091
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
1092
+ "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
1093
+ "dev": true,
1094
+ "license": "MIT",
1095
+ "engines": {
1096
+ "node": ">=8.6"
1097
+ },
1098
+ "funding": {
1099
+ "url": "https://github.com/sponsors/jonschlinkert"
1100
+ }
1101
+ },
1102
+ "node_modules/proxy-addr": {
1103
+ "version": "2.0.7",
1104
+ "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
1105
+ "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
1106
+ "license": "MIT",
1107
+ "dependencies": {
1108
+ "forwarded": "0.2.0",
1109
+ "ipaddr.js": "1.9.1"
1110
+ },
1111
+ "engines": {
1112
+ "node": ">= 0.10"
1113
+ }
1114
+ },
1115
+ "node_modules/proxy-from-env": {
1116
+ "version": "1.1.0",
1117
+ "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
1118
+ "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==",
1119
+ "license": "MIT"
1120
+ },
1121
+ "node_modules/pstree.remy": {
1122
+ "version": "1.1.8",
1123
+ "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz",
1124
+ "integrity": "sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w==",
1125
+ "dev": true,
1126
+ "license": "MIT"
1127
+ },
1128
+ "node_modules/qs": {
1129
+ "version": "6.11.0",
1130
+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz",
1131
+ "integrity": "sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==",
1132
+ "license": "BSD-3-Clause",
1133
+ "dependencies": {
1134
+ "side-channel": "^1.0.4"
1135
+ },
1136
+ "engines": {
1137
+ "node": ">=0.6"
1138
+ },
1139
+ "funding": {
1140
+ "url": "https://github.com/sponsors/ljharb"
1141
+ }
1142
+ },
1143
+ "node_modules/range-parser": {
1144
+ "version": "1.2.1",
1145
+ "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
1146
+ "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
1147
+ "license": "MIT",
1148
+ "engines": {
1149
+ "node": ">= 0.6"
1150
+ }
1151
+ },
1152
+ "node_modules/raw-body": {
1153
+ "version": "2.5.1",
1154
+ "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.1.tgz",
1155
+ "integrity": "sha512-qqJBtEyVgS0ZmPGdCFPWJ3FreoqvG4MVQln/kCgF7Olq95IbOp0/BWyMwbdtn4VTvkM8Y7khCQ2Xgk/tcrCXig==",
1156
+ "license": "MIT",
1157
+ "dependencies": {
1158
+ "bytes": "3.1.2",
1159
+ "http-errors": "2.0.0",
1160
+ "iconv-lite": "0.4.24",
1161
+ "unpipe": "1.0.0"
1162
+ },
1163
+ "engines": {
1164
+ "node": ">= 0.8"
1165
+ }
1166
+ },
1167
+ "node_modules/readdirp": {
1168
+ "version": "3.6.0",
1169
+ "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
1170
+ "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==",
1171
+ "dev": true,
1172
+ "license": "MIT",
1173
+ "dependencies": {
1174
+ "picomatch": "^2.2.1"
1175
+ },
1176
+ "engines": {
1177
+ "node": ">=8.10.0"
1178
+ }
1179
+ },
1180
+ "node_modules/safe-buffer": {
1181
+ "version": "5.2.1",
1182
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
1183
+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
1184
+ "funding": [
1185
+ {
1186
+ "type": "github",
1187
+ "url": "https://github.com/sponsors/feross"
1188
+ },
1189
+ {
1190
+ "type": "patreon",
1191
+ "url": "https://www.patreon.com/feross"
1192
+ },
1193
+ {
1194
+ "type": "consulting",
1195
+ "url": "https://feross.org/support"
1196
+ }
1197
+ ],
1198
+ "license": "MIT"
1199
+ },
1200
+ "node_modules/safer-buffer": {
1201
+ "version": "2.1.2",
1202
+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
1203
+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
1204
+ "license": "MIT"
1205
+ },
1206
+ "node_modules/semver": {
1207
+ "version": "7.5.4",
1208
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz",
1209
+ "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==",
1210
+ "dev": true,
1211
+ "license": "ISC",
1212
+ "dependencies": {
1213
+ "lru-cache": "^6.0.0"
1214
+ },
1215
+ "bin": {
1216
+ "semver": "bin/semver.js"
1217
+ },
1218
+ "engines": {
1219
+ "node": ">=10"
1220
+ }
1221
+ },
1222
+ "node_modules/send": {
1223
+ "version": "0.18.0",
1224
+ "resolved": "https://registry.npmjs.org/send/-/send-0.18.0.tgz",
1225
+ "integrity": "sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==",
1226
+ "license": "MIT",
1227
+ "dependencies": {
1228
+ "debug": "2.6.9",
1229
+ "depd": "2.0.0",
1230
+ "destroy": "1.2.0",
1231
+ "encodeurl": "~1.0.2",
1232
+ "escape-html": "~1.0.3",
1233
+ "etag": "~1.8.1",
1234
+ "fresh": "0.5.2",
1235
+ "http-errors": "2.0.0",
1236
+ "mime": "1.6.0",
1237
+ "ms": "2.1.3",
1238
+ "on-finished": "2.4.1",
1239
+ "range-parser": "~1.2.1",
1240
+ "statuses": "2.0.1"
1241
+ },
1242
+ "engines": {
1243
+ "node": ">= 0.8.0"
1244
+ }
1245
+ },
1246
+ "node_modules/send/node_modules/ms": {
1247
+ "version": "2.1.3",
1248
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
1249
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
1250
+ "license": "MIT"
1251
+ },
1252
+ "node_modules/serve-static": {
1253
+ "version": "1.15.0",
1254
+ "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.15.0.tgz",
1255
+ "integrity": "sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g==",
1256
+ "license": "MIT",
1257
+ "dependencies": {
1258
+ "encodeurl": "~1.0.2",
1259
+ "escape-html": "~1.0.3",
1260
+ "parseurl": "~1.3.3",
1261
+ "send": "0.18.0"
1262
+ },
1263
+ "engines": {
1264
+ "node": ">= 0.8.0"
1265
+ }
1266
+ },
1267
+ "node_modules/setprototypeof": {
1268
+ "version": "1.2.0",
1269
+ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
1270
+ "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
1271
+ "license": "ISC"
1272
+ },
1273
+ "node_modules/side-channel": {
1274
+ "version": "1.0.4",
1275
+ "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz",
1276
+ "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==",
1277
+ "license": "MIT",
1278
+ "dependencies": {
1279
+ "call-bind": "^1.0.0",
1280
+ "get-intrinsic": "^1.0.2",
1281
+ "object-inspect": "^1.9.0"
1282
+ },
1283
+ "funding": {
1284
+ "url": "https://github.com/sponsors/ljharb"
1285
+ }
1286
+ },
1287
+ "node_modules/simple-update-notifier": {
1288
+ "version": "2.0.0",
1289
+ "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz",
1290
+ "integrity": "sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==",
1291
+ "dev": true,
1292
+ "license": "MIT",
1293
+ "dependencies": {
1294
+ "semver": "^7.5.3"
1295
+ },
1296
+ "engines": {
1297
+ "node": ">=10"
1298
+ }
1299
+ },
1300
+ "node_modules/statuses": {
1301
+ "version": "2.0.1",
1302
+ "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz",
1303
+ "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==",
1304
+ "license": "MIT",
1305
+ "engines": {
1306
+ "node": ">= 0.8"
1307
+ }
1308
+ },
1309
+ "node_modules/supports-color": {
1310
+ "version": "5.5.0",
1311
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz",
1312
+ "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==",
1313
+ "dev": true,
1314
+ "license": "MIT",
1315
+ "dependencies": {
1316
+ "has-flag": "^3.0.0"
1317
+ },
1318
+ "engines": {
1319
+ "node": ">=4"
1320
+ }
1321
+ },
1322
+ "node_modules/to-regex-range": {
1323
+ "version": "5.0.1",
1324
+ "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
1325
+ "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
1326
+ "dev": true,
1327
+ "license": "MIT",
1328
+ "dependencies": {
1329
+ "is-number": "^7.0.0"
1330
+ },
1331
+ "engines": {
1332
+ "node": ">=8.0"
1333
+ }
1334
+ },
1335
+ "node_modules/toidentifier": {
1336
+ "version": "1.0.1",
1337
+ "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
1338
+ "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
1339
+ "license": "MIT",
1340
+ "engines": {
1341
+ "node": ">=0.6"
1342
+ }
1343
+ },
1344
+ "node_modules/touch": {
1345
+ "version": "3.1.0",
1346
+ "resolved": "https://registry.npmjs.org/touch/-/touch-3.1.0.tgz",
1347
+ "integrity": "sha512-WBx8Uy5TLtOSRtIq+M03/sKDrXCLHxwDcquSP2c43Le03/9serjQBIztjRz6FkJez9D/hleyAXTBGLwwZUw9lA==",
1348
+ "dev": true,
1349
+ "license": "ISC",
1350
+ "dependencies": {
1351
+ "nopt": "~1.0.10"
1352
+ },
1353
+ "bin": {
1354
+ "nodetouch": "bin/nodetouch.js"
1355
+ }
1356
+ },
1357
+ "node_modules/tr46": {
1358
+ "version": "0.0.3",
1359
+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
1360
+ "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
1361
+ "license": "MIT"
1362
+ },
1363
+ "node_modules/type-is": {
1364
+ "version": "1.6.18",
1365
+ "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
1366
+ "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
1367
+ "license": "MIT",
1368
+ "dependencies": {
1369
+ "media-typer": "0.3.0",
1370
+ "mime-types": "~2.1.24"
1371
+ },
1372
+ "engines": {
1373
+ "node": ">= 0.6"
1374
+ }
1375
+ },
1376
+ "node_modules/undefsafe": {
1377
+ "version": "2.0.5",
1378
+ "resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz",
1379
+ "integrity": "sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA==",
1380
+ "dev": true,
1381
+ "license": "MIT"
1382
+ },
1383
+ "node_modules/undici-types": {
1384
+ "version": "5.26.5",
1385
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz",
1386
+ "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==",
1387
+ "license": "MIT"
1388
+ },
1389
+ "node_modules/universalify": {
1390
+ "version": "2.0.0",
1391
+ "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.0.tgz",
1392
+ "integrity": "sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ==",
1393
+ "license": "MIT",
1394
+ "engines": {
1395
+ "node": ">= 10.0.0"
1396
+ }
1397
+ },
1398
+ "node_modules/unpipe": {
1399
+ "version": "1.0.0",
1400
+ "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
1401
+ "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
1402
+ "license": "MIT",
1403
+ "engines": {
1404
+ "node": ">= 0.8"
1405
+ }
1406
+ },
1407
+ "node_modules/utils-merge": {
1408
+ "version": "1.0.1",
1409
+ "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
1410
+ "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==",
1411
+ "license": "MIT",
1412
+ "engines": {
1413
+ "node": ">= 0.4.0"
1414
+ }
1415
+ },
1416
+ "node_modules/vary": {
1417
+ "version": "1.1.2",
1418
+ "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
1419
+ "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
1420
+ "license": "MIT",
1421
+ "engines": {
1422
+ "node": ">= 0.8"
1423
+ }
1424
+ },
1425
+ "node_modules/web-streams-polyfill": {
1426
+ "version": "3.3.2",
1427
+ "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.2.tgz",
1428
+ "integrity": "sha512-3pRGuxRF5gpuZc0W+EpwQRmCD7gRqcDOMt688KmdlDAgAyaB1XlN0zq2njfDNm44XVdIouE7pZ6GzbdyH47uIQ==",
1429
+ "license": "MIT",
1430
+ "engines": {
1431
+ "node": ">= 8"
1432
+ }
1433
+ },
1434
+ "node_modules/webidl-conversions": {
1435
+ "version": "3.0.1",
1436
+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
1437
+ "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
1438
+ "license": "BSD-2-Clause"
1439
+ },
1440
+ "node_modules/whatwg-url": {
1441
+ "version": "5.0.0",
1442
+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
1443
+ "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
1444
+ "license": "MIT",
1445
+ "dependencies": {
1446
+ "tr46": "~0.0.3",
1447
+ "webidl-conversions": "^3.0.0"
1448
+ }
1449
+ },
1450
+ "node_modules/yallist": {
1451
+ "version": "4.0.0",
1452
+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
1453
+ "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
1454
+ "dev": true,
1455
+ "license": "ISC"
1456
+ }
1457
+ }
1458
+ }
backend-old/node_modules/@google/generative-ai/LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
backend-old/node_modules/@google/generative-ai/README.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # [Deprecated] Google AI JavaScript SDK for the Gemini API
2
+
3
+ With Gemini 2.0, we took the chance to create a single unified SDK for all developers who want to use Google's GenAI models (Gemini, Veo, Imagen, etc). As part of that process, we took all of the feedback from this SDK and what developers like about other SDKs in the ecosystem to create the [Google Gen AI SDK](https://github.com/googleapis/js-genai).
4
+
5
+ The full migration guide from the old SDK to new SDK is available in the [Gemini API docs](https://ai.google.dev/gemini-api/docs/migrate).
6
+
7
+ The Gemini API docs are fully updated to show examples of the new Google Gen AI SDK. We know how disruptive an SDK change can be and don't take this change lightly, but our goal is to create an extremely simple and clear path for developers to build with our models so it felt necessary to make this change.
8
+
9
+ Thank you for building with Gemini and [let us know](https://discuss.ai.google.dev/c/gemini-api/4) if you need any help!
10
+
11
+ **Please be advised that this repository is now considered legacy.** For the latest features, performance improvements, and active development, we strongly recommend migrating to the official **[Google Generative AI SDK for JavaScript](https://github.com/googleapis/js-genai)**.
12
+
13
+ **Support Plan for this Repository:**
14
+
15
+ * **Limited Maintenance:** Development is now restricted to **critical bug fixes only**. No new features will be added.
16
+ * **Purpose:** This limited support aims to provide stability for users while they transition to the new SDK.
17
+ * **End-of-Life Date:** All support for this repository (including bug fixes) will permanently end on **August 31st, 2025**.
18
+
19
+ We encourage all users to begin planning their migration to the [Google Generative AI SDK](https://github.com/googleapis/js-genai) to ensure continued access to the latest capabilities and support.
20
+
backend-old/node_modules/@google/generative-ai/dist/generative-ai.d.ts ADDED
@@ -0,0 +1,1395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Describes an array, an ordered list of values.
3
+ *
4
+ * @public
5
+ */
6
+ export declare interface ArraySchema extends BaseSchema {
7
+ type: typeof SchemaType.ARRAY;
8
+ /** A schema describing the entries in the array. */
9
+ items: Schema;
10
+ /** The minimum number of items in the array. */
11
+ minItems?: number;
12
+ /** The maximum number of items in the array. */
13
+ maxItems?: number;
14
+ }
15
+
16
+ /**
17
+ * Base parameters for a number of methods.
18
+ * @public
19
+ */
20
+ export declare interface BaseParams {
21
+ safetySettings?: SafetySetting[];
22
+ generationConfig?: GenerationConfig;
23
+ }
24
+
25
+ /**
26
+ * Fields common to all Schema types.
27
+ *
28
+ * @internal
29
+ */
30
+ export declare interface BaseSchema {
31
+ /** Optional. Description of the value. */
32
+ description?: string;
33
+ /** If true, the value can be null. */
34
+ nullable?: boolean;
35
+ }
36
+
37
+ /**
38
+ * Params for calling {@link GenerativeModel.batchEmbedContents}
39
+ * @public
40
+ */
41
+ export declare interface BatchEmbedContentsRequest {
42
+ requests: EmbedContentRequest[];
43
+ }
44
+
45
+ /**
46
+ * Response from calling {@link GenerativeModel.batchEmbedContents}.
47
+ * @public
48
+ */
49
+ export declare interface BatchEmbedContentsResponse {
50
+ embeddings: ContentEmbedding[];
51
+ }
52
+
53
+ /**
54
+ * Reason that a prompt was blocked.
55
+ * @public
56
+ */
57
+ export declare enum BlockReason {
58
+ BLOCKED_REASON_UNSPECIFIED = "BLOCKED_REASON_UNSPECIFIED",
59
+ SAFETY = "SAFETY",
60
+ OTHER = "OTHER"
61
+ }
62
+
63
+ /**
64
+ * Describes a boolean, either 'true' or 'false'.
65
+ *
66
+ * @public
67
+ */
68
+ export declare interface BooleanSchema extends BaseSchema {
69
+ type: typeof SchemaType.BOOLEAN;
70
+ }
71
+
72
+ /**
73
+ * Describes `CachedContent` interface for sending to the server (if creating)
74
+ * or received from the server (using getters or list methods).
75
+ * @public
76
+ */
77
+ export declare interface CachedContent extends CachedContentBase {
78
+ name?: string;
79
+ /**
80
+ * protobuf.Duration format (ex. "3.0001s").
81
+ */
82
+ ttl?: string;
83
+ /**
84
+ * `CachedContent` creation time in ISO string format.
85
+ */
86
+ createTime?: string;
87
+ /**
88
+ * `CachedContent` update time in ISO string format.
89
+ */
90
+ updateTime?: string;
91
+ }
92
+
93
+ /**
94
+ * @public
95
+ */
96
+ export declare interface CachedContentBase {
97
+ model?: string;
98
+ contents: Content[];
99
+ tools?: Tool[];
100
+ toolConfig?: ToolConfig;
101
+ systemInstruction?: string | Part | Content;
102
+ /**
103
+ * Expiration time in ISO string format. Specify either this or `ttlSeconds`
104
+ * when creating a `CachedContent`.
105
+ */
106
+ expireTime?: string;
107
+ displayName?: string;
108
+ }
109
+
110
+ /**
111
+ * ChatSession class that enables sending chat messages and stores
112
+ * history of sent and received messages so far.
113
+ *
114
+ * @public
115
+ */
116
+ export declare class ChatSession {
117
+ model: string;
118
+ params?: StartChatParams;
119
+ private _requestOptions;
120
+ private _apiKey;
121
+ private _history;
122
+ private _sendPromise;
123
+ constructor(apiKey: string, model: string, params?: StartChatParams, _requestOptions?: RequestOptions);
124
+ /**
125
+ * Gets the chat history so far. Blocked prompts are not added to history.
126
+ * Blocked candidates are not added to history, nor are the prompts that
127
+ * generated them.
128
+ */
129
+ getHistory(): Promise<Content[]>;
130
+ /**
131
+ * Sends a chat message and receives a non-streaming
132
+ * {@link GenerateContentResult}.
133
+ *
134
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
135
+ * take precedence over the {@link RequestOptions} values provided to
136
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
137
+ */
138
+ sendMessage(request: string | Array<string | Part>, requestOptions?: SingleRequestOptions): Promise<GenerateContentResult>;
139
+ /**
140
+ * Sends a chat message and receives the response as a
141
+ * {@link GenerateContentStreamResult} containing an iterable stream
142
+ * and a response promise.
143
+ *
144
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
145
+ * take precedence over the {@link RequestOptions} values provided to
146
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
147
+ */
148
+ sendMessageStream(request: string | Array<string | Part>, requestOptions?: SingleRequestOptions): Promise<GenerateContentStreamResult>;
149
+ }
150
+
151
+ /**
152
+ * Citation metadata that may be found on a {@link GenerateContentCandidate}.
153
+ * @public
154
+ */
155
+ export declare interface CitationMetadata {
156
+ citationSources: CitationSource[];
157
+ }
158
+
159
+ /**
160
+ * A single citation source.
161
+ * @public
162
+ */
163
+ export declare interface CitationSource {
164
+ startIndex?: number;
165
+ endIndex?: number;
166
+ uri?: string;
167
+ license?: string;
168
+ }
169
+
170
+ /**
171
+ * Result of executing the `ExecutableCode`.
172
+ * Only generated when using code execution, and always follows a `Part`
173
+ * containing the `ExecutableCode`.
174
+ * @public
175
+ */
176
+ export declare interface CodeExecutionResult {
177
+ /**
178
+ * Outcome of the code execution.
179
+ */
180
+ outcome: Outcome;
181
+ /**
182
+ * Contains stdout when code execution is successful, stderr or other
183
+ * description otherwise.
184
+ */
185
+ output: string;
186
+ }
187
+
188
+ /**
189
+ * Content part containing the result of executed code.
190
+ * @public
191
+ */
192
+ export declare interface CodeExecutionResultPart {
193
+ text?: never;
194
+ inlineData?: never;
195
+ functionCall?: never;
196
+ functionResponse?: never;
197
+ fileData?: never;
198
+ executableCode?: never;
199
+ codeExecutionResult: CodeExecutionResult;
200
+ }
201
+
202
+ /**
203
+ * Enables the model to execute code as part of generation.
204
+ * @public
205
+ */
206
+ export declare interface CodeExecutionTool {
207
+ /**
208
+ * Provide an empty object to enable code execution. This field may have
209
+ * subfields added in the future.
210
+ */
211
+ codeExecution: {};
212
+ }
213
+
214
+ /**
215
+ * Content type for both prompts and response candidates.
216
+ * @public
217
+ */
218
+ export declare interface Content {
219
+ role: string;
220
+ parts: Part[];
221
+ }
222
+
223
+ /**
224
+ * A single content embedding.
225
+ * @public
226
+ */
227
+ export declare interface ContentEmbedding {
228
+ values: number[];
229
+ }
230
+
231
+ /**
232
+ * Params for calling {@link GenerativeModel.countTokens}.
233
+ *
234
+ * The request must contain either a {@link Content} array or a
235
+ * {@link GenerateContentRequest}, but not both. If both are provided
236
+ * then a {@link GoogleGenerativeAIRequestInputError} is thrown.
237
+ *
238
+ * @public
239
+ */
240
+ export declare interface CountTokensRequest {
241
+ generateContentRequest?: GenerateContentRequest;
242
+ contents?: Content[];
243
+ }
244
+
245
+ /**
246
+ * Params for calling {@link GenerativeModel.countTokens}
247
+ * @internal
248
+ */
249
+ export declare interface _CountTokensRequestInternal {
250
+ generateContentRequest?: _GenerateContentRequestInternal;
251
+ contents?: Content[];
252
+ }
253
+
254
+ /**
255
+ * Response from calling {@link GenerativeModel.countTokens}.
256
+ * @public
257
+ */
258
+ export declare interface CountTokensResponse {
259
+ totalTokens: number;
260
+ }
261
+
262
+ /**
263
+ * Specifies the dynamic retrieval configuration for the given source.
264
+ * @public
265
+ */
266
+ export declare interface DynamicRetrievalConfig {
267
+ /**
268
+ * The mode of the predictor to be used in dynamic retrieval.
269
+ */
270
+ mode?: DynamicRetrievalMode;
271
+ /**
272
+ * The threshold to be used in dynamic retrieval. If not set, a system default
273
+ * value is used.
274
+ */
275
+ dynamicThreshold?: number;
276
+ }
277
+
278
+ /**
279
+ * The mode of the predictor to be used in dynamic retrieval.
280
+ * @public
281
+ */
282
+ export declare enum DynamicRetrievalMode {
283
+ MODE_UNSPECIFIED = "MODE_UNSPECIFIED",
284
+ MODE_DYNAMIC = "MODE_DYNAMIC"
285
+ }
286
+
287
+ /**
288
+ * Params for calling {@link GenerativeModel.embedContent}
289
+ * @public
290
+ */
291
+ export declare interface EmbedContentRequest {
292
+ content: Content;
293
+ taskType?: TaskType;
294
+ title?: string;
295
+ }
296
+
297
+ /**
298
+ * Response from calling {@link GenerativeModel.embedContent}.
299
+ * @public
300
+ */
301
+ export declare interface EmbedContentResponse {
302
+ embedding: ContentEmbedding;
303
+ }
304
+
305
+ /**
306
+ * Response object wrapped with helper methods.
307
+ *
308
+ * @public
309
+ */
310
+ export declare interface EnhancedGenerateContentResponse extends GenerateContentResponse {
311
+ /**
312
+ * Returns the text string assembled from all `Part`s of the first candidate
313
+ * of the response, if available.
314
+ * Throws if the prompt or candidate was blocked.
315
+ */
316
+ text: () => string;
317
+ /**
318
+ * Deprecated: use `functionCalls()` instead.
319
+ * @deprecated - use `functionCalls()` instead
320
+ */
321
+ functionCall: () => FunctionCall | undefined;
322
+ /**
323
+ * Returns function calls found in any `Part`s of the first candidate
324
+ * of the response, if available.
325
+ * Throws if the prompt or candidate was blocked.
326
+ */
327
+ functionCalls: () => FunctionCall[] | undefined;
328
+ }
329
+
330
+ /**
331
+ * Describes a string enum
332
+ *
333
+ * @public
334
+ */
335
+ export declare interface EnumStringSchema extends BaseSchema {
336
+ type: typeof SchemaType.STRING;
337
+ format: "enum";
338
+ /** Possible values for this enum */
339
+ enum: string[];
340
+ }
341
+
342
+ /**
343
+ * Details object that may be included in an error response.
344
+ * @public
345
+ */
346
+ export declare interface ErrorDetails {
347
+ "@type"?: string;
348
+ reason?: string;
349
+ domain?: string;
350
+ metadata?: Record<string, unknown>;
351
+ [key: string]: unknown;
352
+ }
353
+
354
+ /**
355
+ * Code generated by the model that is meant to be executed, where the result
356
+ * is returned to the model.
357
+ * Only generated when using the code execution tool, in which the code will
358
+ * be automatically executed, and a corresponding `CodeExecutionResult` will
359
+ * also be generated.
360
+ *
361
+ * @public
362
+ */
363
+ export declare interface ExecutableCode {
364
+ /**
365
+ * Programming language of the `code`.
366
+ */
367
+ language: ExecutableCodeLanguage;
368
+ /**
369
+ * The code to be executed.
370
+ */
371
+ code: string;
372
+ }
373
+
374
+ /**
375
+ * @public
376
+ */
377
+ export declare enum ExecutableCodeLanguage {
378
+ LANGUAGE_UNSPECIFIED = "language_unspecified",
379
+ PYTHON = "python"
380
+ }
381
+
382
+ /**
383
+ * Content part containing executable code generated by the model.
384
+ * @public
385
+ */
386
+ export declare interface ExecutableCodePart {
387
+ text?: never;
388
+ inlineData?: never;
389
+ functionCall?: never;
390
+ functionResponse?: never;
391
+ fileData?: never;
392
+ executableCode: ExecutableCode;
393
+ codeExecutionResult?: never;
394
+ }
395
+
396
+ /**
397
+ * Data pointing to a file uploaded with the Files API.
398
+ * @public
399
+ */
400
+ export declare interface FileData {
401
+ mimeType: string;
402
+ fileUri: string;
403
+ }
404
+
405
+ /**
406
+ * Content part interface if the part represents FileData.
407
+ * @public
408
+ */
409
+ export declare interface FileDataPart {
410
+ text?: never;
411
+ inlineData?: never;
412
+ functionCall?: never;
413
+ functionResponse?: never;
414
+ fileData: FileData;
415
+ executableCode?: never;
416
+ codeExecutionResult?: never;
417
+ }
418
+
419
+ /**
420
+ * Reason that a candidate finished.
421
+ * @public
422
+ */
423
+ export declare enum FinishReason {
424
+ FINISH_REASON_UNSPECIFIED = "FINISH_REASON_UNSPECIFIED",
425
+ STOP = "STOP",
426
+ MAX_TOKENS = "MAX_TOKENS",
427
+ SAFETY = "SAFETY",
428
+ RECITATION = "RECITATION",
429
+ LANGUAGE = "LANGUAGE",
430
+ BLOCKLIST = "BLOCKLIST",
431
+ PROHIBITED_CONTENT = "PROHIBITED_CONTENT",
432
+ SPII = "SPII",
433
+ MALFORMED_FUNCTION_CALL = "MALFORMED_FUNCTION_CALL",
434
+ OTHER = "OTHER"
435
+ }
436
+
437
+ /**
438
+ * A predicted [FunctionCall] returned from the model
439
+ * that contains a string representing the [FunctionDeclaration.name]
440
+ * and a structured JSON object containing the parameters and their values.
441
+ * @public
442
+ */
443
+ export declare interface FunctionCall {
444
+ name: string;
445
+ args: object;
446
+ }
447
+
448
+ /**
449
+ * @public
450
+ */
451
+ export declare interface FunctionCallingConfig {
452
+ mode?: FunctionCallingMode;
453
+ allowedFunctionNames?: string[];
454
+ }
455
+
456
+ /**
457
+ * @public
458
+ */
459
+ export declare enum FunctionCallingMode {
460
+ MODE_UNSPECIFIED = "MODE_UNSPECIFIED",
461
+ AUTO = "AUTO",
462
+ ANY = "ANY",
463
+ NONE = "NONE"
464
+ }
465
+
466
+ /**
467
+ * Content part interface if the part represents a FunctionCall.
468
+ * @public
469
+ */
470
+ export declare interface FunctionCallPart {
471
+ text?: never;
472
+ inlineData?: never;
473
+ functionCall: FunctionCall;
474
+ functionResponse?: never;
475
+ fileData?: never;
476
+ executableCode?: never;
477
+ codeExecutionResult?: never;
478
+ }
479
+
480
+ /**
481
+ * Structured representation of a function declaration as defined by the
482
+ * [OpenAPI 3.0 specification](https://spec.openapis.org/oas/v3.0.3). Included
483
+ * in this declaration are the function name and parameters. This
484
+ * FunctionDeclaration is a representation of a block of code that can be used
485
+ * as a Tool by the model and executed by the client.
486
+ * @public
487
+ */
488
+ export declare interface FunctionDeclaration {
489
+ /**
490
+ * The name of the function to call. Must start with a letter or an
491
+ * underscore. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with
492
+ * a max length of 64.
493
+ */
494
+ name: string;
495
+ /**
496
+ * Optional. Description and purpose of the function. Model uses it to decide
497
+ * how and whether to call the function.
498
+ */
499
+ description?: string;
500
+ /**
501
+ * Optional. Describes the parameters to this function in JSON Schema Object
502
+ * format. Reflects the Open API 3.03 Parameter Object. string Key: the name
503
+ * of the parameter. Parameter names are case sensitive. Schema Value: the
504
+ * Schema defining the type used for the parameter. For function with no
505
+ * parameters, this can be left unset.
506
+ *
507
+ * @example with 1 required and 1 optional parameter: type: OBJECT properties:
508
+ * ```
509
+ * param1:
510
+ *
511
+ * type: STRING
512
+ * param2:
513
+ *
514
+ * type: INTEGER
515
+ * required:
516
+ *
517
+ * - param1
518
+ * ```
519
+ */
520
+ parameters?: FunctionDeclarationSchema;
521
+ }
522
+
523
+ /**
524
+ * Schema for parameters passed to {@link FunctionDeclaration.parameters}.
525
+ * @public
526
+ */
527
+ export declare interface FunctionDeclarationSchema {
528
+ /** The type of the parameter. */
529
+ type: SchemaType;
530
+ /** The format of the parameter. */
531
+ properties: {
532
+ [k: string]: FunctionDeclarationSchemaProperty;
533
+ };
534
+ /** Optional. Description of the parameter. */
535
+ description?: string;
536
+ /** Optional. Array of required parameters. */
537
+ required?: string[];
538
+ }
539
+
540
+ /**
541
+ * Schema for top-level function declaration
542
+ * @public
543
+ */
544
+ export declare type FunctionDeclarationSchemaProperty = Schema;
545
+
546
+ /**
547
+ * A FunctionDeclarationsTool is a piece of code that enables the system to
548
+ * interact with external systems to perform an action, or set of actions,
549
+ * outside of knowledge and scope of the model.
550
+ * @public
551
+ */
552
+ export declare interface FunctionDeclarationsTool {
553
+ /**
554
+ * Optional. One or more function declarations
555
+ * to be passed to the model along with the current user query. Model may
556
+ * decide to call a subset of these functions by populating
557
+ * [FunctionCall][content.part.functionCall] in the response. User should
558
+ * provide a [FunctionResponse][content.part.functionResponse] for each
559
+ * function call in the next turn. Based on the function responses, Model will
560
+ * generate the final response back to the user. Maximum 64 function
561
+ * declarations can be provided.
562
+ */
563
+ functionDeclarations?: FunctionDeclaration[];
564
+ }
565
+
566
+ /**
567
+ * The result output from a [FunctionCall] that contains a string
568
+ * representing the [FunctionDeclaration.name]
569
+ * and a structured JSON object containing any output
570
+ * from the function is used as context to the model.
571
+ * This should contain the result of a [FunctionCall]
572
+ * made based on model prediction.
573
+ * @public
574
+ */
575
+ export declare interface FunctionResponse {
576
+ name: string;
577
+ response: object;
578
+ }
579
+
580
+ /**
581
+ * Content part interface if the part represents FunctionResponse.
582
+ * @public
583
+ */
584
+ export declare interface FunctionResponsePart {
585
+ text?: never;
586
+ inlineData?: never;
587
+ functionCall?: never;
588
+ functionResponse: FunctionResponse;
589
+ fileData?: never;
590
+ executableCode?: never;
591
+ codeExecutionResult?: never;
592
+ }
593
+
594
+ /**
595
+ * A candidate returned as part of a {@link GenerateContentResponse}.
596
+ * @public
597
+ */
598
+ export declare interface GenerateContentCandidate {
599
+ index: number;
600
+ content: Content;
601
+ finishReason?: FinishReason;
602
+ finishMessage?: string;
603
+ safetyRatings?: SafetyRating[];
604
+ citationMetadata?: CitationMetadata;
605
+ /** Average log probability score of the candidate. */
606
+ avgLogprobs?: number;
607
+ /** Log-likelihood scores for the response tokens and top tokens. */
608
+ logprobsResult?: LogprobsResult;
609
+ /** Search grounding metadata. */
610
+ groundingMetadata?: GroundingMetadata;
611
+ }
612
+
613
+ /**
614
+ * Request sent to `generateContent` endpoint.
615
+ * @public
616
+ */
617
+ export declare interface GenerateContentRequest extends BaseParams {
618
+ contents: Content[];
619
+ tools?: Tool[];
620
+ toolConfig?: ToolConfig;
621
+ systemInstruction?: string | Part | Content;
622
+ /**
623
+ * This is the name of a `CachedContent` and not the cache object itself.
624
+ */
625
+ cachedContent?: string;
626
+ }
627
+
628
+ /**
629
+ * Request sent to `generateContent` endpoint.
630
+ * @internal
631
+ */
632
+ export declare interface _GenerateContentRequestInternal extends GenerateContentRequest {
633
+ model?: string;
634
+ }
635
+
636
+ /**
637
+ * Individual response from {@link GenerativeModel.generateContent} and
638
+ * {@link GenerativeModel.generateContentStream}.
639
+ * `generateContentStream()` will return one in each chunk until
640
+ * the stream is done.
641
+ * @public
642
+ */
643
+ export declare interface GenerateContentResponse {
644
+ /** Candidate responses from the model. */
645
+ candidates?: GenerateContentCandidate[];
646
+ /** The prompt's feedback related to the content filters. */
647
+ promptFeedback?: PromptFeedback;
648
+ /** Metadata on the generation request's token usage. */
649
+ usageMetadata?: UsageMetadata;
650
+ }
651
+
652
+ /**
653
+ * Result object returned from generateContent() call.
654
+ *
655
+ * @public
656
+ */
657
+ export declare interface GenerateContentResult {
658
+ response: EnhancedGenerateContentResponse;
659
+ }
660
+
661
+ /**
662
+ * Result object returned from generateContentStream() call.
663
+ * Iterate over `stream` to get chunks as they come in and/or
664
+ * use the `response` promise to get the aggregated response when
665
+ * the stream is done.
666
+ *
667
+ * @public
668
+ */
669
+ export declare interface GenerateContentStreamResult {
670
+ stream: AsyncGenerator<EnhancedGenerateContentResponse>;
671
+ response: Promise<EnhancedGenerateContentResponse>;
672
+ }
673
+
674
+ /**
675
+ * Config options for content-related requests
676
+ * @public
677
+ */
678
+ export declare interface GenerationConfig {
679
+ candidateCount?: number;
680
+ stopSequences?: string[];
681
+ maxOutputTokens?: number;
682
+ temperature?: number;
683
+ topP?: number;
684
+ topK?: number;
685
+ /**
686
+ * Output response mimetype of the generated candidate text.
687
+ * Supported mimetype:
688
+ * `text/plain`: (default) Text output.
689
+ * `application/json`: JSON response in the candidates.
690
+ */
691
+ responseMimeType?: string;
692
+ /**
693
+ * Output response schema of the generated candidate text.
694
+ * Note: This only applies when the specified `responseMIMEType` supports a schema; currently
695
+ * this is limited to `application/json`.
696
+ */
697
+ responseSchema?: ResponseSchema;
698
+ /**
699
+ * Presence penalty applied to the next token's logprobs if the token has
700
+ * already been seen in the response.
701
+ */
702
+ presencePenalty?: number;
703
+ /**
704
+ * Frequency penalty applied to the next token's logprobs, multiplied by the
705
+ * number of times each token has been seen in the respponse so far.
706
+ */
707
+ frequencyPenalty?: number;
708
+ /**
709
+ * If True, export the logprobs results in response.
710
+ */
711
+ responseLogprobs?: boolean;
712
+ /**
713
+ * Valid if responseLogProbs is set to True. This will set the number of top
714
+ * logprobs to return at each decoding step in the logprobsResult.
715
+ */
716
+ logprobs?: number;
717
+ }
718
+
719
+ /**
720
+ * Interface for sending an image.
721
+ * @public
722
+ */
723
+ export declare interface GenerativeContentBlob {
724
+ mimeType: string;
725
+ /**
726
+ * Image as a base64 string.
727
+ */
728
+ data: string;
729
+ }
730
+
731
+ /**
732
+ * Class for generative model APIs.
733
+ * @public
734
+ */
735
+ export declare class GenerativeModel {
736
+ apiKey: string;
737
+ private _requestOptions;
738
+ model: string;
739
+ generationConfig: GenerationConfig;
740
+ safetySettings: SafetySetting[];
741
+ tools?: Tool[];
742
+ toolConfig?: ToolConfig;
743
+ systemInstruction?: Content;
744
+ cachedContent: CachedContent;
745
+ constructor(apiKey: string, modelParams: ModelParams, _requestOptions?: RequestOptions);
746
+ /**
747
+ * Makes a single non-streaming call to the model
748
+ * and returns an object containing a single {@link GenerateContentResponse}.
749
+ *
750
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
751
+ * take precedence over the {@link RequestOptions} values provided to
752
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
753
+ */
754
+ generateContent(request: GenerateContentRequest | string | Array<string | Part>, requestOptions?: SingleRequestOptions): Promise<GenerateContentResult>;
755
+ /**
756
+ * Makes a single streaming call to the model and returns an object
757
+ * containing an iterable stream that iterates over all chunks in the
758
+ * streaming response as well as a promise that returns the final
759
+ * aggregated response.
760
+ *
761
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
762
+ * take precedence over the {@link RequestOptions} values provided to
763
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
764
+ */
765
+ generateContentStream(request: GenerateContentRequest | string | Array<string | Part>, requestOptions?: SingleRequestOptions): Promise<GenerateContentStreamResult>;
766
+ /**
767
+ * Gets a new {@link ChatSession} instance which can be used for
768
+ * multi-turn chats.
769
+ */
770
+ startChat(startChatParams?: StartChatParams): ChatSession;
771
+ /**
772
+ * Counts the tokens in the provided request.
773
+ *
774
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
775
+ * take precedence over the {@link RequestOptions} values provided to
776
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
777
+ */
778
+ countTokens(request: CountTokensRequest | string | Array<string | Part>, requestOptions?: SingleRequestOptions): Promise<CountTokensResponse>;
779
+ /**
780
+ * Embeds the provided content.
781
+ *
782
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
783
+ * take precedence over the {@link RequestOptions} values provided to
784
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
785
+ */
786
+ embedContent(request: EmbedContentRequest | string | Array<string | Part>, requestOptions?: SingleRequestOptions): Promise<EmbedContentResponse>;
787
+ /**
788
+ * Embeds an array of {@link EmbedContentRequest}s.
789
+ *
790
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
791
+ * take precedence over the {@link RequestOptions} values provided to
792
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
793
+ */
794
+ batchEmbedContents(batchEmbedContentRequest: BatchEmbedContentsRequest, requestOptions?: SingleRequestOptions): Promise<BatchEmbedContentsResponse>;
795
+ }
796
+
797
+ /**
798
+ * Top-level class for this SDK
799
+ * @public
800
+ */
801
+ export declare class GoogleGenerativeAI {
802
+ apiKey: string;
803
+ constructor(apiKey: string);
804
+ /**
805
+ * Gets a {@link GenerativeModel} instance for the provided model name.
806
+ */
807
+ getGenerativeModel(modelParams: ModelParams, requestOptions?: RequestOptions): GenerativeModel;
808
+ /**
809
+ * Creates a {@link GenerativeModel} instance from provided content cache.
810
+ */
811
+ getGenerativeModelFromCachedContent(cachedContent: CachedContent, modelParams?: Partial<ModelParams>, requestOptions?: RequestOptions): GenerativeModel;
812
+ }
813
+
814
+ /**
815
+ * Error thrown when a request is aborted, either due to a timeout or
816
+ * intentional cancellation by the user.
817
+ * @public
818
+ */
819
+ export declare class GoogleGenerativeAIAbortError extends GoogleGenerativeAIError {
820
+ }
821
+
822
+ /**
823
+ * Basic error type for this SDK.
824
+ * @public
825
+ */
826
+ export declare class GoogleGenerativeAIError extends Error {
827
+ constructor(message: string);
828
+ }
829
+
830
+ /**
831
+ * Error class covering HTTP errors when calling the server. Includes HTTP
832
+ * status, statusText, and optional details, if provided in the server response.
833
+ * @public
834
+ */
835
+ export declare class GoogleGenerativeAIFetchError extends GoogleGenerativeAIError {
836
+ status?: number;
837
+ statusText?: string;
838
+ errorDetails?: ErrorDetails[];
839
+ constructor(message: string, status?: number, statusText?: string, errorDetails?: ErrorDetails[]);
840
+ }
841
+
842
+ /**
843
+ * Errors in the contents of a request originating from user input.
844
+ * @public
845
+ */
846
+ export declare class GoogleGenerativeAIRequestInputError extends GoogleGenerativeAIError {
847
+ }
848
+
849
+ /**
850
+ * Errors in the contents of a response from the model. This includes parsing
851
+ * errors, or responses including a safety block reason.
852
+ * @public
853
+ */
854
+ export declare class GoogleGenerativeAIResponseError<T> extends GoogleGenerativeAIError {
855
+ response?: T;
856
+ constructor(message: string, response?: T);
857
+ }
858
+
859
+ /**
860
+ * Retrieval tool that is powered by Google search.
861
+ * @public
862
+ */
863
+ export declare interface GoogleSearchRetrieval {
864
+ /**
865
+ * Specifies the dynamic retrieval configuration for the given source.
866
+ */
867
+ dynamicRetrievalConfig?: DynamicRetrievalConfig;
868
+ }
869
+
870
+ /**
871
+ * Retrieval tool that is powered by Google search.
872
+ * @public
873
+ */
874
+ export declare interface GoogleSearchRetrievalTool {
875
+ /**
876
+ * Google search retrieval tool config.
877
+ */
878
+ googleSearchRetrieval?: GoogleSearchRetrieval;
879
+ }
880
+
881
+ /**
882
+ * Grounding chunk.
883
+ * @public
884
+ */
885
+ export declare interface GroundingChunk {
886
+ /**
887
+ * Chunk from the web.
888
+ */
889
+ web?: GroundingChunkWeb;
890
+ }
891
+
892
+ /**
893
+ * Chunk from the web.
894
+ * @public
895
+ */
896
+ export declare interface GroundingChunkWeb {
897
+ /**
898
+ * URI reference of the chunk.
899
+ */
900
+ uri?: string;
901
+ /**
902
+ * Title of the chunk.
903
+ */
904
+ title?: string;
905
+ }
906
+
907
+ /**
908
+ * Metadata returned to client when grounding is enabled.
909
+ * @public
910
+ */
911
+ export declare interface GroundingMetadata {
912
+ /**
913
+ * Google search entry for the following-up web searches.
914
+ */
915
+ searchEntryPoint?: SearchEntryPoint;
916
+ /**
917
+ * List of supporting references retrieved from specified grounding source.
918
+ */
919
+ groundingChunks?: GroundingChunk[];
920
+ /**
921
+ * List of grounding support.
922
+ */
923
+ groundingSupports?: GroundingSupport[];
924
+ /**
925
+ * Metadata related to retrieval in the grounding flow.
926
+ */
927
+ retrievalMetadata?: RetrievalMetadata;
928
+ /**
929
+ * * Web search queries for the following-up web search.
930
+ */
931
+ webSearchQueries: string[];
932
+ }
933
+
934
+ /**
935
+ * Grounding support.
936
+ * @public
937
+ */
938
+ export declare interface GroundingSupport {
939
+ /**
940
+ * URI reference of the chunk.
941
+ */
942
+ segment?: string;
943
+ /**
944
+ * A list of indices (into 'grounding_chunk') specifying the citations
945
+ * associated with the claim. For instance [1,3,4] means that
946
+ * grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the
947
+ * retrieved content attributed to the claim.
948
+ */
949
+ groundingChunckIndices?: number[];
950
+ /**
951
+ * Confidence score of the support references. Ranges from 0 to 1. 1 is the
952
+ * most confident. This list must have the same size as the
953
+ * grounding_chunk_indices.
954
+ */
955
+ confidenceScores?: number[];
956
+ }
957
+
958
+ /**
959
+ * Segment of the content.
960
+ * @public
961
+ */
962
+ export declare interface GroundingSupportSegment {
963
+ /**
964
+ * The index of a Part object within its parent Content object.
965
+ */
966
+ partIndex?: number;
967
+ /**
968
+ * Start index in the given Part, measured in bytes. Offset from the start of
969
+ * the Part, inclusive, starting at zero.
970
+ */
971
+ startIndex?: number;
972
+ /**
973
+ * End index in the given Part, measured in bytes. Offset from the start of
974
+ * the Part, exclusive, starting at zero.
975
+ */
976
+ endIndex?: number;
977
+ /**
978
+ * The text corresponding to the segment from the response.
979
+ */
980
+ text?: string;
981
+ }
982
+
983
+ /**
984
+ * Threshold above which a prompt or candidate will be blocked.
985
+ * @public
986
+ */
987
+ export declare enum HarmBlockThreshold {
988
+ /** Threshold is unspecified. */
989
+ HARM_BLOCK_THRESHOLD_UNSPECIFIED = "HARM_BLOCK_THRESHOLD_UNSPECIFIED",
990
+ /** Content with NEGLIGIBLE will be allowed. */
991
+ BLOCK_LOW_AND_ABOVE = "BLOCK_LOW_AND_ABOVE",
992
+ /** Content with NEGLIGIBLE and LOW will be allowed. */
993
+ BLOCK_MEDIUM_AND_ABOVE = "BLOCK_MEDIUM_AND_ABOVE",
994
+ /** Content with NEGLIGIBLE, LOW, and MEDIUM will be allowed. */
995
+ BLOCK_ONLY_HIGH = "BLOCK_ONLY_HIGH",
996
+ /** All content will be allowed. */
997
+ BLOCK_NONE = "BLOCK_NONE"
998
+ }
999
+
1000
+ /**
1001
+ * Harm categories that would cause prompts or candidates to be blocked.
1002
+ * @public
1003
+ */
1004
+ export declare enum HarmCategory {
1005
+ HARM_CATEGORY_UNSPECIFIED = "HARM_CATEGORY_UNSPECIFIED",
1006
+ HARM_CATEGORY_HATE_SPEECH = "HARM_CATEGORY_HATE_SPEECH",
1007
+ HARM_CATEGORY_SEXUALLY_EXPLICIT = "HARM_CATEGORY_SEXUALLY_EXPLICIT",
1008
+ HARM_CATEGORY_HARASSMENT = "HARM_CATEGORY_HARASSMENT",
1009
+ HARM_CATEGORY_DANGEROUS_CONTENT = "HARM_CATEGORY_DANGEROUS_CONTENT",
1010
+ HARM_CATEGORY_CIVIC_INTEGRITY = "HARM_CATEGORY_CIVIC_INTEGRITY"
1011
+ }
1012
+
1013
+ /**
1014
+ * Probability that a prompt or candidate matches a harm category.
1015
+ * @public
1016
+ */
1017
+ export declare enum HarmProbability {
1018
+ /** Probability is unspecified. */
1019
+ HARM_PROBABILITY_UNSPECIFIED = "HARM_PROBABILITY_UNSPECIFIED",
1020
+ /** Content has a negligible chance of being unsafe. */
1021
+ NEGLIGIBLE = "NEGLIGIBLE",
1022
+ /** Content has a low chance of being unsafe. */
1023
+ LOW = "LOW",
1024
+ /** Content has a medium chance of being unsafe. */
1025
+ MEDIUM = "MEDIUM",
1026
+ /** Content has a high chance of being unsafe. */
1027
+ HIGH = "HIGH"
1028
+ }
1029
+
1030
+ /**
1031
+ * Content part interface if the part represents an image.
1032
+ * @public
1033
+ */
1034
+ export declare interface InlineDataPart {
1035
+ text?: never;
1036
+ inlineData: GenerativeContentBlob;
1037
+ functionCall?: never;
1038
+ functionResponse?: never;
1039
+ fileData?: never;
1040
+ executableCode?: never;
1041
+ codeExecutionResult?: never;
1042
+ }
1043
+
1044
+ /**
1045
+ * Describes a JSON-encodable integer.
1046
+ *
1047
+ * @public
1048
+ */
1049
+ export declare interface IntegerSchema extends BaseSchema {
1050
+ type: typeof SchemaType.INTEGER;
1051
+ /** Optional. The format of the number. */
1052
+ format?: "int32" | "int64";
1053
+ }
1054
+
1055
+ /**
1056
+ * Candidate for the logprobs token and score.
1057
+ * @public
1058
+ */
1059
+ export declare interface LogprobsCandidate {
1060
+ /** The candidate's token string value. */
1061
+ token: string;
1062
+ /** The candidate's token id value. */
1063
+ tokenID: number;
1064
+ /** The candidate's log probability. */
1065
+ logProbability: number;
1066
+ }
1067
+
1068
+ /**
1069
+ * Logprobs Result
1070
+ * @public
1071
+ */
1072
+ export declare interface LogprobsResult {
1073
+ /** Length = total number of decoding steps. */
1074
+ topCandidates: TopCandidates[];
1075
+ /**
1076
+ * Length = total number of decoding steps.
1077
+ * The chosen candidates may or may not be in topCandidates.
1078
+ */
1079
+ chosenCandidates: LogprobsCandidate[];
1080
+ }
1081
+
1082
+ /**
1083
+ * Params passed to {@link GoogleGenerativeAI.getGenerativeModel}.
1084
+ * @public
1085
+ */
1086
+ export declare interface ModelParams extends BaseParams {
1087
+ model: string;
1088
+ tools?: Tool[];
1089
+ toolConfig?: ToolConfig;
1090
+ systemInstruction?: string | Part | Content;
1091
+ cachedContent?: CachedContent;
1092
+ }
1093
+
1094
+ /**
1095
+ * Describes a JSON-encodable floating point number.
1096
+ *
1097
+ * @public
1098
+ */
1099
+ export declare interface NumberSchema extends BaseSchema {
1100
+ type: typeof SchemaType.NUMBER;
1101
+ /** Optional. The format of the number. */
1102
+ format?: "float" | "double";
1103
+ }
1104
+
1105
+ /**
1106
+ * Describes a JSON object, a mapping of specific keys to values.
1107
+ *
1108
+ * @public
1109
+ */
1110
+ export declare interface ObjectSchema extends BaseSchema {
1111
+ type: typeof SchemaType.OBJECT;
1112
+ /** Describes the properties of the JSON object. Must not be empty. */
1113
+ properties: {
1114
+ [k: string]: Schema;
1115
+ };
1116
+ /**
1117
+ * A list of keys declared in the properties object.
1118
+ * Required properties will always be present in the generated object.
1119
+ */
1120
+ required?: string[];
1121
+ }
1122
+
1123
+ /**
1124
+ * Possible outcomes of code execution.
1125
+ * @public
1126
+ */
1127
+ export declare enum Outcome {
1128
+ /**
1129
+ * Unspecified status. This value should not be used.
1130
+ */
1131
+ OUTCOME_UNSPECIFIED = "outcome_unspecified",
1132
+ /**
1133
+ * Code execution completed successfully.
1134
+ */
1135
+ OUTCOME_OK = "outcome_ok",
1136
+ /**
1137
+ * Code execution finished but with a failure. `stderr` should contain the
1138
+ * reason.
1139
+ */
1140
+ OUTCOME_FAILED = "outcome_failed",
1141
+ /**
1142
+ * Code execution ran for too long, and was cancelled. There may or may not
1143
+ * be a partial output present.
1144
+ */
1145
+ OUTCOME_DEADLINE_EXCEEDED = "outcome_deadline_exceeded"
1146
+ }
1147
+
1148
+ /**
1149
+ * Content part - includes text or image part types.
1150
+ * @public
1151
+ */
1152
+ export declare type Part = TextPart | InlineDataPart | FunctionCallPart | FunctionResponsePart | FileDataPart | ExecutableCodePart | CodeExecutionResultPart;
1153
+
1154
+ /**
1155
+ * Possible roles.
1156
+ * @public
1157
+ */
1158
+ export declare const POSSIBLE_ROLES: readonly ["user", "model", "function", "system"];
1159
+
1160
+ /**
1161
+ * If the prompt was blocked, this will be populated with `blockReason` and
1162
+ * the relevant `safetyRatings`.
1163
+ * @public
1164
+ */
1165
+ export declare interface PromptFeedback {
1166
+ blockReason: BlockReason;
1167
+ safetyRatings: SafetyRating[];
1168
+ blockReasonMessage?: string;
1169
+ }
1170
+
1171
+ /**
1172
+ * Params passed to getGenerativeModel() or GoogleAIFileManager().
1173
+ * @public
1174
+ */
1175
+ export declare interface RequestOptions {
1176
+ /**
1177
+ * Request timeout in milliseconds.
1178
+ */
1179
+ timeout?: number;
1180
+ /**
1181
+ * Version of API endpoint to call (e.g. "v1" or "v1beta"). If not specified,
1182
+ * defaults to latest stable version.
1183
+ */
1184
+ apiVersion?: string;
1185
+ /**
1186
+ * Additional attribution information to include in the x-goog-api-client header.
1187
+ * Used by wrapper SDKs.
1188
+ */
1189
+ apiClient?: string;
1190
+ /**
1191
+ * Base endpoint url. Defaults to "https://generativelanguage.googleapis.com"
1192
+ */
1193
+ baseUrl?: string;
1194
+ /**
1195
+ * Custom HTTP request headers.
1196
+ */
1197
+ customHeaders?: Headers | Record<string, string>;
1198
+ }
1199
+
1200
+ /**
1201
+ * Schema passed to `GenerationConfig.responseSchema`
1202
+ * @public
1203
+ */
1204
+ export declare type ResponseSchema = Schema;
1205
+
1206
+ /**
1207
+ * Metadata related to retrieval in the grounding flow.
1208
+ * @public
1209
+ */
1210
+ export declare interface RetrievalMetadata {
1211
+ /**
1212
+ * Score indicating how likely information from google search could help
1213
+ * answer the prompt. The score is in the range [0, 1], where 0 is the least
1214
+ * likely and 1 is the most likely. This score is only populated when google
1215
+ * search grounding and dynamic retrieval is enabled. It will becompared to
1216
+ * the threshold to determine whether to trigger google search.
1217
+ */
1218
+ googleSearchDynamicRetrievalScore?: number;
1219
+ }
1220
+
1221
+ /**
1222
+ * A safety rating associated with a {@link GenerateContentCandidate}
1223
+ * @public
1224
+ */
1225
+ export declare interface SafetyRating {
1226
+ category: HarmCategory;
1227
+ probability: HarmProbability;
1228
+ }
1229
+
1230
+ /**
1231
+ * Safety setting that can be sent as part of request parameters.
1232
+ * @public
1233
+ */
1234
+ export declare interface SafetySetting {
1235
+ category: HarmCategory;
1236
+ threshold: HarmBlockThreshold;
1237
+ }
1238
+
1239
+ /**
1240
+ * Schema is used to define the format of input/output data.
1241
+ * Represents a select subset of an OpenAPI 3.0 schema object.
1242
+ * More fields may be added in the future as needed.
1243
+ * @public
1244
+ */
1245
+ export declare type Schema = StringSchema | NumberSchema | IntegerSchema | BooleanSchema | ArraySchema | ObjectSchema;
1246
+
1247
+ /**
1248
+ * Contains the list of OpenAPI data types
1249
+ * as defined by https://swagger.io/docs/specification/data-models/data-types/
1250
+ * @public
1251
+ */
1252
+ export declare enum SchemaType {
1253
+ /** String type. */
1254
+ STRING = "string",
1255
+ /** Number type. */
1256
+ NUMBER = "number",
1257
+ /** Integer type. */
1258
+ INTEGER = "integer",
1259
+ /** Boolean type. */
1260
+ BOOLEAN = "boolean",
1261
+ /** Array type. */
1262
+ ARRAY = "array",
1263
+ /** Object type. */
1264
+ OBJECT = "object"
1265
+ }
1266
+
1267
+ /**
1268
+ * Google search entry point.
1269
+ * @public
1270
+ */
1271
+ export declare interface SearchEntryPoint {
1272
+ /**
1273
+ * Web content snippet that can be embedded in a web page or an app webview.
1274
+ */
1275
+ renderedContent?: string;
1276
+ /**
1277
+ * Base64 encoded JSON representing array of <search term, search url> tuple.
1278
+ */
1279
+ sdkBlob?: string;
1280
+ }
1281
+
1282
+ /**
1283
+ * Describes a simple string schema, with or without format
1284
+ *
1285
+ * @public
1286
+ */
1287
+ export declare interface SimpleStringSchema extends BaseSchema {
1288
+ type: typeof SchemaType.STRING;
1289
+ format?: "date-time" | undefined;
1290
+ enum?: never;
1291
+ }
1292
+
1293
+ /**
1294
+ * Params passed to atomic asynchronous operations.
1295
+ * @public
1296
+ */
1297
+ export declare interface SingleRequestOptions extends RequestOptions {
1298
+ /**
1299
+ * An object that may be used to abort asynchronous requests. The request may
1300
+ * also be aborted due to the expiration of the timeout value, if provided.
1301
+ *
1302
+ * NOTE: AbortSignal is a client-only operation. Using it to cancel an
1303
+ * operation will not cancel the request in the service. You will still
1304
+ * be charged usage for any applicable operations.
1305
+ */
1306
+ signal?: AbortSignal;
1307
+ }
1308
+
1309
+ /**
1310
+ * Params for {@link GenerativeModel.startChat}.
1311
+ * @public
1312
+ */
1313
+ export declare interface StartChatParams extends BaseParams {
1314
+ history?: Content[];
1315
+ tools?: Tool[];
1316
+ toolConfig?: ToolConfig;
1317
+ systemInstruction?: string | Part | Content;
1318
+ /**
1319
+ * This is the name of a `CachedContent` and not the cache object itself.
1320
+ */
1321
+ cachedContent?: string;
1322
+ }
1323
+
1324
+ /**
1325
+ * Describes a string.
1326
+ *
1327
+ * @public
1328
+ */
1329
+ export declare type StringSchema = SimpleStringSchema | EnumStringSchema;
1330
+
1331
+ /**
1332
+ * Task type for embedding content.
1333
+ * @public
1334
+ */
1335
+ export declare enum TaskType {
1336
+ TASK_TYPE_UNSPECIFIED = "TASK_TYPE_UNSPECIFIED",
1337
+ RETRIEVAL_QUERY = "RETRIEVAL_QUERY",
1338
+ RETRIEVAL_DOCUMENT = "RETRIEVAL_DOCUMENT",
1339
+ SEMANTIC_SIMILARITY = "SEMANTIC_SIMILARITY",
1340
+ CLASSIFICATION = "CLASSIFICATION",
1341
+ CLUSTERING = "CLUSTERING"
1342
+ }
1343
+
1344
+ /**
1345
+ * Content part interface if the part represents a text string.
1346
+ * @public
1347
+ */
1348
+ export declare interface TextPart {
1349
+ text: string;
1350
+ inlineData?: never;
1351
+ functionCall?: never;
1352
+ functionResponse?: never;
1353
+ fileData?: never;
1354
+ executableCode?: never;
1355
+ codeExecutionResult?: never;
1356
+ }
1357
+
1358
+ /**
1359
+ * Defines a tool that model can call to access external knowledge.
1360
+ * @public
1361
+ */
1362
+ export declare type Tool = FunctionDeclarationsTool | CodeExecutionTool | GoogleSearchRetrievalTool;
1363
+
1364
+ /**
1365
+ * Tool config. This config is shared for all tools provided in the request.
1366
+ * @public
1367
+ */
1368
+ export declare interface ToolConfig {
1369
+ functionCallingConfig: FunctionCallingConfig;
1370
+ }
1371
+
1372
+ /**
1373
+ * Candidates with top log probabilities at each decoding step
1374
+ */
1375
+ export declare interface TopCandidates {
1376
+ /** Sorted by log probability in descending order. */
1377
+ candidates: LogprobsCandidate[];
1378
+ }
1379
+
1380
+ /**
1381
+ * Metadata on the generation request's token usage.
1382
+ * @public
1383
+ */
1384
+ export declare interface UsageMetadata {
1385
+ /** Number of tokens in the prompt. */
1386
+ promptTokenCount: number;
1387
+ /** Total number of tokens across the generated candidates. */
1388
+ candidatesTokenCount: number;
1389
+ /** Total token count for the generation request (prompt + candidates). */
1390
+ totalTokenCount: number;
1391
+ /** Total token count in the cached part of the prompt, i.e. in the cached content. */
1392
+ cachedContentTokenCount?: number;
1393
+ }
1394
+
1395
+ export { }
backend-old/node_modules/@google/generative-ai/dist/index.js ADDED
@@ -0,0 +1,1530 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ /**
4
+ * Contains the list of OpenAPI data types
5
+ * as defined by https://swagger.io/docs/specification/data-models/data-types/
6
+ * @public
7
+ */
8
+ exports.SchemaType = void 0;
9
+ (function (SchemaType) {
10
+ /** String type. */
11
+ SchemaType["STRING"] = "string";
12
+ /** Number type. */
13
+ SchemaType["NUMBER"] = "number";
14
+ /** Integer type. */
15
+ SchemaType["INTEGER"] = "integer";
16
+ /** Boolean type. */
17
+ SchemaType["BOOLEAN"] = "boolean";
18
+ /** Array type. */
19
+ SchemaType["ARRAY"] = "array";
20
+ /** Object type. */
21
+ SchemaType["OBJECT"] = "object";
22
+ })(exports.SchemaType || (exports.SchemaType = {}));
23
+
24
+ /**
25
+ * @license
26
+ * Copyright 2024 Google LLC
27
+ *
28
+ * Licensed under the Apache License, Version 2.0 (the "License");
29
+ * you may not use this file except in compliance with the License.
30
+ * You may obtain a copy of the License at
31
+ *
32
+ * http://www.apache.org/licenses/LICENSE-2.0
33
+ *
34
+ * Unless required by applicable law or agreed to in writing, software
35
+ * distributed under the License is distributed on an "AS IS" BASIS,
36
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
37
+ * See the License for the specific language governing permissions and
38
+ * limitations under the License.
39
+ */
40
+ /**
41
+ * @public
42
+ */
43
+ exports.ExecutableCodeLanguage = void 0;
44
+ (function (ExecutableCodeLanguage) {
45
+ ExecutableCodeLanguage["LANGUAGE_UNSPECIFIED"] = "language_unspecified";
46
+ ExecutableCodeLanguage["PYTHON"] = "python";
47
+ })(exports.ExecutableCodeLanguage || (exports.ExecutableCodeLanguage = {}));
48
+ /**
49
+ * Possible outcomes of code execution.
50
+ * @public
51
+ */
52
+ exports.Outcome = void 0;
53
+ (function (Outcome) {
54
+ /**
55
+ * Unspecified status. This value should not be used.
56
+ */
57
+ Outcome["OUTCOME_UNSPECIFIED"] = "outcome_unspecified";
58
+ /**
59
+ * Code execution completed successfully.
60
+ */
61
+ Outcome["OUTCOME_OK"] = "outcome_ok";
62
+ /**
63
+ * Code execution finished but with a failure. `stderr` should contain the
64
+ * reason.
65
+ */
66
+ Outcome["OUTCOME_FAILED"] = "outcome_failed";
67
+ /**
68
+ * Code execution ran for too long, and was cancelled. There may or may not
69
+ * be a partial output present.
70
+ */
71
+ Outcome["OUTCOME_DEADLINE_EXCEEDED"] = "outcome_deadline_exceeded";
72
+ })(exports.Outcome || (exports.Outcome = {}));
73
+
74
+ /**
75
+ * @license
76
+ * Copyright 2024 Google LLC
77
+ *
78
+ * Licensed under the Apache License, Version 2.0 (the "License");
79
+ * you may not use this file except in compliance with the License.
80
+ * You may obtain a copy of the License at
81
+ *
82
+ * http://www.apache.org/licenses/LICENSE-2.0
83
+ *
84
+ * Unless required by applicable law or agreed to in writing, software
85
+ * distributed under the License is distributed on an "AS IS" BASIS,
86
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
87
+ * See the License for the specific language governing permissions and
88
+ * limitations under the License.
89
+ */
90
+ /**
91
+ * Possible roles.
92
+ * @public
93
+ */
94
+ const POSSIBLE_ROLES = ["user", "model", "function", "system"];
95
+ /**
96
+ * Harm categories that would cause prompts or candidates to be blocked.
97
+ * @public
98
+ */
99
+ exports.HarmCategory = void 0;
100
+ (function (HarmCategory) {
101
+ HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED";
102
+ HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH";
103
+ HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT";
104
+ HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT";
105
+ HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT";
106
+ HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY";
107
+ })(exports.HarmCategory || (exports.HarmCategory = {}));
108
+ /**
109
+ * Threshold above which a prompt or candidate will be blocked.
110
+ * @public
111
+ */
112
+ exports.HarmBlockThreshold = void 0;
113
+ (function (HarmBlockThreshold) {
114
+ /** Threshold is unspecified. */
115
+ HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED";
116
+ /** Content with NEGLIGIBLE will be allowed. */
117
+ HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE";
118
+ /** Content with NEGLIGIBLE and LOW will be allowed. */
119
+ HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE";
120
+ /** Content with NEGLIGIBLE, LOW, and MEDIUM will be allowed. */
121
+ HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH";
122
+ /** All content will be allowed. */
123
+ HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE";
124
+ })(exports.HarmBlockThreshold || (exports.HarmBlockThreshold = {}));
125
+ /**
126
+ * Probability that a prompt or candidate matches a harm category.
127
+ * @public
128
+ */
129
+ exports.HarmProbability = void 0;
130
+ (function (HarmProbability) {
131
+ /** Probability is unspecified. */
132
+ HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED";
133
+ /** Content has a negligible chance of being unsafe. */
134
+ HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE";
135
+ /** Content has a low chance of being unsafe. */
136
+ HarmProbability["LOW"] = "LOW";
137
+ /** Content has a medium chance of being unsafe. */
138
+ HarmProbability["MEDIUM"] = "MEDIUM";
139
+ /** Content has a high chance of being unsafe. */
140
+ HarmProbability["HIGH"] = "HIGH";
141
+ })(exports.HarmProbability || (exports.HarmProbability = {}));
142
+ /**
143
+ * Reason that a prompt was blocked.
144
+ * @public
145
+ */
146
+ exports.BlockReason = void 0;
147
+ (function (BlockReason) {
148
+ // A blocked reason was not specified.
149
+ BlockReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED";
150
+ // Content was blocked by safety settings.
151
+ BlockReason["SAFETY"] = "SAFETY";
152
+ // Content was blocked, but the reason is uncategorized.
153
+ BlockReason["OTHER"] = "OTHER";
154
+ })(exports.BlockReason || (exports.BlockReason = {}));
155
+ /**
156
+ * Reason that a candidate finished.
157
+ * @public
158
+ */
159
+ exports.FinishReason = void 0;
160
+ (function (FinishReason) {
161
+ // Default value. This value is unused.
162
+ FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED";
163
+ // Natural stop point of the model or provided stop sequence.
164
+ FinishReason["STOP"] = "STOP";
165
+ // The maximum number of tokens as specified in the request was reached.
166
+ FinishReason["MAX_TOKENS"] = "MAX_TOKENS";
167
+ // The candidate content was flagged for safety reasons.
168
+ FinishReason["SAFETY"] = "SAFETY";
169
+ // The candidate content was flagged for recitation reasons.
170
+ FinishReason["RECITATION"] = "RECITATION";
171
+ // The candidate content was flagged for using an unsupported language.
172
+ FinishReason["LANGUAGE"] = "LANGUAGE";
173
+ // Token generation stopped because the content contains forbidden terms.
174
+ FinishReason["BLOCKLIST"] = "BLOCKLIST";
175
+ // Token generation stopped for potentially containing prohibited content.
176
+ FinishReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT";
177
+ // Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII).
178
+ FinishReason["SPII"] = "SPII";
179
+ // The function call generated by the model is invalid.
180
+ FinishReason["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL";
181
+ // Unknown reason.
182
+ FinishReason["OTHER"] = "OTHER";
183
+ })(exports.FinishReason || (exports.FinishReason = {}));
184
+ /**
185
+ * Task type for embedding content.
186
+ * @public
187
+ */
188
+ exports.TaskType = void 0;
189
+ (function (TaskType) {
190
+ TaskType["TASK_TYPE_UNSPECIFIED"] = "TASK_TYPE_UNSPECIFIED";
191
+ TaskType["RETRIEVAL_QUERY"] = "RETRIEVAL_QUERY";
192
+ TaskType["RETRIEVAL_DOCUMENT"] = "RETRIEVAL_DOCUMENT";
193
+ TaskType["SEMANTIC_SIMILARITY"] = "SEMANTIC_SIMILARITY";
194
+ TaskType["CLASSIFICATION"] = "CLASSIFICATION";
195
+ TaskType["CLUSTERING"] = "CLUSTERING";
196
+ })(exports.TaskType || (exports.TaskType = {}));
197
+ /**
198
+ * @public
199
+ */
200
+ exports.FunctionCallingMode = void 0;
201
+ (function (FunctionCallingMode) {
202
+ // Unspecified function calling mode. This value should not be used.
203
+ FunctionCallingMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
204
+ // Default model behavior, model decides to predict either a function call
205
+ // or a natural language repspose.
206
+ FunctionCallingMode["AUTO"] = "AUTO";
207
+ // Model is constrained to always predicting a function call only.
208
+ // If "allowed_function_names" are set, the predicted function call will be
209
+ // limited to any one of "allowed_function_names", else the predicted
210
+ // function call will be any one of the provided "function_declarations".
211
+ FunctionCallingMode["ANY"] = "ANY";
212
+ // Model will not predict any function call. Model behavior is same as when
213
+ // not passing any function declarations.
214
+ FunctionCallingMode["NONE"] = "NONE";
215
+ })(exports.FunctionCallingMode || (exports.FunctionCallingMode = {}));
216
+ /**
217
+ * The mode of the predictor to be used in dynamic retrieval.
218
+ * @public
219
+ */
220
+ exports.DynamicRetrievalMode = void 0;
221
+ (function (DynamicRetrievalMode) {
222
+ // Unspecified function calling mode. This value should not be used.
223
+ DynamicRetrievalMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
224
+ // Run retrieval only when system decides it is necessary.
225
+ DynamicRetrievalMode["MODE_DYNAMIC"] = "MODE_DYNAMIC";
226
+ })(exports.DynamicRetrievalMode || (exports.DynamicRetrievalMode = {}));
227
+
228
+ /**
229
+ * @license
230
+ * Copyright 2024 Google LLC
231
+ *
232
+ * Licensed under the Apache License, Version 2.0 (the "License");
233
+ * you may not use this file except in compliance with the License.
234
+ * You may obtain a copy of the License at
235
+ *
236
+ * http://www.apache.org/licenses/LICENSE-2.0
237
+ *
238
+ * Unless required by applicable law or agreed to in writing, software
239
+ * distributed under the License is distributed on an "AS IS" BASIS,
240
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
241
+ * See the License for the specific language governing permissions and
242
+ * limitations under the License.
243
+ */
244
+ /**
245
+ * Basic error type for this SDK.
246
+ * @public
247
+ */
248
+ class GoogleGenerativeAIError extends Error {
249
+ constructor(message) {
250
+ super(`[GoogleGenerativeAI Error]: ${message}`);
251
+ }
252
+ }
253
+ /**
254
+ * Errors in the contents of a response from the model. This includes parsing
255
+ * errors, or responses including a safety block reason.
256
+ * @public
257
+ */
258
+ class GoogleGenerativeAIResponseError extends GoogleGenerativeAIError {
259
+ constructor(message, response) {
260
+ super(message);
261
+ this.response = response;
262
+ }
263
+ }
264
+ /**
265
+ * Error class covering HTTP errors when calling the server. Includes HTTP
266
+ * status, statusText, and optional details, if provided in the server response.
267
+ * @public
268
+ */
269
+ class GoogleGenerativeAIFetchError extends GoogleGenerativeAIError {
270
+ constructor(message, status, statusText, errorDetails) {
271
+ super(message);
272
+ this.status = status;
273
+ this.statusText = statusText;
274
+ this.errorDetails = errorDetails;
275
+ }
276
+ }
277
+ /**
278
+ * Errors in the contents of a request originating from user input.
279
+ * @public
280
+ */
281
+ class GoogleGenerativeAIRequestInputError extends GoogleGenerativeAIError {
282
+ }
283
+ /**
284
+ * Error thrown when a request is aborted, either due to a timeout or
285
+ * intentional cancellation by the user.
286
+ * @public
287
+ */
288
+ class GoogleGenerativeAIAbortError extends GoogleGenerativeAIError {
289
+ }
290
+
291
+ /**
292
+ * @license
293
+ * Copyright 2024 Google LLC
294
+ *
295
+ * Licensed under the Apache License, Version 2.0 (the "License");
296
+ * you may not use this file except in compliance with the License.
297
+ * You may obtain a copy of the License at
298
+ *
299
+ * http://www.apache.org/licenses/LICENSE-2.0
300
+ *
301
+ * Unless required by applicable law or agreed to in writing, software
302
+ * distributed under the License is distributed on an "AS IS" BASIS,
303
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
304
+ * See the License for the specific language governing permissions and
305
+ * limitations under the License.
306
+ */
307
+ const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com";
308
+ const DEFAULT_API_VERSION = "v1beta";
309
+ /**
310
+ * We can't `require` package.json if this runs on web. We will use rollup to
311
+ * swap in the version number here at build time.
312
+ */
313
+ const PACKAGE_VERSION = "0.24.1";
314
+ const PACKAGE_LOG_HEADER = "genai-js";
315
+ var Task;
316
+ (function (Task) {
317
+ Task["GENERATE_CONTENT"] = "generateContent";
318
+ Task["STREAM_GENERATE_CONTENT"] = "streamGenerateContent";
319
+ Task["COUNT_TOKENS"] = "countTokens";
320
+ Task["EMBED_CONTENT"] = "embedContent";
321
+ Task["BATCH_EMBED_CONTENTS"] = "batchEmbedContents";
322
+ })(Task || (Task = {}));
323
+ class RequestUrl {
324
+ constructor(model, task, apiKey, stream, requestOptions) {
325
+ this.model = model;
326
+ this.task = task;
327
+ this.apiKey = apiKey;
328
+ this.stream = stream;
329
+ this.requestOptions = requestOptions;
330
+ }
331
+ toString() {
332
+ var _a, _b;
333
+ const apiVersion = ((_a = this.requestOptions) === null || _a === void 0 ? void 0 : _a.apiVersion) || DEFAULT_API_VERSION;
334
+ const baseUrl = ((_b = this.requestOptions) === null || _b === void 0 ? void 0 : _b.baseUrl) || DEFAULT_BASE_URL;
335
+ let url = `${baseUrl}/${apiVersion}/${this.model}:${this.task}`;
336
+ if (this.stream) {
337
+ url += "?alt=sse";
338
+ }
339
+ return url;
340
+ }
341
+ }
342
+ /**
343
+ * Simple, but may become more complex if we add more versions to log.
344
+ */
345
+ function getClientHeaders(requestOptions) {
346
+ const clientHeaders = [];
347
+ if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.apiClient) {
348
+ clientHeaders.push(requestOptions.apiClient);
349
+ }
350
+ clientHeaders.push(`${PACKAGE_LOG_HEADER}/${PACKAGE_VERSION}`);
351
+ return clientHeaders.join(" ");
352
+ }
353
+ async function getHeaders(url) {
354
+ var _a;
355
+ const headers = new Headers();
356
+ headers.append("Content-Type", "application/json");
357
+ headers.append("x-goog-api-client", getClientHeaders(url.requestOptions));
358
+ headers.append("x-goog-api-key", url.apiKey);
359
+ let customHeaders = (_a = url.requestOptions) === null || _a === void 0 ? void 0 : _a.customHeaders;
360
+ if (customHeaders) {
361
+ if (!(customHeaders instanceof Headers)) {
362
+ try {
363
+ customHeaders = new Headers(customHeaders);
364
+ }
365
+ catch (e) {
366
+ throw new GoogleGenerativeAIRequestInputError(`unable to convert customHeaders value ${JSON.stringify(customHeaders)} to Headers: ${e.message}`);
367
+ }
368
+ }
369
+ for (const [headerName, headerValue] of customHeaders.entries()) {
370
+ if (headerName === "x-goog-api-key") {
371
+ throw new GoogleGenerativeAIRequestInputError(`Cannot set reserved header name ${headerName}`);
372
+ }
373
+ else if (headerName === "x-goog-api-client") {
374
+ throw new GoogleGenerativeAIRequestInputError(`Header name ${headerName} can only be set using the apiClient field`);
375
+ }
376
+ headers.append(headerName, headerValue);
377
+ }
378
+ }
379
+ return headers;
380
+ }
381
+ async function constructModelRequest(model, task, apiKey, stream, body, requestOptions) {
382
+ const url = new RequestUrl(model, task, apiKey, stream, requestOptions);
383
+ return {
384
+ url: url.toString(),
385
+ fetchOptions: Object.assign(Object.assign({}, buildFetchOptions(requestOptions)), { method: "POST", headers: await getHeaders(url), body }),
386
+ };
387
+ }
388
+ async function makeModelRequest(model, task, apiKey, stream, body, requestOptions = {},
389
+ // Allows this to be stubbed for tests
390
+ fetchFn = fetch) {
391
+ const { url, fetchOptions } = await constructModelRequest(model, task, apiKey, stream, body, requestOptions);
392
+ return makeRequest(url, fetchOptions, fetchFn);
393
+ }
394
+ async function makeRequest(url, fetchOptions, fetchFn = fetch) {
395
+ let response;
396
+ try {
397
+ response = await fetchFn(url, fetchOptions);
398
+ }
399
+ catch (e) {
400
+ handleResponseError(e, url);
401
+ }
402
+ if (!response.ok) {
403
+ await handleResponseNotOk(response, url);
404
+ }
405
+ return response;
406
+ }
407
+ function handleResponseError(e, url) {
408
+ let err = e;
409
+ if (err.name === "AbortError") {
410
+ err = new GoogleGenerativeAIAbortError(`Request aborted when fetching ${url.toString()}: ${e.message}`);
411
+ err.stack = e.stack;
412
+ }
413
+ else if (!(e instanceof GoogleGenerativeAIFetchError ||
414
+ e instanceof GoogleGenerativeAIRequestInputError)) {
415
+ err = new GoogleGenerativeAIError(`Error fetching from ${url.toString()}: ${e.message}`);
416
+ err.stack = e.stack;
417
+ }
418
+ throw err;
419
+ }
420
+ async function handleResponseNotOk(response, url) {
421
+ let message = "";
422
+ let errorDetails;
423
+ try {
424
+ const json = await response.json();
425
+ message = json.error.message;
426
+ if (json.error.details) {
427
+ message += ` ${JSON.stringify(json.error.details)}`;
428
+ errorDetails = json.error.details;
429
+ }
430
+ }
431
+ catch (e) {
432
+ // ignored
433
+ }
434
+ throw new GoogleGenerativeAIFetchError(`Error fetching from ${url.toString()}: [${response.status} ${response.statusText}] ${message}`, response.status, response.statusText, errorDetails);
435
+ }
436
+ /**
437
+ * Generates the request options to be passed to the fetch API.
438
+ * @param requestOptions - The user-defined request options.
439
+ * @returns The generated request options.
440
+ */
441
+ function buildFetchOptions(requestOptions) {
442
+ const fetchOptions = {};
443
+ if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.signal) !== undefined || (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeout) >= 0) {
444
+ const controller = new AbortController();
445
+ if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeout) >= 0) {
446
+ setTimeout(() => controller.abort(), requestOptions.timeout);
447
+ }
448
+ if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.signal) {
449
+ requestOptions.signal.addEventListener("abort", () => {
450
+ controller.abort();
451
+ });
452
+ }
453
+ fetchOptions.signal = controller.signal;
454
+ }
455
+ return fetchOptions;
456
+ }
457
+
458
+ /**
459
+ * @license
460
+ * Copyright 2024 Google LLC
461
+ *
462
+ * Licensed under the Apache License, Version 2.0 (the "License");
463
+ * you may not use this file except in compliance with the License.
464
+ * You may obtain a copy of the License at
465
+ *
466
+ * http://www.apache.org/licenses/LICENSE-2.0
467
+ *
468
+ * Unless required by applicable law or agreed to in writing, software
469
+ * distributed under the License is distributed on an "AS IS" BASIS,
470
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
471
+ * See the License for the specific language governing permissions and
472
+ * limitations under the License.
473
+ */
474
+ /**
475
+ * Adds convenience helper methods to a response object, including stream
476
+ * chunks (as long as each chunk is a complete GenerateContentResponse JSON).
477
+ */
478
+ function addHelpers(response) {
479
+ response.text = () => {
480
+ if (response.candidates && response.candidates.length > 0) {
481
+ if (response.candidates.length > 1) {
482
+ console.warn(`This response had ${response.candidates.length} ` +
483
+ `candidates. Returning text from the first candidate only. ` +
484
+ `Access response.candidates directly to use the other candidates.`);
485
+ }
486
+ if (hadBadFinishReason(response.candidates[0])) {
487
+ throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response);
488
+ }
489
+ return getText(response);
490
+ }
491
+ else if (response.promptFeedback) {
492
+ throw new GoogleGenerativeAIResponseError(`Text not available. ${formatBlockErrorMessage(response)}`, response);
493
+ }
494
+ return "";
495
+ };
496
+ /**
497
+ * TODO: remove at next major version
498
+ */
499
+ response.functionCall = () => {
500
+ if (response.candidates && response.candidates.length > 0) {
501
+ if (response.candidates.length > 1) {
502
+ console.warn(`This response had ${response.candidates.length} ` +
503
+ `candidates. Returning function calls from the first candidate only. ` +
504
+ `Access response.candidates directly to use the other candidates.`);
505
+ }
506
+ if (hadBadFinishReason(response.candidates[0])) {
507
+ throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response);
508
+ }
509
+ console.warn(`response.functionCall() is deprecated. ` +
510
+ `Use response.functionCalls() instead.`);
511
+ return getFunctionCalls(response)[0];
512
+ }
513
+ else if (response.promptFeedback) {
514
+ throw new GoogleGenerativeAIResponseError(`Function call not available. ${formatBlockErrorMessage(response)}`, response);
515
+ }
516
+ return undefined;
517
+ };
518
+ response.functionCalls = () => {
519
+ if (response.candidates && response.candidates.length > 0) {
520
+ if (response.candidates.length > 1) {
521
+ console.warn(`This response had ${response.candidates.length} ` +
522
+ `candidates. Returning function calls from the first candidate only. ` +
523
+ `Access response.candidates directly to use the other candidates.`);
524
+ }
525
+ if (hadBadFinishReason(response.candidates[0])) {
526
+ throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response);
527
+ }
528
+ return getFunctionCalls(response);
529
+ }
530
+ else if (response.promptFeedback) {
531
+ throw new GoogleGenerativeAIResponseError(`Function call not available. ${formatBlockErrorMessage(response)}`, response);
532
+ }
533
+ return undefined;
534
+ };
535
+ return response;
536
+ }
537
+ /**
538
+ * Returns all text found in all parts of first candidate.
539
+ */
540
+ function getText(response) {
541
+ var _a, _b, _c, _d;
542
+ const textStrings = [];
543
+ if ((_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0].content) === null || _b === void 0 ? void 0 : _b.parts) {
544
+ for (const part of (_d = (_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0].content) === null || _d === void 0 ? void 0 : _d.parts) {
545
+ if (part.text) {
546
+ textStrings.push(part.text);
547
+ }
548
+ if (part.executableCode) {
549
+ textStrings.push("\n```" +
550
+ part.executableCode.language +
551
+ "\n" +
552
+ part.executableCode.code +
553
+ "\n```\n");
554
+ }
555
+ if (part.codeExecutionResult) {
556
+ textStrings.push("\n```\n" + part.codeExecutionResult.output + "\n```\n");
557
+ }
558
+ }
559
+ }
560
+ if (textStrings.length > 0) {
561
+ return textStrings.join("");
562
+ }
563
+ else {
564
+ return "";
565
+ }
566
+ }
567
+ /**
568
+ * Returns functionCall of first candidate.
569
+ */
570
+ function getFunctionCalls(response) {
571
+ var _a, _b, _c, _d;
572
+ const functionCalls = [];
573
+ if ((_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0].content) === null || _b === void 0 ? void 0 : _b.parts) {
574
+ for (const part of (_d = (_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0].content) === null || _d === void 0 ? void 0 : _d.parts) {
575
+ if (part.functionCall) {
576
+ functionCalls.push(part.functionCall);
577
+ }
578
+ }
579
+ }
580
+ if (functionCalls.length > 0) {
581
+ return functionCalls;
582
+ }
583
+ else {
584
+ return undefined;
585
+ }
586
+ }
587
+ const badFinishReasons = [
588
+ exports.FinishReason.RECITATION,
589
+ exports.FinishReason.SAFETY,
590
+ exports.FinishReason.LANGUAGE,
591
+ ];
592
+ function hadBadFinishReason(candidate) {
593
+ return (!!candidate.finishReason &&
594
+ badFinishReasons.includes(candidate.finishReason));
595
+ }
596
+ function formatBlockErrorMessage(response) {
597
+ var _a, _b, _c;
598
+ let message = "";
599
+ if ((!response.candidates || response.candidates.length === 0) &&
600
+ response.promptFeedback) {
601
+ message += "Response was blocked";
602
+ if ((_a = response.promptFeedback) === null || _a === void 0 ? void 0 : _a.blockReason) {
603
+ message += ` due to ${response.promptFeedback.blockReason}`;
604
+ }
605
+ if ((_b = response.promptFeedback) === null || _b === void 0 ? void 0 : _b.blockReasonMessage) {
606
+ message += `: ${response.promptFeedback.blockReasonMessage}`;
607
+ }
608
+ }
609
+ else if ((_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0]) {
610
+ const firstCandidate = response.candidates[0];
611
+ if (hadBadFinishReason(firstCandidate)) {
612
+ message += `Candidate was blocked due to ${firstCandidate.finishReason}`;
613
+ if (firstCandidate.finishMessage) {
614
+ message += `: ${firstCandidate.finishMessage}`;
615
+ }
616
+ }
617
+ }
618
+ return message;
619
+ }
620
+
621
+ /******************************************************************************
622
+ Copyright (c) Microsoft Corporation.
623
+
624
+ Permission to use, copy, modify, and/or distribute this software for any
625
+ purpose with or without fee is hereby granted.
626
+
627
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
628
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
629
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
630
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
631
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
632
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
633
+ PERFORMANCE OF THIS SOFTWARE.
634
+ ***************************************************************************** */
635
+ /* global Reflect, Promise, SuppressedError, Symbol */
636
+
637
+
638
+ function __await(v) {
639
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
640
+ }
641
+
642
+ function __asyncGenerator(thisArg, _arguments, generator) {
643
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
644
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
645
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
646
+ function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
647
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
648
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
649
+ function fulfill(value) { resume("next", value); }
650
+ function reject(value) { resume("throw", value); }
651
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
652
+ }
653
+
654
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
655
+ var e = new Error(message);
656
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
657
+ };
658
+
659
+ /**
660
+ * @license
661
+ * Copyright 2024 Google LLC
662
+ *
663
+ * Licensed under the Apache License, Version 2.0 (the "License");
664
+ * you may not use this file except in compliance with the License.
665
+ * You may obtain a copy of the License at
666
+ *
667
+ * http://www.apache.org/licenses/LICENSE-2.0
668
+ *
669
+ * Unless required by applicable law or agreed to in writing, software
670
+ * distributed under the License is distributed on an "AS IS" BASIS,
671
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
672
+ * See the License for the specific language governing permissions and
673
+ * limitations under the License.
674
+ */
675
+ const responseLineRE = /^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;
676
+ /**
677
+ * Process a response.body stream from the backend and return an
678
+ * iterator that provides one complete GenerateContentResponse at a time
679
+ * and a promise that resolves with a single aggregated
680
+ * GenerateContentResponse.
681
+ *
682
+ * @param response - Response from a fetch call
683
+ */
684
+ function processStream(response) {
685
+ const inputStream = response.body.pipeThrough(new TextDecoderStream("utf8", { fatal: true }));
686
+ const responseStream = getResponseStream(inputStream);
687
+ const [stream1, stream2] = responseStream.tee();
688
+ return {
689
+ stream: generateResponseSequence(stream1),
690
+ response: getResponsePromise(stream2),
691
+ };
692
+ }
693
+ async function getResponsePromise(stream) {
694
+ const allResponses = [];
695
+ const reader = stream.getReader();
696
+ while (true) {
697
+ const { done, value } = await reader.read();
698
+ if (done) {
699
+ return addHelpers(aggregateResponses(allResponses));
700
+ }
701
+ allResponses.push(value);
702
+ }
703
+ }
704
+ function generateResponseSequence(stream) {
705
+ return __asyncGenerator(this, arguments, function* generateResponseSequence_1() {
706
+ const reader = stream.getReader();
707
+ while (true) {
708
+ const { value, done } = yield __await(reader.read());
709
+ if (done) {
710
+ break;
711
+ }
712
+ yield yield __await(addHelpers(value));
713
+ }
714
+ });
715
+ }
716
+ /**
717
+ * Reads a raw stream from the fetch response and join incomplete
718
+ * chunks, returning a new stream that provides a single complete
719
+ * GenerateContentResponse in each iteration.
720
+ */
721
+ function getResponseStream(inputStream) {
722
+ const reader = inputStream.getReader();
723
+ const stream = new ReadableStream({
724
+ start(controller) {
725
+ let currentText = "";
726
+ return pump();
727
+ function pump() {
728
+ return reader
729
+ .read()
730
+ .then(({ value, done }) => {
731
+ if (done) {
732
+ if (currentText.trim()) {
733
+ controller.error(new GoogleGenerativeAIError("Failed to parse stream"));
734
+ return;
735
+ }
736
+ controller.close();
737
+ return;
738
+ }
739
+ currentText += value;
740
+ let match = currentText.match(responseLineRE);
741
+ let parsedResponse;
742
+ while (match) {
743
+ try {
744
+ parsedResponse = JSON.parse(match[1]);
745
+ }
746
+ catch (e) {
747
+ controller.error(new GoogleGenerativeAIError(`Error parsing JSON response: "${match[1]}"`));
748
+ return;
749
+ }
750
+ controller.enqueue(parsedResponse);
751
+ currentText = currentText.substring(match[0].length);
752
+ match = currentText.match(responseLineRE);
753
+ }
754
+ return pump();
755
+ })
756
+ .catch((e) => {
757
+ let err = e;
758
+ err.stack = e.stack;
759
+ if (err.name === "AbortError") {
760
+ err = new GoogleGenerativeAIAbortError("Request aborted when reading from the stream");
761
+ }
762
+ else {
763
+ err = new GoogleGenerativeAIError("Error reading from the stream");
764
+ }
765
+ throw err;
766
+ });
767
+ }
768
+ },
769
+ });
770
+ return stream;
771
+ }
772
+ /**
773
+ * Aggregates an array of `GenerateContentResponse`s into a single
774
+ * GenerateContentResponse.
775
+ */
776
+ function aggregateResponses(responses) {
777
+ const lastResponse = responses[responses.length - 1];
778
+ const aggregatedResponse = {
779
+ promptFeedback: lastResponse === null || lastResponse === void 0 ? void 0 : lastResponse.promptFeedback,
780
+ };
781
+ for (const response of responses) {
782
+ if (response.candidates) {
783
+ let candidateIndex = 0;
784
+ for (const candidate of response.candidates) {
785
+ if (!aggregatedResponse.candidates) {
786
+ aggregatedResponse.candidates = [];
787
+ }
788
+ if (!aggregatedResponse.candidates[candidateIndex]) {
789
+ aggregatedResponse.candidates[candidateIndex] = {
790
+ index: candidateIndex,
791
+ };
792
+ }
793
+ // Keep overwriting, the last one will be final
794
+ aggregatedResponse.candidates[candidateIndex].citationMetadata =
795
+ candidate.citationMetadata;
796
+ aggregatedResponse.candidates[candidateIndex].groundingMetadata =
797
+ candidate.groundingMetadata;
798
+ aggregatedResponse.candidates[candidateIndex].finishReason =
799
+ candidate.finishReason;
800
+ aggregatedResponse.candidates[candidateIndex].finishMessage =
801
+ candidate.finishMessage;
802
+ aggregatedResponse.candidates[candidateIndex].safetyRatings =
803
+ candidate.safetyRatings;
804
+ /**
805
+ * Candidates should always have content and parts, but this handles
806
+ * possible malformed responses.
807
+ */
808
+ if (candidate.content && candidate.content.parts) {
809
+ if (!aggregatedResponse.candidates[candidateIndex].content) {
810
+ aggregatedResponse.candidates[candidateIndex].content = {
811
+ role: candidate.content.role || "user",
812
+ parts: [],
813
+ };
814
+ }
815
+ const newPart = {};
816
+ for (const part of candidate.content.parts) {
817
+ if (part.text) {
818
+ newPart.text = part.text;
819
+ }
820
+ if (part.functionCall) {
821
+ newPart.functionCall = part.functionCall;
822
+ }
823
+ if (part.executableCode) {
824
+ newPart.executableCode = part.executableCode;
825
+ }
826
+ if (part.codeExecutionResult) {
827
+ newPart.codeExecutionResult = part.codeExecutionResult;
828
+ }
829
+ if (Object.keys(newPart).length === 0) {
830
+ newPart.text = "";
831
+ }
832
+ aggregatedResponse.candidates[candidateIndex].content.parts.push(newPart);
833
+ }
834
+ }
835
+ }
836
+ candidateIndex++;
837
+ }
838
+ if (response.usageMetadata) {
839
+ aggregatedResponse.usageMetadata = response.usageMetadata;
840
+ }
841
+ }
842
+ return aggregatedResponse;
843
+ }
844
+
845
+ /**
846
+ * @license
847
+ * Copyright 2024 Google LLC
848
+ *
849
+ * Licensed under the Apache License, Version 2.0 (the "License");
850
+ * you may not use this file except in compliance with the License.
851
+ * You may obtain a copy of the License at
852
+ *
853
+ * http://www.apache.org/licenses/LICENSE-2.0
854
+ *
855
+ * Unless required by applicable law or agreed to in writing, software
856
+ * distributed under the License is distributed on an "AS IS" BASIS,
857
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
858
+ * See the License for the specific language governing permissions and
859
+ * limitations under the License.
860
+ */
861
+ async function generateContentStream(apiKey, model, params, requestOptions) {
862
+ const response = await makeModelRequest(model, Task.STREAM_GENERATE_CONTENT, apiKey,
863
+ /* stream */ true, JSON.stringify(params), requestOptions);
864
+ return processStream(response);
865
+ }
866
+ async function generateContent(apiKey, model, params, requestOptions) {
867
+ const response = await makeModelRequest(model, Task.GENERATE_CONTENT, apiKey,
868
+ /* stream */ false, JSON.stringify(params), requestOptions);
869
+ const responseJson = await response.json();
870
+ const enhancedResponse = addHelpers(responseJson);
871
+ return {
872
+ response: enhancedResponse,
873
+ };
874
+ }
875
+
876
+ /**
877
+ * @license
878
+ * Copyright 2024 Google LLC
879
+ *
880
+ * Licensed under the Apache License, Version 2.0 (the "License");
881
+ * you may not use this file except in compliance with the License.
882
+ * You may obtain a copy of the License at
883
+ *
884
+ * http://www.apache.org/licenses/LICENSE-2.0
885
+ *
886
+ * Unless required by applicable law or agreed to in writing, software
887
+ * distributed under the License is distributed on an "AS IS" BASIS,
888
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
889
+ * See the License for the specific language governing permissions and
890
+ * limitations under the License.
891
+ */
892
+ function formatSystemInstruction(input) {
893
+ // null or undefined
894
+ if (input == null) {
895
+ return undefined;
896
+ }
897
+ else if (typeof input === "string") {
898
+ return { role: "system", parts: [{ text: input }] };
899
+ }
900
+ else if (input.text) {
901
+ return { role: "system", parts: [input] };
902
+ }
903
+ else if (input.parts) {
904
+ if (!input.role) {
905
+ return { role: "system", parts: input.parts };
906
+ }
907
+ else {
908
+ return input;
909
+ }
910
+ }
911
+ }
912
+ function formatNewContent(request) {
913
+ let newParts = [];
914
+ if (typeof request === "string") {
915
+ newParts = [{ text: request }];
916
+ }
917
+ else {
918
+ for (const partOrString of request) {
919
+ if (typeof partOrString === "string") {
920
+ newParts.push({ text: partOrString });
921
+ }
922
+ else {
923
+ newParts.push(partOrString);
924
+ }
925
+ }
926
+ }
927
+ return assignRoleToPartsAndValidateSendMessageRequest(newParts);
928
+ }
929
+ /**
930
+ * When multiple Part types (i.e. FunctionResponsePart and TextPart) are
931
+ * passed in a single Part array, we may need to assign different roles to each
932
+ * part. Currently only FunctionResponsePart requires a role other than 'user'.
933
+ * @private
934
+ * @param parts Array of parts to pass to the model
935
+ * @returns Array of content items
936
+ */
937
+ function assignRoleToPartsAndValidateSendMessageRequest(parts) {
938
+ const userContent = { role: "user", parts: [] };
939
+ const functionContent = { role: "function", parts: [] };
940
+ let hasUserContent = false;
941
+ let hasFunctionContent = false;
942
+ for (const part of parts) {
943
+ if ("functionResponse" in part) {
944
+ functionContent.parts.push(part);
945
+ hasFunctionContent = true;
946
+ }
947
+ else {
948
+ userContent.parts.push(part);
949
+ hasUserContent = true;
950
+ }
951
+ }
952
+ if (hasUserContent && hasFunctionContent) {
953
+ throw new GoogleGenerativeAIError("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");
954
+ }
955
+ if (!hasUserContent && !hasFunctionContent) {
956
+ throw new GoogleGenerativeAIError("No content is provided for sending chat message.");
957
+ }
958
+ if (hasUserContent) {
959
+ return userContent;
960
+ }
961
+ return functionContent;
962
+ }
963
+ function formatCountTokensInput(params, modelParams) {
964
+ var _a;
965
+ let formattedGenerateContentRequest = {
966
+ model: modelParams === null || modelParams === void 0 ? void 0 : modelParams.model,
967
+ generationConfig: modelParams === null || modelParams === void 0 ? void 0 : modelParams.generationConfig,
968
+ safetySettings: modelParams === null || modelParams === void 0 ? void 0 : modelParams.safetySettings,
969
+ tools: modelParams === null || modelParams === void 0 ? void 0 : modelParams.tools,
970
+ toolConfig: modelParams === null || modelParams === void 0 ? void 0 : modelParams.toolConfig,
971
+ systemInstruction: modelParams === null || modelParams === void 0 ? void 0 : modelParams.systemInstruction,
972
+ cachedContent: (_a = modelParams === null || modelParams === void 0 ? void 0 : modelParams.cachedContent) === null || _a === void 0 ? void 0 : _a.name,
973
+ contents: [],
974
+ };
975
+ const containsGenerateContentRequest = params.generateContentRequest != null;
976
+ if (params.contents) {
977
+ if (containsGenerateContentRequest) {
978
+ throw new GoogleGenerativeAIRequestInputError("CountTokensRequest must have one of contents or generateContentRequest, not both.");
979
+ }
980
+ formattedGenerateContentRequest.contents = params.contents;
981
+ }
982
+ else if (containsGenerateContentRequest) {
983
+ formattedGenerateContentRequest = Object.assign(Object.assign({}, formattedGenerateContentRequest), params.generateContentRequest);
984
+ }
985
+ else {
986
+ // Array or string
987
+ const content = formatNewContent(params);
988
+ formattedGenerateContentRequest.contents = [content];
989
+ }
990
+ return { generateContentRequest: formattedGenerateContentRequest };
991
+ }
992
+ function formatGenerateContentInput(params) {
993
+ let formattedRequest;
994
+ if (params.contents) {
995
+ formattedRequest = params;
996
+ }
997
+ else {
998
+ // Array or string
999
+ const content = formatNewContent(params);
1000
+ formattedRequest = { contents: [content] };
1001
+ }
1002
+ if (params.systemInstruction) {
1003
+ formattedRequest.systemInstruction = formatSystemInstruction(params.systemInstruction);
1004
+ }
1005
+ return formattedRequest;
1006
+ }
1007
+ function formatEmbedContentInput(params) {
1008
+ if (typeof params === "string" || Array.isArray(params)) {
1009
+ const content = formatNewContent(params);
1010
+ return { content };
1011
+ }
1012
+ return params;
1013
+ }
1014
+
1015
+ /**
1016
+ * @license
1017
+ * Copyright 2024 Google LLC
1018
+ *
1019
+ * Licensed under the Apache License, Version 2.0 (the "License");
1020
+ * you may not use this file except in compliance with the License.
1021
+ * You may obtain a copy of the License at
1022
+ *
1023
+ * http://www.apache.org/licenses/LICENSE-2.0
1024
+ *
1025
+ * Unless required by applicable law or agreed to in writing, software
1026
+ * distributed under the License is distributed on an "AS IS" BASIS,
1027
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1028
+ * See the License for the specific language governing permissions and
1029
+ * limitations under the License.
1030
+ */
1031
+ // https://ai.google.dev/api/rest/v1beta/Content#part
1032
+ const VALID_PART_FIELDS = [
1033
+ "text",
1034
+ "inlineData",
1035
+ "functionCall",
1036
+ "functionResponse",
1037
+ "executableCode",
1038
+ "codeExecutionResult",
1039
+ ];
1040
+ const VALID_PARTS_PER_ROLE = {
1041
+ user: ["text", "inlineData"],
1042
+ function: ["functionResponse"],
1043
+ model: ["text", "functionCall", "executableCode", "codeExecutionResult"],
1044
+ // System instructions shouldn't be in history anyway.
1045
+ system: ["text"],
1046
+ };
1047
+ function validateChatHistory(history) {
1048
+ let prevContent = false;
1049
+ for (const currContent of history) {
1050
+ const { role, parts } = currContent;
1051
+ if (!prevContent && role !== "user") {
1052
+ throw new GoogleGenerativeAIError(`First content should be with role 'user', got ${role}`);
1053
+ }
1054
+ if (!POSSIBLE_ROLES.includes(role)) {
1055
+ throw new GoogleGenerativeAIError(`Each item should include role field. Got ${role} but valid roles are: ${JSON.stringify(POSSIBLE_ROLES)}`);
1056
+ }
1057
+ if (!Array.isArray(parts)) {
1058
+ throw new GoogleGenerativeAIError("Content should have 'parts' property with an array of Parts");
1059
+ }
1060
+ if (parts.length === 0) {
1061
+ throw new GoogleGenerativeAIError("Each Content should have at least one part");
1062
+ }
1063
+ const countFields = {
1064
+ text: 0,
1065
+ inlineData: 0,
1066
+ functionCall: 0,
1067
+ functionResponse: 0,
1068
+ fileData: 0,
1069
+ executableCode: 0,
1070
+ codeExecutionResult: 0,
1071
+ };
1072
+ for (const part of parts) {
1073
+ for (const key of VALID_PART_FIELDS) {
1074
+ if (key in part) {
1075
+ countFields[key] += 1;
1076
+ }
1077
+ }
1078
+ }
1079
+ const validParts = VALID_PARTS_PER_ROLE[role];
1080
+ for (const key of VALID_PART_FIELDS) {
1081
+ if (!validParts.includes(key) && countFields[key] > 0) {
1082
+ throw new GoogleGenerativeAIError(`Content with role '${role}' can't contain '${key}' part`);
1083
+ }
1084
+ }
1085
+ prevContent = true;
1086
+ }
1087
+ }
1088
+ /**
1089
+ * Returns true if the response is valid (could be appended to the history), flase otherwise.
1090
+ */
1091
+ function isValidResponse(response) {
1092
+ var _a;
1093
+ if (response.candidates === undefined || response.candidates.length === 0) {
1094
+ return false;
1095
+ }
1096
+ const content = (_a = response.candidates[0]) === null || _a === void 0 ? void 0 : _a.content;
1097
+ if (content === undefined) {
1098
+ return false;
1099
+ }
1100
+ if (content.parts === undefined || content.parts.length === 0) {
1101
+ return false;
1102
+ }
1103
+ for (const part of content.parts) {
1104
+ if (part === undefined || Object.keys(part).length === 0) {
1105
+ return false;
1106
+ }
1107
+ if (part.text !== undefined && part.text === "") {
1108
+ return false;
1109
+ }
1110
+ }
1111
+ return true;
1112
+ }
1113
+
1114
+ /**
1115
+ * @license
1116
+ * Copyright 2024 Google LLC
1117
+ *
1118
+ * Licensed under the Apache License, Version 2.0 (the "License");
1119
+ * you may not use this file except in compliance with the License.
1120
+ * You may obtain a copy of the License at
1121
+ *
1122
+ * http://www.apache.org/licenses/LICENSE-2.0
1123
+ *
1124
+ * Unless required by applicable law or agreed to in writing, software
1125
+ * distributed under the License is distributed on an "AS IS" BASIS,
1126
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1127
+ * See the License for the specific language governing permissions and
1128
+ * limitations under the License.
1129
+ */
1130
+ /**
1131
+ * Do not log a message for this error.
1132
+ */
1133
+ const SILENT_ERROR = "SILENT_ERROR";
1134
+ /**
1135
+ * ChatSession class that enables sending chat messages and stores
1136
+ * history of sent and received messages so far.
1137
+ *
1138
+ * @public
1139
+ */
1140
+ class ChatSession {
1141
+ constructor(apiKey, model, params, _requestOptions = {}) {
1142
+ this.model = model;
1143
+ this.params = params;
1144
+ this._requestOptions = _requestOptions;
1145
+ this._history = [];
1146
+ this._sendPromise = Promise.resolve();
1147
+ this._apiKey = apiKey;
1148
+ if (params === null || params === void 0 ? void 0 : params.history) {
1149
+ validateChatHistory(params.history);
1150
+ this._history = params.history;
1151
+ }
1152
+ }
1153
+ /**
1154
+ * Gets the chat history so far. Blocked prompts are not added to history.
1155
+ * Blocked candidates are not added to history, nor are the prompts that
1156
+ * generated them.
1157
+ */
1158
+ async getHistory() {
1159
+ await this._sendPromise;
1160
+ return this._history;
1161
+ }
1162
+ /**
1163
+ * Sends a chat message and receives a non-streaming
1164
+ * {@link GenerateContentResult}.
1165
+ *
1166
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
1167
+ * take precedence over the {@link RequestOptions} values provided to
1168
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
1169
+ */
1170
+ async sendMessage(request, requestOptions = {}) {
1171
+ var _a, _b, _c, _d, _e, _f;
1172
+ await this._sendPromise;
1173
+ const newContent = formatNewContent(request);
1174
+ const generateContentRequest = {
1175
+ safetySettings: (_a = this.params) === null || _a === void 0 ? void 0 : _a.safetySettings,
1176
+ generationConfig: (_b = this.params) === null || _b === void 0 ? void 0 : _b.generationConfig,
1177
+ tools: (_c = this.params) === null || _c === void 0 ? void 0 : _c.tools,
1178
+ toolConfig: (_d = this.params) === null || _d === void 0 ? void 0 : _d.toolConfig,
1179
+ systemInstruction: (_e = this.params) === null || _e === void 0 ? void 0 : _e.systemInstruction,
1180
+ cachedContent: (_f = this.params) === null || _f === void 0 ? void 0 : _f.cachedContent,
1181
+ contents: [...this._history, newContent],
1182
+ };
1183
+ const chatSessionRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
1184
+ let finalResult;
1185
+ // Add onto the chain.
1186
+ this._sendPromise = this._sendPromise
1187
+ .then(() => generateContent(this._apiKey, this.model, generateContentRequest, chatSessionRequestOptions))
1188
+ .then((result) => {
1189
+ var _a;
1190
+ if (isValidResponse(result.response)) {
1191
+ this._history.push(newContent);
1192
+ const responseContent = Object.assign({ parts: [],
1193
+ // Response seems to come back without a role set.
1194
+ role: "model" }, (_a = result.response.candidates) === null || _a === void 0 ? void 0 : _a[0].content);
1195
+ this._history.push(responseContent);
1196
+ }
1197
+ else {
1198
+ const blockErrorMessage = formatBlockErrorMessage(result.response);
1199
+ if (blockErrorMessage) {
1200
+ console.warn(`sendMessage() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`);
1201
+ }
1202
+ }
1203
+ finalResult = result;
1204
+ })
1205
+ .catch((e) => {
1206
+ // Resets _sendPromise to avoid subsequent calls failing and throw error.
1207
+ this._sendPromise = Promise.resolve();
1208
+ throw e;
1209
+ });
1210
+ await this._sendPromise;
1211
+ return finalResult;
1212
+ }
1213
+ /**
1214
+ * Sends a chat message and receives the response as a
1215
+ * {@link GenerateContentStreamResult} containing an iterable stream
1216
+ * and a response promise.
1217
+ *
1218
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
1219
+ * take precedence over the {@link RequestOptions} values provided to
1220
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
1221
+ */
1222
+ async sendMessageStream(request, requestOptions = {}) {
1223
+ var _a, _b, _c, _d, _e, _f;
1224
+ await this._sendPromise;
1225
+ const newContent = formatNewContent(request);
1226
+ const generateContentRequest = {
1227
+ safetySettings: (_a = this.params) === null || _a === void 0 ? void 0 : _a.safetySettings,
1228
+ generationConfig: (_b = this.params) === null || _b === void 0 ? void 0 : _b.generationConfig,
1229
+ tools: (_c = this.params) === null || _c === void 0 ? void 0 : _c.tools,
1230
+ toolConfig: (_d = this.params) === null || _d === void 0 ? void 0 : _d.toolConfig,
1231
+ systemInstruction: (_e = this.params) === null || _e === void 0 ? void 0 : _e.systemInstruction,
1232
+ cachedContent: (_f = this.params) === null || _f === void 0 ? void 0 : _f.cachedContent,
1233
+ contents: [...this._history, newContent],
1234
+ };
1235
+ const chatSessionRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
1236
+ const streamPromise = generateContentStream(this._apiKey, this.model, generateContentRequest, chatSessionRequestOptions);
1237
+ // Add onto the chain.
1238
+ this._sendPromise = this._sendPromise
1239
+ .then(() => streamPromise)
1240
+ // This must be handled to avoid unhandled rejection, but jump
1241
+ // to the final catch block with a label to not log this error.
1242
+ .catch((_ignored) => {
1243
+ throw new Error(SILENT_ERROR);
1244
+ })
1245
+ .then((streamResult) => streamResult.response)
1246
+ .then((response) => {
1247
+ if (isValidResponse(response)) {
1248
+ this._history.push(newContent);
1249
+ const responseContent = Object.assign({}, response.candidates[0].content);
1250
+ // Response seems to come back without a role set.
1251
+ if (!responseContent.role) {
1252
+ responseContent.role = "model";
1253
+ }
1254
+ this._history.push(responseContent);
1255
+ }
1256
+ else {
1257
+ const blockErrorMessage = formatBlockErrorMessage(response);
1258
+ if (blockErrorMessage) {
1259
+ console.warn(`sendMessageStream() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`);
1260
+ }
1261
+ }
1262
+ })
1263
+ .catch((e) => {
1264
+ // Errors in streamPromise are already catchable by the user as
1265
+ // streamPromise is returned.
1266
+ // Avoid duplicating the error message in logs.
1267
+ if (e.message !== SILENT_ERROR) {
1268
+ // Users do not have access to _sendPromise to catch errors
1269
+ // downstream from streamPromise, so they should not throw.
1270
+ console.error(e);
1271
+ }
1272
+ });
1273
+ return streamPromise;
1274
+ }
1275
+ }
1276
+
1277
+ /**
1278
+ * @license
1279
+ * Copyright 2024 Google LLC
1280
+ *
1281
+ * Licensed under the Apache License, Version 2.0 (the "License");
1282
+ * you may not use this file except in compliance with the License.
1283
+ * You may obtain a copy of the License at
1284
+ *
1285
+ * http://www.apache.org/licenses/LICENSE-2.0
1286
+ *
1287
+ * Unless required by applicable law or agreed to in writing, software
1288
+ * distributed under the License is distributed on an "AS IS" BASIS,
1289
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1290
+ * See the License for the specific language governing permissions and
1291
+ * limitations under the License.
1292
+ */
1293
+ async function countTokens(apiKey, model, params, singleRequestOptions) {
1294
+ const response = await makeModelRequest(model, Task.COUNT_TOKENS, apiKey, false, JSON.stringify(params), singleRequestOptions);
1295
+ return response.json();
1296
+ }
1297
+
1298
+ /**
1299
+ * @license
1300
+ * Copyright 2024 Google LLC
1301
+ *
1302
+ * Licensed under the Apache License, Version 2.0 (the "License");
1303
+ * you may not use this file except in compliance with the License.
1304
+ * You may obtain a copy of the License at
1305
+ *
1306
+ * http://www.apache.org/licenses/LICENSE-2.0
1307
+ *
1308
+ * Unless required by applicable law or agreed to in writing, software
1309
+ * distributed under the License is distributed on an "AS IS" BASIS,
1310
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1311
+ * See the License for the specific language governing permissions and
1312
+ * limitations under the License.
1313
+ */
1314
+ async function embedContent(apiKey, model, params, requestOptions) {
1315
+ const response = await makeModelRequest(model, Task.EMBED_CONTENT, apiKey, false, JSON.stringify(params), requestOptions);
1316
+ return response.json();
1317
+ }
1318
+ async function batchEmbedContents(apiKey, model, params, requestOptions) {
1319
+ const requestsWithModel = params.requests.map((request) => {
1320
+ return Object.assign(Object.assign({}, request), { model });
1321
+ });
1322
+ const response = await makeModelRequest(model, Task.BATCH_EMBED_CONTENTS, apiKey, false, JSON.stringify({ requests: requestsWithModel }), requestOptions);
1323
+ return response.json();
1324
+ }
1325
+
1326
+ /**
1327
+ * @license
1328
+ * Copyright 2024 Google LLC
1329
+ *
1330
+ * Licensed under the Apache License, Version 2.0 (the "License");
1331
+ * you may not use this file except in compliance with the License.
1332
+ * You may obtain a copy of the License at
1333
+ *
1334
+ * http://www.apache.org/licenses/LICENSE-2.0
1335
+ *
1336
+ * Unless required by applicable law or agreed to in writing, software
1337
+ * distributed under the License is distributed on an "AS IS" BASIS,
1338
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1339
+ * See the License for the specific language governing permissions and
1340
+ * limitations under the License.
1341
+ */
1342
+ /**
1343
+ * Class for generative model APIs.
1344
+ * @public
1345
+ */
1346
+ class GenerativeModel {
1347
+ constructor(apiKey, modelParams, _requestOptions = {}) {
1348
+ this.apiKey = apiKey;
1349
+ this._requestOptions = _requestOptions;
1350
+ if (modelParams.model.includes("/")) {
1351
+ // Models may be named "models/model-name" or "tunedModels/model-name"
1352
+ this.model = modelParams.model;
1353
+ }
1354
+ else {
1355
+ // If path is not included, assume it's a non-tuned model.
1356
+ this.model = `models/${modelParams.model}`;
1357
+ }
1358
+ this.generationConfig = modelParams.generationConfig || {};
1359
+ this.safetySettings = modelParams.safetySettings || [];
1360
+ this.tools = modelParams.tools;
1361
+ this.toolConfig = modelParams.toolConfig;
1362
+ this.systemInstruction = formatSystemInstruction(modelParams.systemInstruction);
1363
+ this.cachedContent = modelParams.cachedContent;
1364
+ }
1365
+ /**
1366
+ * Makes a single non-streaming call to the model
1367
+ * and returns an object containing a single {@link GenerateContentResponse}.
1368
+ *
1369
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
1370
+ * take precedence over the {@link RequestOptions} values provided to
1371
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
1372
+ */
1373
+ async generateContent(request, requestOptions = {}) {
1374
+ var _a;
1375
+ const formattedParams = formatGenerateContentInput(request);
1376
+ const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
1377
+ return generateContent(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a = this.cachedContent) === null || _a === void 0 ? void 0 : _a.name }, formattedParams), generativeModelRequestOptions);
1378
+ }
1379
+ /**
1380
+ * Makes a single streaming call to the model and returns an object
1381
+ * containing an iterable stream that iterates over all chunks in the
1382
+ * streaming response as well as a promise that returns the final
1383
+ * aggregated response.
1384
+ *
1385
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
1386
+ * take precedence over the {@link RequestOptions} values provided to
1387
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
1388
+ */
1389
+ async generateContentStream(request, requestOptions = {}) {
1390
+ var _a;
1391
+ const formattedParams = formatGenerateContentInput(request);
1392
+ const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
1393
+ return generateContentStream(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a = this.cachedContent) === null || _a === void 0 ? void 0 : _a.name }, formattedParams), generativeModelRequestOptions);
1394
+ }
1395
+ /**
1396
+ * Gets a new {@link ChatSession} instance which can be used for
1397
+ * multi-turn chats.
1398
+ */
1399
+ startChat(startChatParams) {
1400
+ var _a;
1401
+ return new ChatSession(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a = this.cachedContent) === null || _a === void 0 ? void 0 : _a.name }, startChatParams), this._requestOptions);
1402
+ }
1403
+ /**
1404
+ * Counts the tokens in the provided request.
1405
+ *
1406
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
1407
+ * take precedence over the {@link RequestOptions} values provided to
1408
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
1409
+ */
1410
+ async countTokens(request, requestOptions = {}) {
1411
+ const formattedParams = formatCountTokensInput(request, {
1412
+ model: this.model,
1413
+ generationConfig: this.generationConfig,
1414
+ safetySettings: this.safetySettings,
1415
+ tools: this.tools,
1416
+ toolConfig: this.toolConfig,
1417
+ systemInstruction: this.systemInstruction,
1418
+ cachedContent: this.cachedContent,
1419
+ });
1420
+ const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
1421
+ return countTokens(this.apiKey, this.model, formattedParams, generativeModelRequestOptions);
1422
+ }
1423
+ /**
1424
+ * Embeds the provided content.
1425
+ *
1426
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
1427
+ * take precedence over the {@link RequestOptions} values provided to
1428
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
1429
+ */
1430
+ async embedContent(request, requestOptions = {}) {
1431
+ const formattedParams = formatEmbedContentInput(request);
1432
+ const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
1433
+ return embedContent(this.apiKey, this.model, formattedParams, generativeModelRequestOptions);
1434
+ }
1435
+ /**
1436
+ * Embeds an array of {@link EmbedContentRequest}s.
1437
+ *
1438
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
1439
+ * take precedence over the {@link RequestOptions} values provided to
1440
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
1441
+ */
1442
+ async batchEmbedContents(batchEmbedContentRequest, requestOptions = {}) {
1443
+ const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
1444
+ return batchEmbedContents(this.apiKey, this.model, batchEmbedContentRequest, generativeModelRequestOptions);
1445
+ }
1446
+ }
1447
+
1448
+ /**
1449
+ * @license
1450
+ * Copyright 2024 Google LLC
1451
+ *
1452
+ * Licensed under the Apache License, Version 2.0 (the "License");
1453
+ * you may not use this file except in compliance with the License.
1454
+ * You may obtain a copy of the License at
1455
+ *
1456
+ * http://www.apache.org/licenses/LICENSE-2.0
1457
+ *
1458
+ * Unless required by applicable law or agreed to in writing, software
1459
+ * distributed under the License is distributed on an "AS IS" BASIS,
1460
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1461
+ * See the License for the specific language governing permissions and
1462
+ * limitations under the License.
1463
+ */
1464
+ /**
1465
+ * Top-level class for this SDK
1466
+ * @public
1467
+ */
1468
+ class GoogleGenerativeAI {
1469
+ constructor(apiKey) {
1470
+ this.apiKey = apiKey;
1471
+ }
1472
+ /**
1473
+ * Gets a {@link GenerativeModel} instance for the provided model name.
1474
+ */
1475
+ getGenerativeModel(modelParams, requestOptions) {
1476
+ if (!modelParams.model) {
1477
+ throw new GoogleGenerativeAIError(`Must provide a model name. ` +
1478
+ `Example: genai.getGenerativeModel({ model: 'my-model-name' })`);
1479
+ }
1480
+ return new GenerativeModel(this.apiKey, modelParams, requestOptions);
1481
+ }
1482
+ /**
1483
+ * Creates a {@link GenerativeModel} instance from provided content cache.
1484
+ */
1485
+ getGenerativeModelFromCachedContent(cachedContent, modelParams, requestOptions) {
1486
+ if (!cachedContent.name) {
1487
+ throw new GoogleGenerativeAIRequestInputError("Cached content must contain a `name` field.");
1488
+ }
1489
+ if (!cachedContent.model) {
1490
+ throw new GoogleGenerativeAIRequestInputError("Cached content must contain a `model` field.");
1491
+ }
1492
+ /**
1493
+ * Not checking tools and toolConfig for now as it would require a deep
1494
+ * equality comparison and isn't likely to be a common case.
1495
+ */
1496
+ const disallowedDuplicates = ["model", "systemInstruction"];
1497
+ for (const key of disallowedDuplicates) {
1498
+ if ((modelParams === null || modelParams === void 0 ? void 0 : modelParams[key]) &&
1499
+ cachedContent[key] &&
1500
+ (modelParams === null || modelParams === void 0 ? void 0 : modelParams[key]) !== cachedContent[key]) {
1501
+ if (key === "model") {
1502
+ const modelParamsComp = modelParams.model.startsWith("models/")
1503
+ ? modelParams.model.replace("models/", "")
1504
+ : modelParams.model;
1505
+ const cachedContentComp = cachedContent.model.startsWith("models/")
1506
+ ? cachedContent.model.replace("models/", "")
1507
+ : cachedContent.model;
1508
+ if (modelParamsComp === cachedContentComp) {
1509
+ continue;
1510
+ }
1511
+ }
1512
+ throw new GoogleGenerativeAIRequestInputError(`Different value for "${key}" specified in modelParams` +
1513
+ ` (${modelParams[key]}) and cachedContent (${cachedContent[key]})`);
1514
+ }
1515
+ }
1516
+ const modelParamsFromCache = Object.assign(Object.assign({}, modelParams), { model: cachedContent.model, tools: cachedContent.tools, toolConfig: cachedContent.toolConfig, systemInstruction: cachedContent.systemInstruction, cachedContent });
1517
+ return new GenerativeModel(this.apiKey, modelParamsFromCache, requestOptions);
1518
+ }
1519
+ }
1520
+
1521
+ exports.ChatSession = ChatSession;
1522
+ exports.GenerativeModel = GenerativeModel;
1523
+ exports.GoogleGenerativeAI = GoogleGenerativeAI;
1524
+ exports.GoogleGenerativeAIAbortError = GoogleGenerativeAIAbortError;
1525
+ exports.GoogleGenerativeAIError = GoogleGenerativeAIError;
1526
+ exports.GoogleGenerativeAIFetchError = GoogleGenerativeAIFetchError;
1527
+ exports.GoogleGenerativeAIRequestInputError = GoogleGenerativeAIRequestInputError;
1528
+ exports.GoogleGenerativeAIResponseError = GoogleGenerativeAIResponseError;
1529
+ exports.POSSIBLE_ROLES = POSSIBLE_ROLES;
1530
+ //# sourceMappingURL=index.js.map
backend-old/node_modules/@google/generative-ai/dist/index.js.map ADDED
@@ -0,0 +1 @@
 
 
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
backend-old/node_modules/@google/generative-ai/dist/index.mjs ADDED
@@ -0,0 +1,1520 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Contains the list of OpenAPI data types
3
+ * as defined by https://swagger.io/docs/specification/data-models/data-types/
4
+ * @public
5
+ */
6
+ var SchemaType;
7
+ (function (SchemaType) {
8
+ /** String type. */
9
+ SchemaType["STRING"] = "string";
10
+ /** Number type. */
11
+ SchemaType["NUMBER"] = "number";
12
+ /** Integer type. */
13
+ SchemaType["INTEGER"] = "integer";
14
+ /** Boolean type. */
15
+ SchemaType["BOOLEAN"] = "boolean";
16
+ /** Array type. */
17
+ SchemaType["ARRAY"] = "array";
18
+ /** Object type. */
19
+ SchemaType["OBJECT"] = "object";
20
+ })(SchemaType || (SchemaType = {}));
21
+
22
+ /**
23
+ * @license
24
+ * Copyright 2024 Google LLC
25
+ *
26
+ * Licensed under the Apache License, Version 2.0 (the "License");
27
+ * you may not use this file except in compliance with the License.
28
+ * You may obtain a copy of the License at
29
+ *
30
+ * http://www.apache.org/licenses/LICENSE-2.0
31
+ *
32
+ * Unless required by applicable law or agreed to in writing, software
33
+ * distributed under the License is distributed on an "AS IS" BASIS,
34
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
35
+ * See the License for the specific language governing permissions and
36
+ * limitations under the License.
37
+ */
38
+ /**
39
+ * @public
40
+ */
41
+ var ExecutableCodeLanguage;
42
+ (function (ExecutableCodeLanguage) {
43
+ ExecutableCodeLanguage["LANGUAGE_UNSPECIFIED"] = "language_unspecified";
44
+ ExecutableCodeLanguage["PYTHON"] = "python";
45
+ })(ExecutableCodeLanguage || (ExecutableCodeLanguage = {}));
46
+ /**
47
+ * Possible outcomes of code execution.
48
+ * @public
49
+ */
50
+ var Outcome;
51
+ (function (Outcome) {
52
+ /**
53
+ * Unspecified status. This value should not be used.
54
+ */
55
+ Outcome["OUTCOME_UNSPECIFIED"] = "outcome_unspecified";
56
+ /**
57
+ * Code execution completed successfully.
58
+ */
59
+ Outcome["OUTCOME_OK"] = "outcome_ok";
60
+ /**
61
+ * Code execution finished but with a failure. `stderr` should contain the
62
+ * reason.
63
+ */
64
+ Outcome["OUTCOME_FAILED"] = "outcome_failed";
65
+ /**
66
+ * Code execution ran for too long, and was cancelled. There may or may not
67
+ * be a partial output present.
68
+ */
69
+ Outcome["OUTCOME_DEADLINE_EXCEEDED"] = "outcome_deadline_exceeded";
70
+ })(Outcome || (Outcome = {}));
71
+
72
+ /**
73
+ * @license
74
+ * Copyright 2024 Google LLC
75
+ *
76
+ * Licensed under the Apache License, Version 2.0 (the "License");
77
+ * you may not use this file except in compliance with the License.
78
+ * You may obtain a copy of the License at
79
+ *
80
+ * http://www.apache.org/licenses/LICENSE-2.0
81
+ *
82
+ * Unless required by applicable law or agreed to in writing, software
83
+ * distributed under the License is distributed on an "AS IS" BASIS,
84
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
85
+ * See the License for the specific language governing permissions and
86
+ * limitations under the License.
87
+ */
88
+ /**
89
+ * Possible roles.
90
+ * @public
91
+ */
92
+ const POSSIBLE_ROLES = ["user", "model", "function", "system"];
93
+ /**
94
+ * Harm categories that would cause prompts or candidates to be blocked.
95
+ * @public
96
+ */
97
+ var HarmCategory;
98
+ (function (HarmCategory) {
99
+ HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED";
100
+ HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH";
101
+ HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT";
102
+ HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT";
103
+ HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT";
104
+ HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY";
105
+ })(HarmCategory || (HarmCategory = {}));
106
+ /**
107
+ * Threshold above which a prompt or candidate will be blocked.
108
+ * @public
109
+ */
110
+ var HarmBlockThreshold;
111
+ (function (HarmBlockThreshold) {
112
+ /** Threshold is unspecified. */
113
+ HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED";
114
+ /** Content with NEGLIGIBLE will be allowed. */
115
+ HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE";
116
+ /** Content with NEGLIGIBLE and LOW will be allowed. */
117
+ HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE";
118
+ /** Content with NEGLIGIBLE, LOW, and MEDIUM will be allowed. */
119
+ HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH";
120
+ /** All content will be allowed. */
121
+ HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE";
122
+ })(HarmBlockThreshold || (HarmBlockThreshold = {}));
123
+ /**
124
+ * Probability that a prompt or candidate matches a harm category.
125
+ * @public
126
+ */
127
+ var HarmProbability;
128
+ (function (HarmProbability) {
129
+ /** Probability is unspecified. */
130
+ HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED";
131
+ /** Content has a negligible chance of being unsafe. */
132
+ HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE";
133
+ /** Content has a low chance of being unsafe. */
134
+ HarmProbability["LOW"] = "LOW";
135
+ /** Content has a medium chance of being unsafe. */
136
+ HarmProbability["MEDIUM"] = "MEDIUM";
137
+ /** Content has a high chance of being unsafe. */
138
+ HarmProbability["HIGH"] = "HIGH";
139
+ })(HarmProbability || (HarmProbability = {}));
140
+ /**
141
+ * Reason that a prompt was blocked.
142
+ * @public
143
+ */
144
+ var BlockReason;
145
+ (function (BlockReason) {
146
+ // A blocked reason was not specified.
147
+ BlockReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED";
148
+ // Content was blocked by safety settings.
149
+ BlockReason["SAFETY"] = "SAFETY";
150
+ // Content was blocked, but the reason is uncategorized.
151
+ BlockReason["OTHER"] = "OTHER";
152
+ })(BlockReason || (BlockReason = {}));
153
+ /**
154
+ * Reason that a candidate finished.
155
+ * @public
156
+ */
157
+ var FinishReason;
158
+ (function (FinishReason) {
159
+ // Default value. This value is unused.
160
+ FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED";
161
+ // Natural stop point of the model or provided stop sequence.
162
+ FinishReason["STOP"] = "STOP";
163
+ // The maximum number of tokens as specified in the request was reached.
164
+ FinishReason["MAX_TOKENS"] = "MAX_TOKENS";
165
+ // The candidate content was flagged for safety reasons.
166
+ FinishReason["SAFETY"] = "SAFETY";
167
+ // The candidate content was flagged for recitation reasons.
168
+ FinishReason["RECITATION"] = "RECITATION";
169
+ // The candidate content was flagged for using an unsupported language.
170
+ FinishReason["LANGUAGE"] = "LANGUAGE";
171
+ // Token generation stopped because the content contains forbidden terms.
172
+ FinishReason["BLOCKLIST"] = "BLOCKLIST";
173
+ // Token generation stopped for potentially containing prohibited content.
174
+ FinishReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT";
175
+ // Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII).
176
+ FinishReason["SPII"] = "SPII";
177
+ // The function call generated by the model is invalid.
178
+ FinishReason["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL";
179
+ // Unknown reason.
180
+ FinishReason["OTHER"] = "OTHER";
181
+ })(FinishReason || (FinishReason = {}));
182
+ /**
183
+ * Task type for embedding content.
184
+ * @public
185
+ */
186
+ var TaskType;
187
+ (function (TaskType) {
188
+ TaskType["TASK_TYPE_UNSPECIFIED"] = "TASK_TYPE_UNSPECIFIED";
189
+ TaskType["RETRIEVAL_QUERY"] = "RETRIEVAL_QUERY";
190
+ TaskType["RETRIEVAL_DOCUMENT"] = "RETRIEVAL_DOCUMENT";
191
+ TaskType["SEMANTIC_SIMILARITY"] = "SEMANTIC_SIMILARITY";
192
+ TaskType["CLASSIFICATION"] = "CLASSIFICATION";
193
+ TaskType["CLUSTERING"] = "CLUSTERING";
194
+ })(TaskType || (TaskType = {}));
195
+ /**
196
+ * @public
197
+ */
198
+ var FunctionCallingMode;
199
+ (function (FunctionCallingMode) {
200
+ // Unspecified function calling mode. This value should not be used.
201
+ FunctionCallingMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
202
+ // Default model behavior, model decides to predict either a function call
203
+ // or a natural language repspose.
204
+ FunctionCallingMode["AUTO"] = "AUTO";
205
+ // Model is constrained to always predicting a function call only.
206
+ // If "allowed_function_names" are set, the predicted function call will be
207
+ // limited to any one of "allowed_function_names", else the predicted
208
+ // function call will be any one of the provided "function_declarations".
209
+ FunctionCallingMode["ANY"] = "ANY";
210
+ // Model will not predict any function call. Model behavior is same as when
211
+ // not passing any function declarations.
212
+ FunctionCallingMode["NONE"] = "NONE";
213
+ })(FunctionCallingMode || (FunctionCallingMode = {}));
214
+ /**
215
+ * The mode of the predictor to be used in dynamic retrieval.
216
+ * @public
217
+ */
218
+ var DynamicRetrievalMode;
219
+ (function (DynamicRetrievalMode) {
220
+ // Unspecified function calling mode. This value should not be used.
221
+ DynamicRetrievalMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
222
+ // Run retrieval only when system decides it is necessary.
223
+ DynamicRetrievalMode["MODE_DYNAMIC"] = "MODE_DYNAMIC";
224
+ })(DynamicRetrievalMode || (DynamicRetrievalMode = {}));
225
+
226
+ /**
227
+ * @license
228
+ * Copyright 2024 Google LLC
229
+ *
230
+ * Licensed under the Apache License, Version 2.0 (the "License");
231
+ * you may not use this file except in compliance with the License.
232
+ * You may obtain a copy of the License at
233
+ *
234
+ * http://www.apache.org/licenses/LICENSE-2.0
235
+ *
236
+ * Unless required by applicable law or agreed to in writing, software
237
+ * distributed under the License is distributed on an "AS IS" BASIS,
238
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
239
+ * See the License for the specific language governing permissions and
240
+ * limitations under the License.
241
+ */
242
+ /**
243
+ * Basic error type for this SDK.
244
+ * @public
245
+ */
246
+ class GoogleGenerativeAIError extends Error {
247
+ constructor(message) {
248
+ super(`[GoogleGenerativeAI Error]: ${message}`);
249
+ }
250
+ }
251
+ /**
252
+ * Errors in the contents of a response from the model. This includes parsing
253
+ * errors, or responses including a safety block reason.
254
+ * @public
255
+ */
256
+ class GoogleGenerativeAIResponseError extends GoogleGenerativeAIError {
257
+ constructor(message, response) {
258
+ super(message);
259
+ this.response = response;
260
+ }
261
+ }
262
+ /**
263
+ * Error class covering HTTP errors when calling the server. Includes HTTP
264
+ * status, statusText, and optional details, if provided in the server response.
265
+ * @public
266
+ */
267
+ class GoogleGenerativeAIFetchError extends GoogleGenerativeAIError {
268
+ constructor(message, status, statusText, errorDetails) {
269
+ super(message);
270
+ this.status = status;
271
+ this.statusText = statusText;
272
+ this.errorDetails = errorDetails;
273
+ }
274
+ }
275
+ /**
276
+ * Errors in the contents of a request originating from user input.
277
+ * @public
278
+ */
279
+ class GoogleGenerativeAIRequestInputError extends GoogleGenerativeAIError {
280
+ }
281
+ /**
282
+ * Error thrown when a request is aborted, either due to a timeout or
283
+ * intentional cancellation by the user.
284
+ * @public
285
+ */
286
+ class GoogleGenerativeAIAbortError extends GoogleGenerativeAIError {
287
+ }
288
+
289
+ /**
290
+ * @license
291
+ * Copyright 2024 Google LLC
292
+ *
293
+ * Licensed under the Apache License, Version 2.0 (the "License");
294
+ * you may not use this file except in compliance with the License.
295
+ * You may obtain a copy of the License at
296
+ *
297
+ * http://www.apache.org/licenses/LICENSE-2.0
298
+ *
299
+ * Unless required by applicable law or agreed to in writing, software
300
+ * distributed under the License is distributed on an "AS IS" BASIS,
301
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
302
+ * See the License for the specific language governing permissions and
303
+ * limitations under the License.
304
+ */
305
+ const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com";
306
+ const DEFAULT_API_VERSION = "v1beta";
307
+ /**
308
+ * We can't `require` package.json if this runs on web. We will use rollup to
309
+ * swap in the version number here at build time.
310
+ */
311
+ const PACKAGE_VERSION = "0.24.1";
312
+ const PACKAGE_LOG_HEADER = "genai-js";
313
+ var Task;
314
+ (function (Task) {
315
+ Task["GENERATE_CONTENT"] = "generateContent";
316
+ Task["STREAM_GENERATE_CONTENT"] = "streamGenerateContent";
317
+ Task["COUNT_TOKENS"] = "countTokens";
318
+ Task["EMBED_CONTENT"] = "embedContent";
319
+ Task["BATCH_EMBED_CONTENTS"] = "batchEmbedContents";
320
+ })(Task || (Task = {}));
321
+ class RequestUrl {
322
+ constructor(model, task, apiKey, stream, requestOptions) {
323
+ this.model = model;
324
+ this.task = task;
325
+ this.apiKey = apiKey;
326
+ this.stream = stream;
327
+ this.requestOptions = requestOptions;
328
+ }
329
+ toString() {
330
+ var _a, _b;
331
+ const apiVersion = ((_a = this.requestOptions) === null || _a === void 0 ? void 0 : _a.apiVersion) || DEFAULT_API_VERSION;
332
+ const baseUrl = ((_b = this.requestOptions) === null || _b === void 0 ? void 0 : _b.baseUrl) || DEFAULT_BASE_URL;
333
+ let url = `${baseUrl}/${apiVersion}/${this.model}:${this.task}`;
334
+ if (this.stream) {
335
+ url += "?alt=sse";
336
+ }
337
+ return url;
338
+ }
339
+ }
340
+ /**
341
+ * Simple, but may become more complex if we add more versions to log.
342
+ */
343
+ function getClientHeaders(requestOptions) {
344
+ const clientHeaders = [];
345
+ if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.apiClient) {
346
+ clientHeaders.push(requestOptions.apiClient);
347
+ }
348
+ clientHeaders.push(`${PACKAGE_LOG_HEADER}/${PACKAGE_VERSION}`);
349
+ return clientHeaders.join(" ");
350
+ }
351
+ async function getHeaders(url) {
352
+ var _a;
353
+ const headers = new Headers();
354
+ headers.append("Content-Type", "application/json");
355
+ headers.append("x-goog-api-client", getClientHeaders(url.requestOptions));
356
+ headers.append("x-goog-api-key", url.apiKey);
357
+ let customHeaders = (_a = url.requestOptions) === null || _a === void 0 ? void 0 : _a.customHeaders;
358
+ if (customHeaders) {
359
+ if (!(customHeaders instanceof Headers)) {
360
+ try {
361
+ customHeaders = new Headers(customHeaders);
362
+ }
363
+ catch (e) {
364
+ throw new GoogleGenerativeAIRequestInputError(`unable to convert customHeaders value ${JSON.stringify(customHeaders)} to Headers: ${e.message}`);
365
+ }
366
+ }
367
+ for (const [headerName, headerValue] of customHeaders.entries()) {
368
+ if (headerName === "x-goog-api-key") {
369
+ throw new GoogleGenerativeAIRequestInputError(`Cannot set reserved header name ${headerName}`);
370
+ }
371
+ else if (headerName === "x-goog-api-client") {
372
+ throw new GoogleGenerativeAIRequestInputError(`Header name ${headerName} can only be set using the apiClient field`);
373
+ }
374
+ headers.append(headerName, headerValue);
375
+ }
376
+ }
377
+ return headers;
378
+ }
379
+ async function constructModelRequest(model, task, apiKey, stream, body, requestOptions) {
380
+ const url = new RequestUrl(model, task, apiKey, stream, requestOptions);
381
+ return {
382
+ url: url.toString(),
383
+ fetchOptions: Object.assign(Object.assign({}, buildFetchOptions(requestOptions)), { method: "POST", headers: await getHeaders(url), body }),
384
+ };
385
+ }
386
+ async function makeModelRequest(model, task, apiKey, stream, body, requestOptions = {},
387
+ // Allows this to be stubbed for tests
388
+ fetchFn = fetch) {
389
+ const { url, fetchOptions } = await constructModelRequest(model, task, apiKey, stream, body, requestOptions);
390
+ return makeRequest(url, fetchOptions, fetchFn);
391
+ }
392
+ async function makeRequest(url, fetchOptions, fetchFn = fetch) {
393
+ let response;
394
+ try {
395
+ response = await fetchFn(url, fetchOptions);
396
+ }
397
+ catch (e) {
398
+ handleResponseError(e, url);
399
+ }
400
+ if (!response.ok) {
401
+ await handleResponseNotOk(response, url);
402
+ }
403
+ return response;
404
+ }
405
+ function handleResponseError(e, url) {
406
+ let err = e;
407
+ if (err.name === "AbortError") {
408
+ err = new GoogleGenerativeAIAbortError(`Request aborted when fetching ${url.toString()}: ${e.message}`);
409
+ err.stack = e.stack;
410
+ }
411
+ else if (!(e instanceof GoogleGenerativeAIFetchError ||
412
+ e instanceof GoogleGenerativeAIRequestInputError)) {
413
+ err = new GoogleGenerativeAIError(`Error fetching from ${url.toString()}: ${e.message}`);
414
+ err.stack = e.stack;
415
+ }
416
+ throw err;
417
+ }
418
+ async function handleResponseNotOk(response, url) {
419
+ let message = "";
420
+ let errorDetails;
421
+ try {
422
+ const json = await response.json();
423
+ message = json.error.message;
424
+ if (json.error.details) {
425
+ message += ` ${JSON.stringify(json.error.details)}`;
426
+ errorDetails = json.error.details;
427
+ }
428
+ }
429
+ catch (e) {
430
+ // ignored
431
+ }
432
+ throw new GoogleGenerativeAIFetchError(`Error fetching from ${url.toString()}: [${response.status} ${response.statusText}] ${message}`, response.status, response.statusText, errorDetails);
433
+ }
434
+ /**
435
+ * Generates the request options to be passed to the fetch API.
436
+ * @param requestOptions - The user-defined request options.
437
+ * @returns The generated request options.
438
+ */
439
+ function buildFetchOptions(requestOptions) {
440
+ const fetchOptions = {};
441
+ if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.signal) !== undefined || (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeout) >= 0) {
442
+ const controller = new AbortController();
443
+ if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeout) >= 0) {
444
+ setTimeout(() => controller.abort(), requestOptions.timeout);
445
+ }
446
+ if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.signal) {
447
+ requestOptions.signal.addEventListener("abort", () => {
448
+ controller.abort();
449
+ });
450
+ }
451
+ fetchOptions.signal = controller.signal;
452
+ }
453
+ return fetchOptions;
454
+ }
455
+
456
+ /**
457
+ * @license
458
+ * Copyright 2024 Google LLC
459
+ *
460
+ * Licensed under the Apache License, Version 2.0 (the "License");
461
+ * you may not use this file except in compliance with the License.
462
+ * You may obtain a copy of the License at
463
+ *
464
+ * http://www.apache.org/licenses/LICENSE-2.0
465
+ *
466
+ * Unless required by applicable law or agreed to in writing, software
467
+ * distributed under the License is distributed on an "AS IS" BASIS,
468
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
469
+ * See the License for the specific language governing permissions and
470
+ * limitations under the License.
471
+ */
472
+ /**
473
+ * Adds convenience helper methods to a response object, including stream
474
+ * chunks (as long as each chunk is a complete GenerateContentResponse JSON).
475
+ */
476
+ function addHelpers(response) {
477
+ response.text = () => {
478
+ if (response.candidates && response.candidates.length > 0) {
479
+ if (response.candidates.length > 1) {
480
+ console.warn(`This response had ${response.candidates.length} ` +
481
+ `candidates. Returning text from the first candidate only. ` +
482
+ `Access response.candidates directly to use the other candidates.`);
483
+ }
484
+ if (hadBadFinishReason(response.candidates[0])) {
485
+ throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response);
486
+ }
487
+ return getText(response);
488
+ }
489
+ else if (response.promptFeedback) {
490
+ throw new GoogleGenerativeAIResponseError(`Text not available. ${formatBlockErrorMessage(response)}`, response);
491
+ }
492
+ return "";
493
+ };
494
+ /**
495
+ * TODO: remove at next major version
496
+ */
497
+ response.functionCall = () => {
498
+ if (response.candidates && response.candidates.length > 0) {
499
+ if (response.candidates.length > 1) {
500
+ console.warn(`This response had ${response.candidates.length} ` +
501
+ `candidates. Returning function calls from the first candidate only. ` +
502
+ `Access response.candidates directly to use the other candidates.`);
503
+ }
504
+ if (hadBadFinishReason(response.candidates[0])) {
505
+ throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response);
506
+ }
507
+ console.warn(`response.functionCall() is deprecated. ` +
508
+ `Use response.functionCalls() instead.`);
509
+ return getFunctionCalls(response)[0];
510
+ }
511
+ else if (response.promptFeedback) {
512
+ throw new GoogleGenerativeAIResponseError(`Function call not available. ${formatBlockErrorMessage(response)}`, response);
513
+ }
514
+ return undefined;
515
+ };
516
+ response.functionCalls = () => {
517
+ if (response.candidates && response.candidates.length > 0) {
518
+ if (response.candidates.length > 1) {
519
+ console.warn(`This response had ${response.candidates.length} ` +
520
+ `candidates. Returning function calls from the first candidate only. ` +
521
+ `Access response.candidates directly to use the other candidates.`);
522
+ }
523
+ if (hadBadFinishReason(response.candidates[0])) {
524
+ throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response);
525
+ }
526
+ return getFunctionCalls(response);
527
+ }
528
+ else if (response.promptFeedback) {
529
+ throw new GoogleGenerativeAIResponseError(`Function call not available. ${formatBlockErrorMessage(response)}`, response);
530
+ }
531
+ return undefined;
532
+ };
533
+ return response;
534
+ }
535
+ /**
536
+ * Returns all text found in all parts of first candidate.
537
+ */
538
+ function getText(response) {
539
+ var _a, _b, _c, _d;
540
+ const textStrings = [];
541
+ if ((_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0].content) === null || _b === void 0 ? void 0 : _b.parts) {
542
+ for (const part of (_d = (_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0].content) === null || _d === void 0 ? void 0 : _d.parts) {
543
+ if (part.text) {
544
+ textStrings.push(part.text);
545
+ }
546
+ if (part.executableCode) {
547
+ textStrings.push("\n```" +
548
+ part.executableCode.language +
549
+ "\n" +
550
+ part.executableCode.code +
551
+ "\n```\n");
552
+ }
553
+ if (part.codeExecutionResult) {
554
+ textStrings.push("\n```\n" + part.codeExecutionResult.output + "\n```\n");
555
+ }
556
+ }
557
+ }
558
+ if (textStrings.length > 0) {
559
+ return textStrings.join("");
560
+ }
561
+ else {
562
+ return "";
563
+ }
564
+ }
565
+ /**
566
+ * Returns functionCall of first candidate.
567
+ */
568
+ function getFunctionCalls(response) {
569
+ var _a, _b, _c, _d;
570
+ const functionCalls = [];
571
+ if ((_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0].content) === null || _b === void 0 ? void 0 : _b.parts) {
572
+ for (const part of (_d = (_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0].content) === null || _d === void 0 ? void 0 : _d.parts) {
573
+ if (part.functionCall) {
574
+ functionCalls.push(part.functionCall);
575
+ }
576
+ }
577
+ }
578
+ if (functionCalls.length > 0) {
579
+ return functionCalls;
580
+ }
581
+ else {
582
+ return undefined;
583
+ }
584
+ }
585
+ const badFinishReasons = [
586
+ FinishReason.RECITATION,
587
+ FinishReason.SAFETY,
588
+ FinishReason.LANGUAGE,
589
+ ];
590
+ function hadBadFinishReason(candidate) {
591
+ return (!!candidate.finishReason &&
592
+ badFinishReasons.includes(candidate.finishReason));
593
+ }
594
+ function formatBlockErrorMessage(response) {
595
+ var _a, _b, _c;
596
+ let message = "";
597
+ if ((!response.candidates || response.candidates.length === 0) &&
598
+ response.promptFeedback) {
599
+ message += "Response was blocked";
600
+ if ((_a = response.promptFeedback) === null || _a === void 0 ? void 0 : _a.blockReason) {
601
+ message += ` due to ${response.promptFeedback.blockReason}`;
602
+ }
603
+ if ((_b = response.promptFeedback) === null || _b === void 0 ? void 0 : _b.blockReasonMessage) {
604
+ message += `: ${response.promptFeedback.blockReasonMessage}`;
605
+ }
606
+ }
607
+ else if ((_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0]) {
608
+ const firstCandidate = response.candidates[0];
609
+ if (hadBadFinishReason(firstCandidate)) {
610
+ message += `Candidate was blocked due to ${firstCandidate.finishReason}`;
611
+ if (firstCandidate.finishMessage) {
612
+ message += `: ${firstCandidate.finishMessage}`;
613
+ }
614
+ }
615
+ }
616
+ return message;
617
+ }
618
+
619
+ /******************************************************************************
620
+ Copyright (c) Microsoft Corporation.
621
+
622
+ Permission to use, copy, modify, and/or distribute this software for any
623
+ purpose with or without fee is hereby granted.
624
+
625
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
626
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
627
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
628
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
629
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
630
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
631
+ PERFORMANCE OF THIS SOFTWARE.
632
+ ***************************************************************************** */
633
+ /* global Reflect, Promise, SuppressedError, Symbol */
634
+
635
+
636
+ function __await(v) {
637
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
638
+ }
639
+
640
+ function __asyncGenerator(thisArg, _arguments, generator) {
641
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
642
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
643
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
644
+ function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
645
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
646
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
647
+ function fulfill(value) { resume("next", value); }
648
+ function reject(value) { resume("throw", value); }
649
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
650
+ }
651
+
652
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
653
+ var e = new Error(message);
654
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
655
+ };
656
+
657
+ /**
658
+ * @license
659
+ * Copyright 2024 Google LLC
660
+ *
661
+ * Licensed under the Apache License, Version 2.0 (the "License");
662
+ * you may not use this file except in compliance with the License.
663
+ * You may obtain a copy of the License at
664
+ *
665
+ * http://www.apache.org/licenses/LICENSE-2.0
666
+ *
667
+ * Unless required by applicable law or agreed to in writing, software
668
+ * distributed under the License is distributed on an "AS IS" BASIS,
669
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
670
+ * See the License for the specific language governing permissions and
671
+ * limitations under the License.
672
+ */
673
+ const responseLineRE = /^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;
674
+ /**
675
+ * Process a response.body stream from the backend and return an
676
+ * iterator that provides one complete GenerateContentResponse at a time
677
+ * and a promise that resolves with a single aggregated
678
+ * GenerateContentResponse.
679
+ *
680
+ * @param response - Response from a fetch call
681
+ */
682
+ function processStream(response) {
683
+ const inputStream = response.body.pipeThrough(new TextDecoderStream("utf8", { fatal: true }));
684
+ const responseStream = getResponseStream(inputStream);
685
+ const [stream1, stream2] = responseStream.tee();
686
+ return {
687
+ stream: generateResponseSequence(stream1),
688
+ response: getResponsePromise(stream2),
689
+ };
690
+ }
691
+ async function getResponsePromise(stream) {
692
+ const allResponses = [];
693
+ const reader = stream.getReader();
694
+ while (true) {
695
+ const { done, value } = await reader.read();
696
+ if (done) {
697
+ return addHelpers(aggregateResponses(allResponses));
698
+ }
699
+ allResponses.push(value);
700
+ }
701
+ }
702
+ function generateResponseSequence(stream) {
703
+ return __asyncGenerator(this, arguments, function* generateResponseSequence_1() {
704
+ const reader = stream.getReader();
705
+ while (true) {
706
+ const { value, done } = yield __await(reader.read());
707
+ if (done) {
708
+ break;
709
+ }
710
+ yield yield __await(addHelpers(value));
711
+ }
712
+ });
713
+ }
714
+ /**
715
+ * Reads a raw stream from the fetch response and join incomplete
716
+ * chunks, returning a new stream that provides a single complete
717
+ * GenerateContentResponse in each iteration.
718
+ */
719
+ function getResponseStream(inputStream) {
720
+ const reader = inputStream.getReader();
721
+ const stream = new ReadableStream({
722
+ start(controller) {
723
+ let currentText = "";
724
+ return pump();
725
+ function pump() {
726
+ return reader
727
+ .read()
728
+ .then(({ value, done }) => {
729
+ if (done) {
730
+ if (currentText.trim()) {
731
+ controller.error(new GoogleGenerativeAIError("Failed to parse stream"));
732
+ return;
733
+ }
734
+ controller.close();
735
+ return;
736
+ }
737
+ currentText += value;
738
+ let match = currentText.match(responseLineRE);
739
+ let parsedResponse;
740
+ while (match) {
741
+ try {
742
+ parsedResponse = JSON.parse(match[1]);
743
+ }
744
+ catch (e) {
745
+ controller.error(new GoogleGenerativeAIError(`Error parsing JSON response: "${match[1]}"`));
746
+ return;
747
+ }
748
+ controller.enqueue(parsedResponse);
749
+ currentText = currentText.substring(match[0].length);
750
+ match = currentText.match(responseLineRE);
751
+ }
752
+ return pump();
753
+ })
754
+ .catch((e) => {
755
+ let err = e;
756
+ err.stack = e.stack;
757
+ if (err.name === "AbortError") {
758
+ err = new GoogleGenerativeAIAbortError("Request aborted when reading from the stream");
759
+ }
760
+ else {
761
+ err = new GoogleGenerativeAIError("Error reading from the stream");
762
+ }
763
+ throw err;
764
+ });
765
+ }
766
+ },
767
+ });
768
+ return stream;
769
+ }
770
+ /**
771
+ * Aggregates an array of `GenerateContentResponse`s into a single
772
+ * GenerateContentResponse.
773
+ */
774
+ function aggregateResponses(responses) {
775
+ const lastResponse = responses[responses.length - 1];
776
+ const aggregatedResponse = {
777
+ promptFeedback: lastResponse === null || lastResponse === void 0 ? void 0 : lastResponse.promptFeedback,
778
+ };
779
+ for (const response of responses) {
780
+ if (response.candidates) {
781
+ let candidateIndex = 0;
782
+ for (const candidate of response.candidates) {
783
+ if (!aggregatedResponse.candidates) {
784
+ aggregatedResponse.candidates = [];
785
+ }
786
+ if (!aggregatedResponse.candidates[candidateIndex]) {
787
+ aggregatedResponse.candidates[candidateIndex] = {
788
+ index: candidateIndex,
789
+ };
790
+ }
791
+ // Keep overwriting, the last one will be final
792
+ aggregatedResponse.candidates[candidateIndex].citationMetadata =
793
+ candidate.citationMetadata;
794
+ aggregatedResponse.candidates[candidateIndex].groundingMetadata =
795
+ candidate.groundingMetadata;
796
+ aggregatedResponse.candidates[candidateIndex].finishReason =
797
+ candidate.finishReason;
798
+ aggregatedResponse.candidates[candidateIndex].finishMessage =
799
+ candidate.finishMessage;
800
+ aggregatedResponse.candidates[candidateIndex].safetyRatings =
801
+ candidate.safetyRatings;
802
+ /**
803
+ * Candidates should always have content and parts, but this handles
804
+ * possible malformed responses.
805
+ */
806
+ if (candidate.content && candidate.content.parts) {
807
+ if (!aggregatedResponse.candidates[candidateIndex].content) {
808
+ aggregatedResponse.candidates[candidateIndex].content = {
809
+ role: candidate.content.role || "user",
810
+ parts: [],
811
+ };
812
+ }
813
+ const newPart = {};
814
+ for (const part of candidate.content.parts) {
815
+ if (part.text) {
816
+ newPart.text = part.text;
817
+ }
818
+ if (part.functionCall) {
819
+ newPart.functionCall = part.functionCall;
820
+ }
821
+ if (part.executableCode) {
822
+ newPart.executableCode = part.executableCode;
823
+ }
824
+ if (part.codeExecutionResult) {
825
+ newPart.codeExecutionResult = part.codeExecutionResult;
826
+ }
827
+ if (Object.keys(newPart).length === 0) {
828
+ newPart.text = "";
829
+ }
830
+ aggregatedResponse.candidates[candidateIndex].content.parts.push(newPart);
831
+ }
832
+ }
833
+ }
834
+ candidateIndex++;
835
+ }
836
+ if (response.usageMetadata) {
837
+ aggregatedResponse.usageMetadata = response.usageMetadata;
838
+ }
839
+ }
840
+ return aggregatedResponse;
841
+ }
842
+
843
+ /**
844
+ * @license
845
+ * Copyright 2024 Google LLC
846
+ *
847
+ * Licensed under the Apache License, Version 2.0 (the "License");
848
+ * you may not use this file except in compliance with the License.
849
+ * You may obtain a copy of the License at
850
+ *
851
+ * http://www.apache.org/licenses/LICENSE-2.0
852
+ *
853
+ * Unless required by applicable law or agreed to in writing, software
854
+ * distributed under the License is distributed on an "AS IS" BASIS,
855
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
856
+ * See the License for the specific language governing permissions and
857
+ * limitations under the License.
858
+ */
859
+ async function generateContentStream(apiKey, model, params, requestOptions) {
860
+ const response = await makeModelRequest(model, Task.STREAM_GENERATE_CONTENT, apiKey,
861
+ /* stream */ true, JSON.stringify(params), requestOptions);
862
+ return processStream(response);
863
+ }
864
+ async function generateContent(apiKey, model, params, requestOptions) {
865
+ const response = await makeModelRequest(model, Task.GENERATE_CONTENT, apiKey,
866
+ /* stream */ false, JSON.stringify(params), requestOptions);
867
+ const responseJson = await response.json();
868
+ const enhancedResponse = addHelpers(responseJson);
869
+ return {
870
+ response: enhancedResponse,
871
+ };
872
+ }
873
+
874
+ /**
875
+ * @license
876
+ * Copyright 2024 Google LLC
877
+ *
878
+ * Licensed under the Apache License, Version 2.0 (the "License");
879
+ * you may not use this file except in compliance with the License.
880
+ * You may obtain a copy of the License at
881
+ *
882
+ * http://www.apache.org/licenses/LICENSE-2.0
883
+ *
884
+ * Unless required by applicable law or agreed to in writing, software
885
+ * distributed under the License is distributed on an "AS IS" BASIS,
886
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
887
+ * See the License for the specific language governing permissions and
888
+ * limitations under the License.
889
+ */
890
+ function formatSystemInstruction(input) {
891
+ // null or undefined
892
+ if (input == null) {
893
+ return undefined;
894
+ }
895
+ else if (typeof input === "string") {
896
+ return { role: "system", parts: [{ text: input }] };
897
+ }
898
+ else if (input.text) {
899
+ return { role: "system", parts: [input] };
900
+ }
901
+ else if (input.parts) {
902
+ if (!input.role) {
903
+ return { role: "system", parts: input.parts };
904
+ }
905
+ else {
906
+ return input;
907
+ }
908
+ }
909
+ }
910
+ function formatNewContent(request) {
911
+ let newParts = [];
912
+ if (typeof request === "string") {
913
+ newParts = [{ text: request }];
914
+ }
915
+ else {
916
+ for (const partOrString of request) {
917
+ if (typeof partOrString === "string") {
918
+ newParts.push({ text: partOrString });
919
+ }
920
+ else {
921
+ newParts.push(partOrString);
922
+ }
923
+ }
924
+ }
925
+ return assignRoleToPartsAndValidateSendMessageRequest(newParts);
926
+ }
927
+ /**
928
+ * When multiple Part types (i.e. FunctionResponsePart and TextPart) are
929
+ * passed in a single Part array, we may need to assign different roles to each
930
+ * part. Currently only FunctionResponsePart requires a role other than 'user'.
931
+ * @private
932
+ * @param parts Array of parts to pass to the model
933
+ * @returns Array of content items
934
+ */
935
+ function assignRoleToPartsAndValidateSendMessageRequest(parts) {
936
+ const userContent = { role: "user", parts: [] };
937
+ const functionContent = { role: "function", parts: [] };
938
+ let hasUserContent = false;
939
+ let hasFunctionContent = false;
940
+ for (const part of parts) {
941
+ if ("functionResponse" in part) {
942
+ functionContent.parts.push(part);
943
+ hasFunctionContent = true;
944
+ }
945
+ else {
946
+ userContent.parts.push(part);
947
+ hasUserContent = true;
948
+ }
949
+ }
950
+ if (hasUserContent && hasFunctionContent) {
951
+ throw new GoogleGenerativeAIError("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");
952
+ }
953
+ if (!hasUserContent && !hasFunctionContent) {
954
+ throw new GoogleGenerativeAIError("No content is provided for sending chat message.");
955
+ }
956
+ if (hasUserContent) {
957
+ return userContent;
958
+ }
959
+ return functionContent;
960
+ }
961
+ function formatCountTokensInput(params, modelParams) {
962
+ var _a;
963
+ let formattedGenerateContentRequest = {
964
+ model: modelParams === null || modelParams === void 0 ? void 0 : modelParams.model,
965
+ generationConfig: modelParams === null || modelParams === void 0 ? void 0 : modelParams.generationConfig,
966
+ safetySettings: modelParams === null || modelParams === void 0 ? void 0 : modelParams.safetySettings,
967
+ tools: modelParams === null || modelParams === void 0 ? void 0 : modelParams.tools,
968
+ toolConfig: modelParams === null || modelParams === void 0 ? void 0 : modelParams.toolConfig,
969
+ systemInstruction: modelParams === null || modelParams === void 0 ? void 0 : modelParams.systemInstruction,
970
+ cachedContent: (_a = modelParams === null || modelParams === void 0 ? void 0 : modelParams.cachedContent) === null || _a === void 0 ? void 0 : _a.name,
971
+ contents: [],
972
+ };
973
+ const containsGenerateContentRequest = params.generateContentRequest != null;
974
+ if (params.contents) {
975
+ if (containsGenerateContentRequest) {
976
+ throw new GoogleGenerativeAIRequestInputError("CountTokensRequest must have one of contents or generateContentRequest, not both.");
977
+ }
978
+ formattedGenerateContentRequest.contents = params.contents;
979
+ }
980
+ else if (containsGenerateContentRequest) {
981
+ formattedGenerateContentRequest = Object.assign(Object.assign({}, formattedGenerateContentRequest), params.generateContentRequest);
982
+ }
983
+ else {
984
+ // Array or string
985
+ const content = formatNewContent(params);
986
+ formattedGenerateContentRequest.contents = [content];
987
+ }
988
+ return { generateContentRequest: formattedGenerateContentRequest };
989
+ }
990
+ function formatGenerateContentInput(params) {
991
+ let formattedRequest;
992
+ if (params.contents) {
993
+ formattedRequest = params;
994
+ }
995
+ else {
996
+ // Array or string
997
+ const content = formatNewContent(params);
998
+ formattedRequest = { contents: [content] };
999
+ }
1000
+ if (params.systemInstruction) {
1001
+ formattedRequest.systemInstruction = formatSystemInstruction(params.systemInstruction);
1002
+ }
1003
+ return formattedRequest;
1004
+ }
1005
+ function formatEmbedContentInput(params) {
1006
+ if (typeof params === "string" || Array.isArray(params)) {
1007
+ const content = formatNewContent(params);
1008
+ return { content };
1009
+ }
1010
+ return params;
1011
+ }
1012
+
1013
+ /**
1014
+ * @license
1015
+ * Copyright 2024 Google LLC
1016
+ *
1017
+ * Licensed under the Apache License, Version 2.0 (the "License");
1018
+ * you may not use this file except in compliance with the License.
1019
+ * You may obtain a copy of the License at
1020
+ *
1021
+ * http://www.apache.org/licenses/LICENSE-2.0
1022
+ *
1023
+ * Unless required by applicable law or agreed to in writing, software
1024
+ * distributed under the License is distributed on an "AS IS" BASIS,
1025
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1026
+ * See the License for the specific language governing permissions and
1027
+ * limitations under the License.
1028
+ */
1029
+ // https://ai.google.dev/api/rest/v1beta/Content#part
1030
+ const VALID_PART_FIELDS = [
1031
+ "text",
1032
+ "inlineData",
1033
+ "functionCall",
1034
+ "functionResponse",
1035
+ "executableCode",
1036
+ "codeExecutionResult",
1037
+ ];
1038
+ const VALID_PARTS_PER_ROLE = {
1039
+ user: ["text", "inlineData"],
1040
+ function: ["functionResponse"],
1041
+ model: ["text", "functionCall", "executableCode", "codeExecutionResult"],
1042
+ // System instructions shouldn't be in history anyway.
1043
+ system: ["text"],
1044
+ };
1045
+ function validateChatHistory(history) {
1046
+ let prevContent = false;
1047
+ for (const currContent of history) {
1048
+ const { role, parts } = currContent;
1049
+ if (!prevContent && role !== "user") {
1050
+ throw new GoogleGenerativeAIError(`First content should be with role 'user', got ${role}`);
1051
+ }
1052
+ if (!POSSIBLE_ROLES.includes(role)) {
1053
+ throw new GoogleGenerativeAIError(`Each item should include role field. Got ${role} but valid roles are: ${JSON.stringify(POSSIBLE_ROLES)}`);
1054
+ }
1055
+ if (!Array.isArray(parts)) {
1056
+ throw new GoogleGenerativeAIError("Content should have 'parts' property with an array of Parts");
1057
+ }
1058
+ if (parts.length === 0) {
1059
+ throw new GoogleGenerativeAIError("Each Content should have at least one part");
1060
+ }
1061
+ const countFields = {
1062
+ text: 0,
1063
+ inlineData: 0,
1064
+ functionCall: 0,
1065
+ functionResponse: 0,
1066
+ fileData: 0,
1067
+ executableCode: 0,
1068
+ codeExecutionResult: 0,
1069
+ };
1070
+ for (const part of parts) {
1071
+ for (const key of VALID_PART_FIELDS) {
1072
+ if (key in part) {
1073
+ countFields[key] += 1;
1074
+ }
1075
+ }
1076
+ }
1077
+ const validParts = VALID_PARTS_PER_ROLE[role];
1078
+ for (const key of VALID_PART_FIELDS) {
1079
+ if (!validParts.includes(key) && countFields[key] > 0) {
1080
+ throw new GoogleGenerativeAIError(`Content with role '${role}' can't contain '${key}' part`);
1081
+ }
1082
+ }
1083
+ prevContent = true;
1084
+ }
1085
+ }
1086
+ /**
1087
+ * Returns true if the response is valid (could be appended to the history), flase otherwise.
1088
+ */
1089
+ function isValidResponse(response) {
1090
+ var _a;
1091
+ if (response.candidates === undefined || response.candidates.length === 0) {
1092
+ return false;
1093
+ }
1094
+ const content = (_a = response.candidates[0]) === null || _a === void 0 ? void 0 : _a.content;
1095
+ if (content === undefined) {
1096
+ return false;
1097
+ }
1098
+ if (content.parts === undefined || content.parts.length === 0) {
1099
+ return false;
1100
+ }
1101
+ for (const part of content.parts) {
1102
+ if (part === undefined || Object.keys(part).length === 0) {
1103
+ return false;
1104
+ }
1105
+ if (part.text !== undefined && part.text === "") {
1106
+ return false;
1107
+ }
1108
+ }
1109
+ return true;
1110
+ }
1111
+
1112
+ /**
1113
+ * @license
1114
+ * Copyright 2024 Google LLC
1115
+ *
1116
+ * Licensed under the Apache License, Version 2.0 (the "License");
1117
+ * you may not use this file except in compliance with the License.
1118
+ * You may obtain a copy of the License at
1119
+ *
1120
+ * http://www.apache.org/licenses/LICENSE-2.0
1121
+ *
1122
+ * Unless required by applicable law or agreed to in writing, software
1123
+ * distributed under the License is distributed on an "AS IS" BASIS,
1124
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1125
+ * See the License for the specific language governing permissions and
1126
+ * limitations under the License.
1127
+ */
1128
+ /**
1129
+ * Do not log a message for this error.
1130
+ */
1131
+ const SILENT_ERROR = "SILENT_ERROR";
1132
+ /**
1133
+ * ChatSession class that enables sending chat messages and stores
1134
+ * history of sent and received messages so far.
1135
+ *
1136
+ * @public
1137
+ */
1138
+ class ChatSession {
1139
+ constructor(apiKey, model, params, _requestOptions = {}) {
1140
+ this.model = model;
1141
+ this.params = params;
1142
+ this._requestOptions = _requestOptions;
1143
+ this._history = [];
1144
+ this._sendPromise = Promise.resolve();
1145
+ this._apiKey = apiKey;
1146
+ if (params === null || params === void 0 ? void 0 : params.history) {
1147
+ validateChatHistory(params.history);
1148
+ this._history = params.history;
1149
+ }
1150
+ }
1151
+ /**
1152
+ * Gets the chat history so far. Blocked prompts are not added to history.
1153
+ * Blocked candidates are not added to history, nor are the prompts that
1154
+ * generated them.
1155
+ */
1156
+ async getHistory() {
1157
+ await this._sendPromise;
1158
+ return this._history;
1159
+ }
1160
+ /**
1161
+ * Sends a chat message and receives a non-streaming
1162
+ * {@link GenerateContentResult}.
1163
+ *
1164
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
1165
+ * take precedence over the {@link RequestOptions} values provided to
1166
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
1167
+ */
1168
+ async sendMessage(request, requestOptions = {}) {
1169
+ var _a, _b, _c, _d, _e, _f;
1170
+ await this._sendPromise;
1171
+ const newContent = formatNewContent(request);
1172
+ const generateContentRequest = {
1173
+ safetySettings: (_a = this.params) === null || _a === void 0 ? void 0 : _a.safetySettings,
1174
+ generationConfig: (_b = this.params) === null || _b === void 0 ? void 0 : _b.generationConfig,
1175
+ tools: (_c = this.params) === null || _c === void 0 ? void 0 : _c.tools,
1176
+ toolConfig: (_d = this.params) === null || _d === void 0 ? void 0 : _d.toolConfig,
1177
+ systemInstruction: (_e = this.params) === null || _e === void 0 ? void 0 : _e.systemInstruction,
1178
+ cachedContent: (_f = this.params) === null || _f === void 0 ? void 0 : _f.cachedContent,
1179
+ contents: [...this._history, newContent],
1180
+ };
1181
+ const chatSessionRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
1182
+ let finalResult;
1183
+ // Add onto the chain.
1184
+ this._sendPromise = this._sendPromise
1185
+ .then(() => generateContent(this._apiKey, this.model, generateContentRequest, chatSessionRequestOptions))
1186
+ .then((result) => {
1187
+ var _a;
1188
+ if (isValidResponse(result.response)) {
1189
+ this._history.push(newContent);
1190
+ const responseContent = Object.assign({ parts: [],
1191
+ // Response seems to come back without a role set.
1192
+ role: "model" }, (_a = result.response.candidates) === null || _a === void 0 ? void 0 : _a[0].content);
1193
+ this._history.push(responseContent);
1194
+ }
1195
+ else {
1196
+ const blockErrorMessage = formatBlockErrorMessage(result.response);
1197
+ if (blockErrorMessage) {
1198
+ console.warn(`sendMessage() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`);
1199
+ }
1200
+ }
1201
+ finalResult = result;
1202
+ })
1203
+ .catch((e) => {
1204
+ // Resets _sendPromise to avoid subsequent calls failing and throw error.
1205
+ this._sendPromise = Promise.resolve();
1206
+ throw e;
1207
+ });
1208
+ await this._sendPromise;
1209
+ return finalResult;
1210
+ }
1211
+ /**
1212
+ * Sends a chat message and receives the response as a
1213
+ * {@link GenerateContentStreamResult} containing an iterable stream
1214
+ * and a response promise.
1215
+ *
1216
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
1217
+ * take precedence over the {@link RequestOptions} values provided to
1218
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
1219
+ */
1220
+ async sendMessageStream(request, requestOptions = {}) {
1221
+ var _a, _b, _c, _d, _e, _f;
1222
+ await this._sendPromise;
1223
+ const newContent = formatNewContent(request);
1224
+ const generateContentRequest = {
1225
+ safetySettings: (_a = this.params) === null || _a === void 0 ? void 0 : _a.safetySettings,
1226
+ generationConfig: (_b = this.params) === null || _b === void 0 ? void 0 : _b.generationConfig,
1227
+ tools: (_c = this.params) === null || _c === void 0 ? void 0 : _c.tools,
1228
+ toolConfig: (_d = this.params) === null || _d === void 0 ? void 0 : _d.toolConfig,
1229
+ systemInstruction: (_e = this.params) === null || _e === void 0 ? void 0 : _e.systemInstruction,
1230
+ cachedContent: (_f = this.params) === null || _f === void 0 ? void 0 : _f.cachedContent,
1231
+ contents: [...this._history, newContent],
1232
+ };
1233
+ const chatSessionRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
1234
+ const streamPromise = generateContentStream(this._apiKey, this.model, generateContentRequest, chatSessionRequestOptions);
1235
+ // Add onto the chain.
1236
+ this._sendPromise = this._sendPromise
1237
+ .then(() => streamPromise)
1238
+ // This must be handled to avoid unhandled rejection, but jump
1239
+ // to the final catch block with a label to not log this error.
1240
+ .catch((_ignored) => {
1241
+ throw new Error(SILENT_ERROR);
1242
+ })
1243
+ .then((streamResult) => streamResult.response)
1244
+ .then((response) => {
1245
+ if (isValidResponse(response)) {
1246
+ this._history.push(newContent);
1247
+ const responseContent = Object.assign({}, response.candidates[0].content);
1248
+ // Response seems to come back without a role set.
1249
+ if (!responseContent.role) {
1250
+ responseContent.role = "model";
1251
+ }
1252
+ this._history.push(responseContent);
1253
+ }
1254
+ else {
1255
+ const blockErrorMessage = formatBlockErrorMessage(response);
1256
+ if (blockErrorMessage) {
1257
+ console.warn(`sendMessageStream() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`);
1258
+ }
1259
+ }
1260
+ })
1261
+ .catch((e) => {
1262
+ // Errors in streamPromise are already catchable by the user as
1263
+ // streamPromise is returned.
1264
+ // Avoid duplicating the error message in logs.
1265
+ if (e.message !== SILENT_ERROR) {
1266
+ // Users do not have access to _sendPromise to catch errors
1267
+ // downstream from streamPromise, so they should not throw.
1268
+ console.error(e);
1269
+ }
1270
+ });
1271
+ return streamPromise;
1272
+ }
1273
+ }
1274
+
1275
+ /**
1276
+ * @license
1277
+ * Copyright 2024 Google LLC
1278
+ *
1279
+ * Licensed under the Apache License, Version 2.0 (the "License");
1280
+ * you may not use this file except in compliance with the License.
1281
+ * You may obtain a copy of the License at
1282
+ *
1283
+ * http://www.apache.org/licenses/LICENSE-2.0
1284
+ *
1285
+ * Unless required by applicable law or agreed to in writing, software
1286
+ * distributed under the License is distributed on an "AS IS" BASIS,
1287
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1288
+ * See the License for the specific language governing permissions and
1289
+ * limitations under the License.
1290
+ */
1291
+ async function countTokens(apiKey, model, params, singleRequestOptions) {
1292
+ const response = await makeModelRequest(model, Task.COUNT_TOKENS, apiKey, false, JSON.stringify(params), singleRequestOptions);
1293
+ return response.json();
1294
+ }
1295
+
1296
+ /**
1297
+ * @license
1298
+ * Copyright 2024 Google LLC
1299
+ *
1300
+ * Licensed under the Apache License, Version 2.0 (the "License");
1301
+ * you may not use this file except in compliance with the License.
1302
+ * You may obtain a copy of the License at
1303
+ *
1304
+ * http://www.apache.org/licenses/LICENSE-2.0
1305
+ *
1306
+ * Unless required by applicable law or agreed to in writing, software
1307
+ * distributed under the License is distributed on an "AS IS" BASIS,
1308
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1309
+ * See the License for the specific language governing permissions and
1310
+ * limitations under the License.
1311
+ */
1312
+ async function embedContent(apiKey, model, params, requestOptions) {
1313
+ const response = await makeModelRequest(model, Task.EMBED_CONTENT, apiKey, false, JSON.stringify(params), requestOptions);
1314
+ return response.json();
1315
+ }
1316
+ async function batchEmbedContents(apiKey, model, params, requestOptions) {
1317
+ const requestsWithModel = params.requests.map((request) => {
1318
+ return Object.assign(Object.assign({}, request), { model });
1319
+ });
1320
+ const response = await makeModelRequest(model, Task.BATCH_EMBED_CONTENTS, apiKey, false, JSON.stringify({ requests: requestsWithModel }), requestOptions);
1321
+ return response.json();
1322
+ }
1323
+
1324
+ /**
1325
+ * @license
1326
+ * Copyright 2024 Google LLC
1327
+ *
1328
+ * Licensed under the Apache License, Version 2.0 (the "License");
1329
+ * you may not use this file except in compliance with the License.
1330
+ * You may obtain a copy of the License at
1331
+ *
1332
+ * http://www.apache.org/licenses/LICENSE-2.0
1333
+ *
1334
+ * Unless required by applicable law or agreed to in writing, software
1335
+ * distributed under the License is distributed on an "AS IS" BASIS,
1336
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1337
+ * See the License for the specific language governing permissions and
1338
+ * limitations under the License.
1339
+ */
1340
+ /**
1341
+ * Class for generative model APIs.
1342
+ * @public
1343
+ */
1344
+ class GenerativeModel {
1345
+ constructor(apiKey, modelParams, _requestOptions = {}) {
1346
+ this.apiKey = apiKey;
1347
+ this._requestOptions = _requestOptions;
1348
+ if (modelParams.model.includes("/")) {
1349
+ // Models may be named "models/model-name" or "tunedModels/model-name"
1350
+ this.model = modelParams.model;
1351
+ }
1352
+ else {
1353
+ // If path is not included, assume it's a non-tuned model.
1354
+ this.model = `models/${modelParams.model}`;
1355
+ }
1356
+ this.generationConfig = modelParams.generationConfig || {};
1357
+ this.safetySettings = modelParams.safetySettings || [];
1358
+ this.tools = modelParams.tools;
1359
+ this.toolConfig = modelParams.toolConfig;
1360
+ this.systemInstruction = formatSystemInstruction(modelParams.systemInstruction);
1361
+ this.cachedContent = modelParams.cachedContent;
1362
+ }
1363
+ /**
1364
+ * Makes a single non-streaming call to the model
1365
+ * and returns an object containing a single {@link GenerateContentResponse}.
1366
+ *
1367
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
1368
+ * take precedence over the {@link RequestOptions} values provided to
1369
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
1370
+ */
1371
+ async generateContent(request, requestOptions = {}) {
1372
+ var _a;
1373
+ const formattedParams = formatGenerateContentInput(request);
1374
+ const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
1375
+ return generateContent(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a = this.cachedContent) === null || _a === void 0 ? void 0 : _a.name }, formattedParams), generativeModelRequestOptions);
1376
+ }
1377
+ /**
1378
+ * Makes a single streaming call to the model and returns an object
1379
+ * containing an iterable stream that iterates over all chunks in the
1380
+ * streaming response as well as a promise that returns the final
1381
+ * aggregated response.
1382
+ *
1383
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
1384
+ * take precedence over the {@link RequestOptions} values provided to
1385
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
1386
+ */
1387
+ async generateContentStream(request, requestOptions = {}) {
1388
+ var _a;
1389
+ const formattedParams = formatGenerateContentInput(request);
1390
+ const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
1391
+ return generateContentStream(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a = this.cachedContent) === null || _a === void 0 ? void 0 : _a.name }, formattedParams), generativeModelRequestOptions);
1392
+ }
1393
+ /**
1394
+ * Gets a new {@link ChatSession} instance which can be used for
1395
+ * multi-turn chats.
1396
+ */
1397
+ startChat(startChatParams) {
1398
+ var _a;
1399
+ return new ChatSession(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a = this.cachedContent) === null || _a === void 0 ? void 0 : _a.name }, startChatParams), this._requestOptions);
1400
+ }
1401
+ /**
1402
+ * Counts the tokens in the provided request.
1403
+ *
1404
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
1405
+ * take precedence over the {@link RequestOptions} values provided to
1406
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
1407
+ */
1408
+ async countTokens(request, requestOptions = {}) {
1409
+ const formattedParams = formatCountTokensInput(request, {
1410
+ model: this.model,
1411
+ generationConfig: this.generationConfig,
1412
+ safetySettings: this.safetySettings,
1413
+ tools: this.tools,
1414
+ toolConfig: this.toolConfig,
1415
+ systemInstruction: this.systemInstruction,
1416
+ cachedContent: this.cachedContent,
1417
+ });
1418
+ const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
1419
+ return countTokens(this.apiKey, this.model, formattedParams, generativeModelRequestOptions);
1420
+ }
1421
+ /**
1422
+ * Embeds the provided content.
1423
+ *
1424
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
1425
+ * take precedence over the {@link RequestOptions} values provided to
1426
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
1427
+ */
1428
+ async embedContent(request, requestOptions = {}) {
1429
+ const formattedParams = formatEmbedContentInput(request);
1430
+ const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
1431
+ return embedContent(this.apiKey, this.model, formattedParams, generativeModelRequestOptions);
1432
+ }
1433
+ /**
1434
+ * Embeds an array of {@link EmbedContentRequest}s.
1435
+ *
1436
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
1437
+ * take precedence over the {@link RequestOptions} values provided to
1438
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
1439
+ */
1440
+ async batchEmbedContents(batchEmbedContentRequest, requestOptions = {}) {
1441
+ const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
1442
+ return batchEmbedContents(this.apiKey, this.model, batchEmbedContentRequest, generativeModelRequestOptions);
1443
+ }
1444
+ }
1445
+
1446
+ /**
1447
+ * @license
1448
+ * Copyright 2024 Google LLC
1449
+ *
1450
+ * Licensed under the Apache License, Version 2.0 (the "License");
1451
+ * you may not use this file except in compliance with the License.
1452
+ * You may obtain a copy of the License at
1453
+ *
1454
+ * http://www.apache.org/licenses/LICENSE-2.0
1455
+ *
1456
+ * Unless required by applicable law or agreed to in writing, software
1457
+ * distributed under the License is distributed on an "AS IS" BASIS,
1458
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1459
+ * See the License for the specific language governing permissions and
1460
+ * limitations under the License.
1461
+ */
1462
+ /**
1463
+ * Top-level class for this SDK
1464
+ * @public
1465
+ */
1466
+ class GoogleGenerativeAI {
1467
+ constructor(apiKey) {
1468
+ this.apiKey = apiKey;
1469
+ }
1470
+ /**
1471
+ * Gets a {@link GenerativeModel} instance for the provided model name.
1472
+ */
1473
+ getGenerativeModel(modelParams, requestOptions) {
1474
+ if (!modelParams.model) {
1475
+ throw new GoogleGenerativeAIError(`Must provide a model name. ` +
1476
+ `Example: genai.getGenerativeModel({ model: 'my-model-name' })`);
1477
+ }
1478
+ return new GenerativeModel(this.apiKey, modelParams, requestOptions);
1479
+ }
1480
+ /**
1481
+ * Creates a {@link GenerativeModel} instance from provided content cache.
1482
+ */
1483
+ getGenerativeModelFromCachedContent(cachedContent, modelParams, requestOptions) {
1484
+ if (!cachedContent.name) {
1485
+ throw new GoogleGenerativeAIRequestInputError("Cached content must contain a `name` field.");
1486
+ }
1487
+ if (!cachedContent.model) {
1488
+ throw new GoogleGenerativeAIRequestInputError("Cached content must contain a `model` field.");
1489
+ }
1490
+ /**
1491
+ * Not checking tools and toolConfig for now as it would require a deep
1492
+ * equality comparison and isn't likely to be a common case.
1493
+ */
1494
+ const disallowedDuplicates = ["model", "systemInstruction"];
1495
+ for (const key of disallowedDuplicates) {
1496
+ if ((modelParams === null || modelParams === void 0 ? void 0 : modelParams[key]) &&
1497
+ cachedContent[key] &&
1498
+ (modelParams === null || modelParams === void 0 ? void 0 : modelParams[key]) !== cachedContent[key]) {
1499
+ if (key === "model") {
1500
+ const modelParamsComp = modelParams.model.startsWith("models/")
1501
+ ? modelParams.model.replace("models/", "")
1502
+ : modelParams.model;
1503
+ const cachedContentComp = cachedContent.model.startsWith("models/")
1504
+ ? cachedContent.model.replace("models/", "")
1505
+ : cachedContent.model;
1506
+ if (modelParamsComp === cachedContentComp) {
1507
+ continue;
1508
+ }
1509
+ }
1510
+ throw new GoogleGenerativeAIRequestInputError(`Different value for "${key}" specified in modelParams` +
1511
+ ` (${modelParams[key]}) and cachedContent (${cachedContent[key]})`);
1512
+ }
1513
+ }
1514
+ const modelParamsFromCache = Object.assign(Object.assign({}, modelParams), { model: cachedContent.model, tools: cachedContent.tools, toolConfig: cachedContent.toolConfig, systemInstruction: cachedContent.systemInstruction, cachedContent });
1515
+ return new GenerativeModel(this.apiKey, modelParamsFromCache, requestOptions);
1516
+ }
1517
+ }
1518
+
1519
+ export { BlockReason, ChatSession, DynamicRetrievalMode, ExecutableCodeLanguage, FinishReason, FunctionCallingMode, GenerativeModel, GoogleGenerativeAI, GoogleGenerativeAIAbortError, GoogleGenerativeAIError, GoogleGenerativeAIFetchError, GoogleGenerativeAIRequestInputError, GoogleGenerativeAIResponseError, HarmBlockThreshold, HarmCategory, HarmProbability, Outcome, POSSIBLE_ROLES, SchemaType, TaskType };
1520
+ //# sourceMappingURL=index.mjs.map
backend-old/node_modules/@google/generative-ai/dist/index.mjs.map ADDED
@@ -0,0 +1 @@
 
 
1
+ {"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
backend-old/node_modules/@google/generative-ai/dist/scripts/check-format.d.ts ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2023 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ export {};
backend-old/node_modules/@google/generative-ai/dist/scripts/format-patterns.d.ts ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2024 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ export declare const formatPatterns: string[];
18
+ export declare function getFormatPatternsString(): string;
backend-old/node_modules/@google/generative-ai/dist/scripts/license.d.ts ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2023 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ export declare function doLicense(write: boolean): Promise<boolean>;
backend-old/node_modules/@google/generative-ai/dist/scripts/run-format.d.ts ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2023 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ export {};
backend-old/node_modules/@google/generative-ai/dist/server/index.js ADDED
@@ -0,0 +1,838 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ var fs = require('fs');
4
+
5
+ /**
6
+ * @license
7
+ * Copyright 2024 Google LLC
8
+ *
9
+ * Licensed under the Apache License, Version 2.0 (the "License");
10
+ * you may not use this file except in compliance with the License.
11
+ * You may obtain a copy of the License at
12
+ *
13
+ * http://www.apache.org/licenses/LICENSE-2.0
14
+ *
15
+ * Unless required by applicable law or agreed to in writing, software
16
+ * distributed under the License is distributed on an "AS IS" BASIS,
17
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ * See the License for the specific language governing permissions and
19
+ * limitations under the License.
20
+ */
21
+ /**
22
+ * Basic error type for this SDK.
23
+ * @public
24
+ */
25
+ class GoogleGenerativeAIError extends Error {
26
+ constructor(message) {
27
+ super(`[GoogleGenerativeAI Error]: ${message}`);
28
+ }
29
+ }
30
+ /**
31
+ * Error class covering HTTP errors when calling the server. Includes HTTP
32
+ * status, statusText, and optional details, if provided in the server response.
33
+ * @public
34
+ */
35
+ class GoogleGenerativeAIFetchError extends GoogleGenerativeAIError {
36
+ constructor(message, status, statusText, errorDetails) {
37
+ super(message);
38
+ this.status = status;
39
+ this.statusText = statusText;
40
+ this.errorDetails = errorDetails;
41
+ }
42
+ }
43
+ /**
44
+ * Errors in the contents of a request originating from user input.
45
+ * @public
46
+ */
47
+ class GoogleGenerativeAIRequestInputError extends GoogleGenerativeAIError {
48
+ }
49
+ /**
50
+ * Error thrown when a request is aborted, either due to a timeout or
51
+ * intentional cancellation by the user.
52
+ * @public
53
+ */
54
+ class GoogleGenerativeAIAbortError extends GoogleGenerativeAIError {
55
+ }
56
+
57
+ /**
58
+ * @license
59
+ * Copyright 2024 Google LLC
60
+ *
61
+ * Licensed under the Apache License, Version 2.0 (the "License");
62
+ * you may not use this file except in compliance with the License.
63
+ * You may obtain a copy of the License at
64
+ *
65
+ * http://www.apache.org/licenses/LICENSE-2.0
66
+ *
67
+ * Unless required by applicable law or agreed to in writing, software
68
+ * distributed under the License is distributed on an "AS IS" BASIS,
69
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
70
+ * See the License for the specific language governing permissions and
71
+ * limitations under the License.
72
+ */
73
+ const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com";
74
+ const DEFAULT_API_VERSION = "v1beta";
75
+ /**
76
+ * We can't `require` package.json if this runs on web. We will use rollup to
77
+ * swap in the version number here at build time.
78
+ */
79
+ const PACKAGE_VERSION = "0.24.1";
80
+ const PACKAGE_LOG_HEADER = "genai-js";
81
+ var Task;
82
+ (function (Task) {
83
+ Task["GENERATE_CONTENT"] = "generateContent";
84
+ Task["STREAM_GENERATE_CONTENT"] = "streamGenerateContent";
85
+ Task["COUNT_TOKENS"] = "countTokens";
86
+ Task["EMBED_CONTENT"] = "embedContent";
87
+ Task["BATCH_EMBED_CONTENTS"] = "batchEmbedContents";
88
+ })(Task || (Task = {}));
89
+ /**
90
+ * Simple, but may become more complex if we add more versions to log.
91
+ */
92
+ function getClientHeaders(requestOptions) {
93
+ const clientHeaders = [];
94
+ if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.apiClient) {
95
+ clientHeaders.push(requestOptions.apiClient);
96
+ }
97
+ clientHeaders.push(`${PACKAGE_LOG_HEADER}/${PACKAGE_VERSION}`);
98
+ return clientHeaders.join(" ");
99
+ }
100
+ async function makeRequest(url, fetchOptions, fetchFn = fetch) {
101
+ let response;
102
+ try {
103
+ response = await fetchFn(url, fetchOptions);
104
+ }
105
+ catch (e) {
106
+ handleResponseError(e, url);
107
+ }
108
+ if (!response.ok) {
109
+ await handleResponseNotOk(response, url);
110
+ }
111
+ return response;
112
+ }
113
+ function handleResponseError(e, url) {
114
+ let err = e;
115
+ if (err.name === "AbortError") {
116
+ err = new GoogleGenerativeAIAbortError(`Request aborted when fetching ${url.toString()}: ${e.message}`);
117
+ err.stack = e.stack;
118
+ }
119
+ else if (!(e instanceof GoogleGenerativeAIFetchError ||
120
+ e instanceof GoogleGenerativeAIRequestInputError)) {
121
+ err = new GoogleGenerativeAIError(`Error fetching from ${url.toString()}: ${e.message}`);
122
+ err.stack = e.stack;
123
+ }
124
+ throw err;
125
+ }
126
+ async function handleResponseNotOk(response, url) {
127
+ let message = "";
128
+ let errorDetails;
129
+ try {
130
+ const json = await response.json();
131
+ message = json.error.message;
132
+ if (json.error.details) {
133
+ message += ` ${JSON.stringify(json.error.details)}`;
134
+ errorDetails = json.error.details;
135
+ }
136
+ }
137
+ catch (e) {
138
+ // ignored
139
+ }
140
+ throw new GoogleGenerativeAIFetchError(`Error fetching from ${url.toString()}: [${response.status} ${response.statusText}] ${message}`, response.status, response.statusText, errorDetails);
141
+ }
142
+
143
+ /**
144
+ * @license
145
+ * Copyright 2024 Google LLC
146
+ *
147
+ * Licensed under the Apache License, Version 2.0 (the "License");
148
+ * you may not use this file except in compliance with the License.
149
+ * You may obtain a copy of the License at
150
+ *
151
+ * http://www.apache.org/licenses/LICENSE-2.0
152
+ *
153
+ * Unless required by applicable law or agreed to in writing, software
154
+ * distributed under the License is distributed on an "AS IS" BASIS,
155
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
156
+ * See the License for the specific language governing permissions and
157
+ * limitations under the License.
158
+ */
159
+ var RpcTask;
160
+ (function (RpcTask) {
161
+ RpcTask["UPLOAD"] = "upload";
162
+ RpcTask["LIST"] = "list";
163
+ RpcTask["GET"] = "get";
164
+ RpcTask["DELETE"] = "delete";
165
+ RpcTask["UPDATE"] = "update";
166
+ RpcTask["CREATE"] = "create";
167
+ })(RpcTask || (RpcTask = {}));
168
+
169
+ /**
170
+ * @license
171
+ * Copyright 2024 Google LLC
172
+ *
173
+ * Licensed under the Apache License, Version 2.0 (the "License");
174
+ * you may not use this file except in compliance with the License.
175
+ * You may obtain a copy of the License at
176
+ *
177
+ * http://www.apache.org/licenses/LICENSE-2.0
178
+ *
179
+ * Unless required by applicable law or agreed to in writing, software
180
+ * distributed under the License is distributed on an "AS IS" BASIS,
181
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
182
+ * See the License for the specific language governing permissions and
183
+ * limitations under the License.
184
+ */
185
+ const taskToMethod = {
186
+ [RpcTask.UPLOAD]: "POST",
187
+ [RpcTask.LIST]: "GET",
188
+ [RpcTask.GET]: "GET",
189
+ [RpcTask.DELETE]: "DELETE",
190
+ [RpcTask.UPDATE]: "PATCH",
191
+ [RpcTask.CREATE]: "POST",
192
+ };
193
+ class ServerRequestUrl {
194
+ constructor(task, apiKey, requestOptions) {
195
+ this.task = task;
196
+ this.apiKey = apiKey;
197
+ this.requestOptions = requestOptions;
198
+ }
199
+ appendPath(path) {
200
+ this._url.pathname = this._url.pathname + `/${path}`;
201
+ }
202
+ appendParam(key, value) {
203
+ this._url.searchParams.append(key, value);
204
+ }
205
+ toString() {
206
+ return this._url.toString();
207
+ }
208
+ }
209
+ class CachedContentUrl extends ServerRequestUrl {
210
+ constructor(task, apiKey, requestOptions) {
211
+ var _a, _b;
212
+ super(task, apiKey, requestOptions);
213
+ this.task = task;
214
+ this.apiKey = apiKey;
215
+ this.requestOptions = requestOptions;
216
+ const apiVersion = ((_a = this.requestOptions) === null || _a === void 0 ? void 0 : _a.apiVersion) || DEFAULT_API_VERSION;
217
+ const baseUrl = ((_b = this.requestOptions) === null || _b === void 0 ? void 0 : _b.baseUrl) || DEFAULT_BASE_URL;
218
+ let initialUrl = baseUrl;
219
+ initialUrl += `/${apiVersion}/cachedContents`;
220
+ this._url = new URL(initialUrl);
221
+ }
222
+ }
223
+ class FilesRequestUrl extends ServerRequestUrl {
224
+ constructor(task, apiKey, requestOptions) {
225
+ var _a, _b;
226
+ super(task, apiKey, requestOptions);
227
+ this.task = task;
228
+ this.apiKey = apiKey;
229
+ this.requestOptions = requestOptions;
230
+ const apiVersion = ((_a = this.requestOptions) === null || _a === void 0 ? void 0 : _a.apiVersion) || DEFAULT_API_VERSION;
231
+ const baseUrl = ((_b = this.requestOptions) === null || _b === void 0 ? void 0 : _b.baseUrl) || DEFAULT_BASE_URL;
232
+ let initialUrl = baseUrl;
233
+ if (this.task === RpcTask.UPLOAD) {
234
+ initialUrl += `/upload`;
235
+ }
236
+ initialUrl += `/${apiVersion}/files`;
237
+ this._url = new URL(initialUrl);
238
+ }
239
+ }
240
+ function getHeaders(url) {
241
+ var _a;
242
+ const headers = new Headers();
243
+ headers.append("x-goog-api-client", getClientHeaders(url.requestOptions));
244
+ headers.append("x-goog-api-key", url.apiKey);
245
+ let customHeaders = (_a = url.requestOptions) === null || _a === void 0 ? void 0 : _a.customHeaders;
246
+ if (customHeaders) {
247
+ if (!(customHeaders instanceof Headers)) {
248
+ try {
249
+ customHeaders = new Headers(customHeaders);
250
+ }
251
+ catch (e) {
252
+ throw new GoogleGenerativeAIRequestInputError(`unable to convert customHeaders value ${JSON.stringify(customHeaders)} to Headers: ${e.message}`);
253
+ }
254
+ }
255
+ for (const [headerName, headerValue] of customHeaders.entries()) {
256
+ if (headerName === "x-goog-api-key") {
257
+ throw new GoogleGenerativeAIRequestInputError(`Cannot set reserved header name ${headerName}`);
258
+ }
259
+ else if (headerName === "x-goog-api-client") {
260
+ throw new GoogleGenerativeAIRequestInputError(`Header name ${headerName} can only be set using the apiClient field`);
261
+ }
262
+ headers.append(headerName, headerValue);
263
+ }
264
+ }
265
+ return headers;
266
+ }
267
+ async function makeServerRequest(url, headers, body, fetchFn = fetch) {
268
+ const requestInit = {
269
+ method: taskToMethod[url.task],
270
+ headers,
271
+ };
272
+ if (body) {
273
+ requestInit.body = body;
274
+ }
275
+ const signal = getSignal(url.requestOptions);
276
+ if (signal) {
277
+ requestInit.signal = signal;
278
+ }
279
+ return makeRequest(url.toString(), requestInit, fetchFn);
280
+ }
281
+ /**
282
+ * Create an AbortSignal based on the timeout and signal in the
283
+ * RequestOptions.
284
+ */
285
+ function getSignal(requestOptions) {
286
+ if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.signal) !== undefined || (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeout) >= 0) {
287
+ const controller = new AbortController();
288
+ if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeout) >= 0) {
289
+ setTimeout(() => controller.abort(), requestOptions.timeout);
290
+ }
291
+ if (requestOptions.signal) {
292
+ requestOptions.signal.addEventListener("abort", () => {
293
+ controller.abort();
294
+ });
295
+ }
296
+ return controller.signal;
297
+ }
298
+ }
299
+
300
+ /**
301
+ * @license
302
+ * Copyright 2024 Google LLC
303
+ *
304
+ * Licensed under the Apache License, Version 2.0 (the "License");
305
+ * you may not use this file except in compliance with the License.
306
+ * You may obtain a copy of the License at
307
+ *
308
+ * http://www.apache.org/licenses/LICENSE-2.0
309
+ *
310
+ * Unless required by applicable law or agreed to in writing, software
311
+ * distributed under the License is distributed on an "AS IS" BASIS,
312
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
313
+ * See the License for the specific language governing permissions and
314
+ * limitations under the License.
315
+ */
316
+ /**
317
+ * Class for managing GoogleAI file uploads.
318
+ * @public
319
+ */
320
+ class GoogleAIFileManager {
321
+ constructor(apiKey, _requestOptions = {}) {
322
+ this.apiKey = apiKey;
323
+ this._requestOptions = _requestOptions;
324
+ }
325
+ /**
326
+ * Upload a file.
327
+ */
328
+ async uploadFile(fileData, fileMetadata) {
329
+ const file = fileData instanceof Buffer ? fileData : fs.readFileSync(fileData);
330
+ const url = new FilesRequestUrl(RpcTask.UPLOAD, this.apiKey, this._requestOptions);
331
+ const uploadHeaders = getHeaders(url);
332
+ const boundary = generateBoundary();
333
+ uploadHeaders.append("X-Goog-Upload-Protocol", "multipart");
334
+ uploadHeaders.append("Content-Type", `multipart/related; boundary=${boundary}`);
335
+ const uploadMetadata = getUploadMetadata(fileMetadata);
336
+ // Multipart formatting code taken from @firebase/storage
337
+ const metadataString = JSON.stringify({ file: uploadMetadata });
338
+ const preBlobPart = "--" +
339
+ boundary +
340
+ "\r\n" +
341
+ "Content-Type: application/json; charset=utf-8\r\n\r\n" +
342
+ metadataString +
343
+ "\r\n--" +
344
+ boundary +
345
+ "\r\n" +
346
+ "Content-Type: " +
347
+ fileMetadata.mimeType +
348
+ "\r\n\r\n";
349
+ const postBlobPart = "\r\n--" + boundary + "--";
350
+ const blob = new Blob([preBlobPart, file, postBlobPart]);
351
+ const response = await makeServerRequest(url, uploadHeaders, blob);
352
+ return response.json();
353
+ }
354
+ /**
355
+ * List all uploaded files.
356
+ *
357
+ * Any fields set in the optional {@link SingleRequestOptions} parameter will take
358
+ * precedence over the {@link RequestOptions} values provided at the time of the
359
+ * {@link GoogleAIFileManager} initialization.
360
+ */
361
+ async listFiles(listParams, requestOptions = {}) {
362
+ const filesRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
363
+ const url = new FilesRequestUrl(RpcTask.LIST, this.apiKey, filesRequestOptions);
364
+ if (listParams === null || listParams === void 0 ? void 0 : listParams.pageSize) {
365
+ url.appendParam("pageSize", listParams.pageSize.toString());
366
+ }
367
+ if (listParams === null || listParams === void 0 ? void 0 : listParams.pageToken) {
368
+ url.appendParam("pageToken", listParams.pageToken);
369
+ }
370
+ const uploadHeaders = getHeaders(url);
371
+ const response = await makeServerRequest(url, uploadHeaders);
372
+ return response.json();
373
+ }
374
+ /**
375
+ * Get metadata for file with given ID.
376
+ *
377
+ * Any fields set in the optional {@link SingleRequestOptions} parameter will take
378
+ * precedence over the {@link RequestOptions} values provided at the time of the
379
+ * {@link GoogleAIFileManager} initialization.
380
+ */
381
+ async getFile(fileId, requestOptions = {}) {
382
+ const filesRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
383
+ const url = new FilesRequestUrl(RpcTask.GET, this.apiKey, filesRequestOptions);
384
+ url.appendPath(parseFileId(fileId));
385
+ const uploadHeaders = getHeaders(url);
386
+ const response = await makeServerRequest(url, uploadHeaders);
387
+ return response.json();
388
+ }
389
+ /**
390
+ * Delete file with given ID.
391
+ */
392
+ async deleteFile(fileId) {
393
+ const url = new FilesRequestUrl(RpcTask.DELETE, this.apiKey, this._requestOptions);
394
+ url.appendPath(parseFileId(fileId));
395
+ const uploadHeaders = getHeaders(url);
396
+ await makeServerRequest(url, uploadHeaders);
397
+ }
398
+ }
399
+ /**
400
+ * If fileId is prepended with "files/", remove prefix
401
+ */
402
+ function parseFileId(fileId) {
403
+ if (fileId.startsWith("files/")) {
404
+ return fileId.split("files/")[1];
405
+ }
406
+ if (!fileId) {
407
+ throw new GoogleGenerativeAIError(`Invalid fileId ${fileId}. ` +
408
+ `Must be in the format "files/filename" or "filename"`);
409
+ }
410
+ return fileId;
411
+ }
412
+ function generateBoundary() {
413
+ let str = "";
414
+ for (let i = 0; i < 2; i++) {
415
+ str = str + Math.random().toString().slice(2);
416
+ }
417
+ return str;
418
+ }
419
+ function getUploadMetadata(inputMetadata) {
420
+ if (!inputMetadata.mimeType) {
421
+ throw new GoogleGenerativeAIRequestInputError("Must provide a mimeType.");
422
+ }
423
+ const uploadMetadata = {
424
+ mimeType: inputMetadata.mimeType,
425
+ displayName: inputMetadata.displayName,
426
+ };
427
+ if (inputMetadata.name) {
428
+ uploadMetadata.name = inputMetadata.name.includes("/")
429
+ ? inputMetadata.name
430
+ : `files/${inputMetadata.name}`;
431
+ }
432
+ return uploadMetadata;
433
+ }
434
+
435
+ /**
436
+ * @license
437
+ * Copyright 2024 Google LLC
438
+ *
439
+ * Licensed under the Apache License, Version 2.0 (the "License");
440
+ * you may not use this file except in compliance with the License.
441
+ * You may obtain a copy of the License at
442
+ *
443
+ * http://www.apache.org/licenses/LICENSE-2.0
444
+ *
445
+ * Unless required by applicable law or agreed to in writing, software
446
+ * distributed under the License is distributed on an "AS IS" BASIS,
447
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
448
+ * See the License for the specific language governing permissions and
449
+ * limitations under the License.
450
+ */
451
+ function formatSystemInstruction(input) {
452
+ // null or undefined
453
+ if (input == null) {
454
+ return undefined;
455
+ }
456
+ else if (typeof input === "string") {
457
+ return { role: "system", parts: [{ text: input }] };
458
+ }
459
+ else if (input.text) {
460
+ return { role: "system", parts: [input] };
461
+ }
462
+ else if (input.parts) {
463
+ if (!input.role) {
464
+ return { role: "system", parts: input.parts };
465
+ }
466
+ else {
467
+ return input;
468
+ }
469
+ }
470
+ }
471
+
472
+ /**
473
+ * @license
474
+ * Copyright 2024 Google LLC
475
+ *
476
+ * Licensed under the Apache License, Version 2.0 (the "License");
477
+ * you may not use this file except in compliance with the License.
478
+ * You may obtain a copy of the License at
479
+ *
480
+ * http://www.apache.org/licenses/LICENSE-2.0
481
+ *
482
+ * Unless required by applicable law or agreed to in writing, software
483
+ * distributed under the License is distributed on an "AS IS" BASIS,
484
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
485
+ * See the License for the specific language governing permissions and
486
+ * limitations under the License.
487
+ */
488
+ /**
489
+ * Class for managing GoogleAI content caches.
490
+ * @public
491
+ */
492
+ class GoogleAICacheManager {
493
+ constructor(apiKey, _requestOptions) {
494
+ this.apiKey = apiKey;
495
+ this._requestOptions = _requestOptions;
496
+ }
497
+ /**
498
+ * Upload a new content cache
499
+ */
500
+ async create(createOptions) {
501
+ const newCachedContent = Object.assign({}, createOptions);
502
+ if (createOptions.ttlSeconds) {
503
+ if (createOptions.expireTime) {
504
+ throw new GoogleGenerativeAIRequestInputError("You cannot specify both `ttlSeconds` and `expireTime` when creating" +
505
+ " a content cache. You must choose one.");
506
+ }
507
+ newCachedContent.ttl = createOptions.ttlSeconds.toString() + "s";
508
+ delete newCachedContent.ttlSeconds;
509
+ }
510
+ if (createOptions.systemInstruction) {
511
+ newCachedContent.systemInstruction = formatSystemInstruction(createOptions.systemInstruction);
512
+ }
513
+ if (!newCachedContent.model) {
514
+ throw new GoogleGenerativeAIRequestInputError("Cached content must contain a `model` field.");
515
+ }
516
+ if (!newCachedContent.model.includes("/")) {
517
+ // If path is not included, assume it's a non-tuned model.
518
+ newCachedContent.model = `models/${newCachedContent.model}`;
519
+ }
520
+ const url = new CachedContentUrl(RpcTask.CREATE, this.apiKey, this._requestOptions);
521
+ const headers = getHeaders(url);
522
+ const response = await makeServerRequest(url, headers, JSON.stringify(newCachedContent));
523
+ return response.json();
524
+ }
525
+ /**
526
+ * List all uploaded content caches
527
+ */
528
+ async list(listParams) {
529
+ const url = new CachedContentUrl(RpcTask.LIST, this.apiKey, this._requestOptions);
530
+ if (listParams === null || listParams === void 0 ? void 0 : listParams.pageSize) {
531
+ url.appendParam("pageSize", listParams.pageSize.toString());
532
+ }
533
+ if (listParams === null || listParams === void 0 ? void 0 : listParams.pageToken) {
534
+ url.appendParam("pageToken", listParams.pageToken);
535
+ }
536
+ const headers = getHeaders(url);
537
+ const response = await makeServerRequest(url, headers);
538
+ return response.json();
539
+ }
540
+ /**
541
+ * Get a content cache
542
+ */
543
+ async get(name) {
544
+ const url = new CachedContentUrl(RpcTask.GET, this.apiKey, this._requestOptions);
545
+ url.appendPath(parseCacheName(name));
546
+ const headers = getHeaders(url);
547
+ const response = await makeServerRequest(url, headers);
548
+ return response.json();
549
+ }
550
+ /**
551
+ * Update an existing content cache
552
+ */
553
+ async update(name, updateParams) {
554
+ const url = new CachedContentUrl(RpcTask.UPDATE, this.apiKey, this._requestOptions);
555
+ url.appendPath(parseCacheName(name));
556
+ const headers = getHeaders(url);
557
+ const formattedCachedContent = Object.assign({}, updateParams.cachedContent);
558
+ if (updateParams.cachedContent.ttlSeconds) {
559
+ formattedCachedContent.ttl =
560
+ updateParams.cachedContent.ttlSeconds.toString() + "s";
561
+ delete formattedCachedContent.ttlSeconds;
562
+ }
563
+ if (updateParams.updateMask) {
564
+ url.appendParam("update_mask", updateParams.updateMask.map((prop) => camelToSnake(prop)).join(","));
565
+ }
566
+ const response = await makeServerRequest(url, headers, JSON.stringify(formattedCachedContent));
567
+ return response.json();
568
+ }
569
+ /**
570
+ * Delete content cache with given name
571
+ */
572
+ async delete(name) {
573
+ const url = new CachedContentUrl(RpcTask.DELETE, this.apiKey, this._requestOptions);
574
+ url.appendPath(parseCacheName(name));
575
+ const headers = getHeaders(url);
576
+ await makeServerRequest(url, headers);
577
+ }
578
+ }
579
+ /**
580
+ * If cache name is prepended with "cachedContents/", remove prefix
581
+ */
582
+ function parseCacheName(name) {
583
+ if (name.startsWith("cachedContents/")) {
584
+ return name.split("cachedContents/")[1];
585
+ }
586
+ if (!name) {
587
+ throw new GoogleGenerativeAIError(`Invalid name ${name}. ` +
588
+ `Must be in the format "cachedContents/name" or "name"`);
589
+ }
590
+ return name;
591
+ }
592
+ function camelToSnake(str) {
593
+ return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
594
+ }
595
+
596
+ /**
597
+ * Processing state of the `File`.
598
+ * @public
599
+ */
600
+ exports.FileState = void 0;
601
+ (function (FileState) {
602
+ // The default value. This value is used if the state is omitted.
603
+ FileState["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED";
604
+ // File is being processed and cannot be used for inference yet.
605
+ FileState["PROCESSING"] = "PROCESSING";
606
+ // File is processed and available for inference.
607
+ FileState["ACTIVE"] = "ACTIVE";
608
+ // File failed processing.
609
+ FileState["FAILED"] = "FAILED";
610
+ })(exports.FileState || (exports.FileState = {}));
611
+
612
+ /**
613
+ * Contains the list of OpenAPI data types
614
+ * as defined by https://swagger.io/docs/specification/data-models/data-types/
615
+ * @public
616
+ */
617
+ exports.SchemaType = void 0;
618
+ (function (SchemaType) {
619
+ /** String type. */
620
+ SchemaType["STRING"] = "string";
621
+ /** Number type. */
622
+ SchemaType["NUMBER"] = "number";
623
+ /** Integer type. */
624
+ SchemaType["INTEGER"] = "integer";
625
+ /** Boolean type. */
626
+ SchemaType["BOOLEAN"] = "boolean";
627
+ /** Array type. */
628
+ SchemaType["ARRAY"] = "array";
629
+ /** Object type. */
630
+ SchemaType["OBJECT"] = "object";
631
+ })(exports.SchemaType || (exports.SchemaType = {}));
632
+
633
+ /**
634
+ * @license
635
+ * Copyright 2024 Google LLC
636
+ *
637
+ * Licensed under the Apache License, Version 2.0 (the "License");
638
+ * you may not use this file except in compliance with the License.
639
+ * You may obtain a copy of the License at
640
+ *
641
+ * http://www.apache.org/licenses/LICENSE-2.0
642
+ *
643
+ * Unless required by applicable law or agreed to in writing, software
644
+ * distributed under the License is distributed on an "AS IS" BASIS,
645
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
646
+ * See the License for the specific language governing permissions and
647
+ * limitations under the License.
648
+ */
649
+ /**
650
+ * @public
651
+ */
652
+ exports.ExecutableCodeLanguage = void 0;
653
+ (function (ExecutableCodeLanguage) {
654
+ ExecutableCodeLanguage["LANGUAGE_UNSPECIFIED"] = "language_unspecified";
655
+ ExecutableCodeLanguage["PYTHON"] = "python";
656
+ })(exports.ExecutableCodeLanguage || (exports.ExecutableCodeLanguage = {}));
657
+ /**
658
+ * Possible outcomes of code execution.
659
+ * @public
660
+ */
661
+ exports.Outcome = void 0;
662
+ (function (Outcome) {
663
+ /**
664
+ * Unspecified status. This value should not be used.
665
+ */
666
+ Outcome["OUTCOME_UNSPECIFIED"] = "outcome_unspecified";
667
+ /**
668
+ * Code execution completed successfully.
669
+ */
670
+ Outcome["OUTCOME_OK"] = "outcome_ok";
671
+ /**
672
+ * Code execution finished but with a failure. `stderr` should contain the
673
+ * reason.
674
+ */
675
+ Outcome["OUTCOME_FAILED"] = "outcome_failed";
676
+ /**
677
+ * Code execution ran for too long, and was cancelled. There may or may not
678
+ * be a partial output present.
679
+ */
680
+ Outcome["OUTCOME_DEADLINE_EXCEEDED"] = "outcome_deadline_exceeded";
681
+ })(exports.Outcome || (exports.Outcome = {}));
682
+
683
+ /**
684
+ * @license
685
+ * Copyright 2024 Google LLC
686
+ *
687
+ * Licensed under the Apache License, Version 2.0 (the "License");
688
+ * you may not use this file except in compliance with the License.
689
+ * You may obtain a copy of the License at
690
+ *
691
+ * http://www.apache.org/licenses/LICENSE-2.0
692
+ *
693
+ * Unless required by applicable law or agreed to in writing, software
694
+ * distributed under the License is distributed on an "AS IS" BASIS,
695
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
696
+ * See the License for the specific language governing permissions and
697
+ * limitations under the License.
698
+ */
699
+ /**
700
+ * Possible roles.
701
+ * @public
702
+ */
703
+ /**
704
+ * Harm categories that would cause prompts or candidates to be blocked.
705
+ * @public
706
+ */
707
+ var HarmCategory;
708
+ (function (HarmCategory) {
709
+ HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED";
710
+ HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH";
711
+ HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT";
712
+ HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT";
713
+ HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT";
714
+ HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY";
715
+ })(HarmCategory || (HarmCategory = {}));
716
+ /**
717
+ * Threshold above which a prompt or candidate will be blocked.
718
+ * @public
719
+ */
720
+ var HarmBlockThreshold;
721
+ (function (HarmBlockThreshold) {
722
+ /** Threshold is unspecified. */
723
+ HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED";
724
+ /** Content with NEGLIGIBLE will be allowed. */
725
+ HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE";
726
+ /** Content with NEGLIGIBLE and LOW will be allowed. */
727
+ HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE";
728
+ /** Content with NEGLIGIBLE, LOW, and MEDIUM will be allowed. */
729
+ HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH";
730
+ /** All content will be allowed. */
731
+ HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE";
732
+ })(HarmBlockThreshold || (HarmBlockThreshold = {}));
733
+ /**
734
+ * Probability that a prompt or candidate matches a harm category.
735
+ * @public
736
+ */
737
+ var HarmProbability;
738
+ (function (HarmProbability) {
739
+ /** Probability is unspecified. */
740
+ HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED";
741
+ /** Content has a negligible chance of being unsafe. */
742
+ HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE";
743
+ /** Content has a low chance of being unsafe. */
744
+ HarmProbability["LOW"] = "LOW";
745
+ /** Content has a medium chance of being unsafe. */
746
+ HarmProbability["MEDIUM"] = "MEDIUM";
747
+ /** Content has a high chance of being unsafe. */
748
+ HarmProbability["HIGH"] = "HIGH";
749
+ })(HarmProbability || (HarmProbability = {}));
750
+ /**
751
+ * Reason that a prompt was blocked.
752
+ * @public
753
+ */
754
+ var BlockReason;
755
+ (function (BlockReason) {
756
+ // A blocked reason was not specified.
757
+ BlockReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED";
758
+ // Content was blocked by safety settings.
759
+ BlockReason["SAFETY"] = "SAFETY";
760
+ // Content was blocked, but the reason is uncategorized.
761
+ BlockReason["OTHER"] = "OTHER";
762
+ })(BlockReason || (BlockReason = {}));
763
+ /**
764
+ * Reason that a candidate finished.
765
+ * @public
766
+ */
767
+ var FinishReason;
768
+ (function (FinishReason) {
769
+ // Default value. This value is unused.
770
+ FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED";
771
+ // Natural stop point of the model or provided stop sequence.
772
+ FinishReason["STOP"] = "STOP";
773
+ // The maximum number of tokens as specified in the request was reached.
774
+ FinishReason["MAX_TOKENS"] = "MAX_TOKENS";
775
+ // The candidate content was flagged for safety reasons.
776
+ FinishReason["SAFETY"] = "SAFETY";
777
+ // The candidate content was flagged for recitation reasons.
778
+ FinishReason["RECITATION"] = "RECITATION";
779
+ // The candidate content was flagged for using an unsupported language.
780
+ FinishReason["LANGUAGE"] = "LANGUAGE";
781
+ // Token generation stopped because the content contains forbidden terms.
782
+ FinishReason["BLOCKLIST"] = "BLOCKLIST";
783
+ // Token generation stopped for potentially containing prohibited content.
784
+ FinishReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT";
785
+ // Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII).
786
+ FinishReason["SPII"] = "SPII";
787
+ // The function call generated by the model is invalid.
788
+ FinishReason["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL";
789
+ // Unknown reason.
790
+ FinishReason["OTHER"] = "OTHER";
791
+ })(FinishReason || (FinishReason = {}));
792
+ /**
793
+ * Task type for embedding content.
794
+ * @public
795
+ */
796
+ var TaskType;
797
+ (function (TaskType) {
798
+ TaskType["TASK_TYPE_UNSPECIFIED"] = "TASK_TYPE_UNSPECIFIED";
799
+ TaskType["RETRIEVAL_QUERY"] = "RETRIEVAL_QUERY";
800
+ TaskType["RETRIEVAL_DOCUMENT"] = "RETRIEVAL_DOCUMENT";
801
+ TaskType["SEMANTIC_SIMILARITY"] = "SEMANTIC_SIMILARITY";
802
+ TaskType["CLASSIFICATION"] = "CLASSIFICATION";
803
+ TaskType["CLUSTERING"] = "CLUSTERING";
804
+ })(TaskType || (TaskType = {}));
805
+ /**
806
+ * @public
807
+ */
808
+ exports.FunctionCallingMode = void 0;
809
+ (function (FunctionCallingMode) {
810
+ // Unspecified function calling mode. This value should not be used.
811
+ FunctionCallingMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
812
+ // Default model behavior, model decides to predict either a function call
813
+ // or a natural language repspose.
814
+ FunctionCallingMode["AUTO"] = "AUTO";
815
+ // Model is constrained to always predicting a function call only.
816
+ // If "allowed_function_names" are set, the predicted function call will be
817
+ // limited to any one of "allowed_function_names", else the predicted
818
+ // function call will be any one of the provided "function_declarations".
819
+ FunctionCallingMode["ANY"] = "ANY";
820
+ // Model will not predict any function call. Model behavior is same as when
821
+ // not passing any function declarations.
822
+ FunctionCallingMode["NONE"] = "NONE";
823
+ })(exports.FunctionCallingMode || (exports.FunctionCallingMode = {}));
824
+ /**
825
+ * The mode of the predictor to be used in dynamic retrieval.
826
+ * @public
827
+ */
828
+ var DynamicRetrievalMode;
829
+ (function (DynamicRetrievalMode) {
830
+ // Unspecified function calling mode. This value should not be used.
831
+ DynamicRetrievalMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
832
+ // Run retrieval only when system decides it is necessary.
833
+ DynamicRetrievalMode["MODE_DYNAMIC"] = "MODE_DYNAMIC";
834
+ })(DynamicRetrievalMode || (DynamicRetrievalMode = {}));
835
+
836
+ exports.GoogleAICacheManager = GoogleAICacheManager;
837
+ exports.GoogleAIFileManager = GoogleAIFileManager;
838
+ //# sourceMappingURL=index.js.map
backend-old/node_modules/@google/generative-ai/dist/server/index.js.map ADDED
@@ -0,0 +1 @@
 
 
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
backend-old/node_modules/@google/generative-ai/dist/server/index.mjs ADDED
@@ -0,0 +1,835 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { readFileSync } from 'fs';
2
+
3
+ /**
4
+ * @license
5
+ * Copyright 2024 Google LLC
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+ /**
20
+ * Basic error type for this SDK.
21
+ * @public
22
+ */
23
+ class GoogleGenerativeAIError extends Error {
24
+ constructor(message) {
25
+ super(`[GoogleGenerativeAI Error]: ${message}`);
26
+ }
27
+ }
28
+ /**
29
+ * Error class covering HTTP errors when calling the server. Includes HTTP
30
+ * status, statusText, and optional details, if provided in the server response.
31
+ * @public
32
+ */
33
+ class GoogleGenerativeAIFetchError extends GoogleGenerativeAIError {
34
+ constructor(message, status, statusText, errorDetails) {
35
+ super(message);
36
+ this.status = status;
37
+ this.statusText = statusText;
38
+ this.errorDetails = errorDetails;
39
+ }
40
+ }
41
+ /**
42
+ * Errors in the contents of a request originating from user input.
43
+ * @public
44
+ */
45
+ class GoogleGenerativeAIRequestInputError extends GoogleGenerativeAIError {
46
+ }
47
+ /**
48
+ * Error thrown when a request is aborted, either due to a timeout or
49
+ * intentional cancellation by the user.
50
+ * @public
51
+ */
52
+ class GoogleGenerativeAIAbortError extends GoogleGenerativeAIError {
53
+ }
54
+
55
+ /**
56
+ * @license
57
+ * Copyright 2024 Google LLC
58
+ *
59
+ * Licensed under the Apache License, Version 2.0 (the "License");
60
+ * you may not use this file except in compliance with the License.
61
+ * You may obtain a copy of the License at
62
+ *
63
+ * http://www.apache.org/licenses/LICENSE-2.0
64
+ *
65
+ * Unless required by applicable law or agreed to in writing, software
66
+ * distributed under the License is distributed on an "AS IS" BASIS,
67
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
68
+ * See the License for the specific language governing permissions and
69
+ * limitations under the License.
70
+ */
71
+ const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com";
72
+ const DEFAULT_API_VERSION = "v1beta";
73
+ /**
74
+ * We can't `require` package.json if this runs on web. We will use rollup to
75
+ * swap in the version number here at build time.
76
+ */
77
+ const PACKAGE_VERSION = "0.24.1";
78
+ const PACKAGE_LOG_HEADER = "genai-js";
79
+ var Task;
80
+ (function (Task) {
81
+ Task["GENERATE_CONTENT"] = "generateContent";
82
+ Task["STREAM_GENERATE_CONTENT"] = "streamGenerateContent";
83
+ Task["COUNT_TOKENS"] = "countTokens";
84
+ Task["EMBED_CONTENT"] = "embedContent";
85
+ Task["BATCH_EMBED_CONTENTS"] = "batchEmbedContents";
86
+ })(Task || (Task = {}));
87
+ /**
88
+ * Simple, but may become more complex if we add more versions to log.
89
+ */
90
+ function getClientHeaders(requestOptions) {
91
+ const clientHeaders = [];
92
+ if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.apiClient) {
93
+ clientHeaders.push(requestOptions.apiClient);
94
+ }
95
+ clientHeaders.push(`${PACKAGE_LOG_HEADER}/${PACKAGE_VERSION}`);
96
+ return clientHeaders.join(" ");
97
+ }
98
+ async function makeRequest(url, fetchOptions, fetchFn = fetch) {
99
+ let response;
100
+ try {
101
+ response = await fetchFn(url, fetchOptions);
102
+ }
103
+ catch (e) {
104
+ handleResponseError(e, url);
105
+ }
106
+ if (!response.ok) {
107
+ await handleResponseNotOk(response, url);
108
+ }
109
+ return response;
110
+ }
111
+ function handleResponseError(e, url) {
112
+ let err = e;
113
+ if (err.name === "AbortError") {
114
+ err = new GoogleGenerativeAIAbortError(`Request aborted when fetching ${url.toString()}: ${e.message}`);
115
+ err.stack = e.stack;
116
+ }
117
+ else if (!(e instanceof GoogleGenerativeAIFetchError ||
118
+ e instanceof GoogleGenerativeAIRequestInputError)) {
119
+ err = new GoogleGenerativeAIError(`Error fetching from ${url.toString()}: ${e.message}`);
120
+ err.stack = e.stack;
121
+ }
122
+ throw err;
123
+ }
124
+ async function handleResponseNotOk(response, url) {
125
+ let message = "";
126
+ let errorDetails;
127
+ try {
128
+ const json = await response.json();
129
+ message = json.error.message;
130
+ if (json.error.details) {
131
+ message += ` ${JSON.stringify(json.error.details)}`;
132
+ errorDetails = json.error.details;
133
+ }
134
+ }
135
+ catch (e) {
136
+ // ignored
137
+ }
138
+ throw new GoogleGenerativeAIFetchError(`Error fetching from ${url.toString()}: [${response.status} ${response.statusText}] ${message}`, response.status, response.statusText, errorDetails);
139
+ }
140
+
141
+ /**
142
+ * @license
143
+ * Copyright 2024 Google LLC
144
+ *
145
+ * Licensed under the Apache License, Version 2.0 (the "License");
146
+ * you may not use this file except in compliance with the License.
147
+ * You may obtain a copy of the License at
148
+ *
149
+ * http://www.apache.org/licenses/LICENSE-2.0
150
+ *
151
+ * Unless required by applicable law or agreed to in writing, software
152
+ * distributed under the License is distributed on an "AS IS" BASIS,
153
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
154
+ * See the License for the specific language governing permissions and
155
+ * limitations under the License.
156
+ */
157
+ var RpcTask;
158
+ (function (RpcTask) {
159
+ RpcTask["UPLOAD"] = "upload";
160
+ RpcTask["LIST"] = "list";
161
+ RpcTask["GET"] = "get";
162
+ RpcTask["DELETE"] = "delete";
163
+ RpcTask["UPDATE"] = "update";
164
+ RpcTask["CREATE"] = "create";
165
+ })(RpcTask || (RpcTask = {}));
166
+
167
+ /**
168
+ * @license
169
+ * Copyright 2024 Google LLC
170
+ *
171
+ * Licensed under the Apache License, Version 2.0 (the "License");
172
+ * you may not use this file except in compliance with the License.
173
+ * You may obtain a copy of the License at
174
+ *
175
+ * http://www.apache.org/licenses/LICENSE-2.0
176
+ *
177
+ * Unless required by applicable law or agreed to in writing, software
178
+ * distributed under the License is distributed on an "AS IS" BASIS,
179
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
180
+ * See the License for the specific language governing permissions and
181
+ * limitations under the License.
182
+ */
183
+ const taskToMethod = {
184
+ [RpcTask.UPLOAD]: "POST",
185
+ [RpcTask.LIST]: "GET",
186
+ [RpcTask.GET]: "GET",
187
+ [RpcTask.DELETE]: "DELETE",
188
+ [RpcTask.UPDATE]: "PATCH",
189
+ [RpcTask.CREATE]: "POST",
190
+ };
191
+ class ServerRequestUrl {
192
+ constructor(task, apiKey, requestOptions) {
193
+ this.task = task;
194
+ this.apiKey = apiKey;
195
+ this.requestOptions = requestOptions;
196
+ }
197
+ appendPath(path) {
198
+ this._url.pathname = this._url.pathname + `/${path}`;
199
+ }
200
+ appendParam(key, value) {
201
+ this._url.searchParams.append(key, value);
202
+ }
203
+ toString() {
204
+ return this._url.toString();
205
+ }
206
+ }
207
+ class CachedContentUrl extends ServerRequestUrl {
208
+ constructor(task, apiKey, requestOptions) {
209
+ var _a, _b;
210
+ super(task, apiKey, requestOptions);
211
+ this.task = task;
212
+ this.apiKey = apiKey;
213
+ this.requestOptions = requestOptions;
214
+ const apiVersion = ((_a = this.requestOptions) === null || _a === void 0 ? void 0 : _a.apiVersion) || DEFAULT_API_VERSION;
215
+ const baseUrl = ((_b = this.requestOptions) === null || _b === void 0 ? void 0 : _b.baseUrl) || DEFAULT_BASE_URL;
216
+ let initialUrl = baseUrl;
217
+ initialUrl += `/${apiVersion}/cachedContents`;
218
+ this._url = new URL(initialUrl);
219
+ }
220
+ }
221
+ class FilesRequestUrl extends ServerRequestUrl {
222
+ constructor(task, apiKey, requestOptions) {
223
+ var _a, _b;
224
+ super(task, apiKey, requestOptions);
225
+ this.task = task;
226
+ this.apiKey = apiKey;
227
+ this.requestOptions = requestOptions;
228
+ const apiVersion = ((_a = this.requestOptions) === null || _a === void 0 ? void 0 : _a.apiVersion) || DEFAULT_API_VERSION;
229
+ const baseUrl = ((_b = this.requestOptions) === null || _b === void 0 ? void 0 : _b.baseUrl) || DEFAULT_BASE_URL;
230
+ let initialUrl = baseUrl;
231
+ if (this.task === RpcTask.UPLOAD) {
232
+ initialUrl += `/upload`;
233
+ }
234
+ initialUrl += `/${apiVersion}/files`;
235
+ this._url = new URL(initialUrl);
236
+ }
237
+ }
238
+ function getHeaders(url) {
239
+ var _a;
240
+ const headers = new Headers();
241
+ headers.append("x-goog-api-client", getClientHeaders(url.requestOptions));
242
+ headers.append("x-goog-api-key", url.apiKey);
243
+ let customHeaders = (_a = url.requestOptions) === null || _a === void 0 ? void 0 : _a.customHeaders;
244
+ if (customHeaders) {
245
+ if (!(customHeaders instanceof Headers)) {
246
+ try {
247
+ customHeaders = new Headers(customHeaders);
248
+ }
249
+ catch (e) {
250
+ throw new GoogleGenerativeAIRequestInputError(`unable to convert customHeaders value ${JSON.stringify(customHeaders)} to Headers: ${e.message}`);
251
+ }
252
+ }
253
+ for (const [headerName, headerValue] of customHeaders.entries()) {
254
+ if (headerName === "x-goog-api-key") {
255
+ throw new GoogleGenerativeAIRequestInputError(`Cannot set reserved header name ${headerName}`);
256
+ }
257
+ else if (headerName === "x-goog-api-client") {
258
+ throw new GoogleGenerativeAIRequestInputError(`Header name ${headerName} can only be set using the apiClient field`);
259
+ }
260
+ headers.append(headerName, headerValue);
261
+ }
262
+ }
263
+ return headers;
264
+ }
265
+ async function makeServerRequest(url, headers, body, fetchFn = fetch) {
266
+ const requestInit = {
267
+ method: taskToMethod[url.task],
268
+ headers,
269
+ };
270
+ if (body) {
271
+ requestInit.body = body;
272
+ }
273
+ const signal = getSignal(url.requestOptions);
274
+ if (signal) {
275
+ requestInit.signal = signal;
276
+ }
277
+ return makeRequest(url.toString(), requestInit, fetchFn);
278
+ }
279
+ /**
280
+ * Create an AbortSignal based on the timeout and signal in the
281
+ * RequestOptions.
282
+ */
283
+ function getSignal(requestOptions) {
284
+ if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.signal) !== undefined || (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeout) >= 0) {
285
+ const controller = new AbortController();
286
+ if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeout) >= 0) {
287
+ setTimeout(() => controller.abort(), requestOptions.timeout);
288
+ }
289
+ if (requestOptions.signal) {
290
+ requestOptions.signal.addEventListener("abort", () => {
291
+ controller.abort();
292
+ });
293
+ }
294
+ return controller.signal;
295
+ }
296
+ }
297
+
298
+ /**
299
+ * @license
300
+ * Copyright 2024 Google LLC
301
+ *
302
+ * Licensed under the Apache License, Version 2.0 (the "License");
303
+ * you may not use this file except in compliance with the License.
304
+ * You may obtain a copy of the License at
305
+ *
306
+ * http://www.apache.org/licenses/LICENSE-2.0
307
+ *
308
+ * Unless required by applicable law or agreed to in writing, software
309
+ * distributed under the License is distributed on an "AS IS" BASIS,
310
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
311
+ * See the License for the specific language governing permissions and
312
+ * limitations under the License.
313
+ */
314
+ /**
315
+ * Class for managing GoogleAI file uploads.
316
+ * @public
317
+ */
318
+ class GoogleAIFileManager {
319
+ constructor(apiKey, _requestOptions = {}) {
320
+ this.apiKey = apiKey;
321
+ this._requestOptions = _requestOptions;
322
+ }
323
+ /**
324
+ * Upload a file.
325
+ */
326
+ async uploadFile(fileData, fileMetadata) {
327
+ const file = fileData instanceof Buffer ? fileData : readFileSync(fileData);
328
+ const url = new FilesRequestUrl(RpcTask.UPLOAD, this.apiKey, this._requestOptions);
329
+ const uploadHeaders = getHeaders(url);
330
+ const boundary = generateBoundary();
331
+ uploadHeaders.append("X-Goog-Upload-Protocol", "multipart");
332
+ uploadHeaders.append("Content-Type", `multipart/related; boundary=${boundary}`);
333
+ const uploadMetadata = getUploadMetadata(fileMetadata);
334
+ // Multipart formatting code taken from @firebase/storage
335
+ const metadataString = JSON.stringify({ file: uploadMetadata });
336
+ const preBlobPart = "--" +
337
+ boundary +
338
+ "\r\n" +
339
+ "Content-Type: application/json; charset=utf-8\r\n\r\n" +
340
+ metadataString +
341
+ "\r\n--" +
342
+ boundary +
343
+ "\r\n" +
344
+ "Content-Type: " +
345
+ fileMetadata.mimeType +
346
+ "\r\n\r\n";
347
+ const postBlobPart = "\r\n--" + boundary + "--";
348
+ const blob = new Blob([preBlobPart, file, postBlobPart]);
349
+ const response = await makeServerRequest(url, uploadHeaders, blob);
350
+ return response.json();
351
+ }
352
+ /**
353
+ * List all uploaded files.
354
+ *
355
+ * Any fields set in the optional {@link SingleRequestOptions} parameter will take
356
+ * precedence over the {@link RequestOptions} values provided at the time of the
357
+ * {@link GoogleAIFileManager} initialization.
358
+ */
359
+ async listFiles(listParams, requestOptions = {}) {
360
+ const filesRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
361
+ const url = new FilesRequestUrl(RpcTask.LIST, this.apiKey, filesRequestOptions);
362
+ if (listParams === null || listParams === void 0 ? void 0 : listParams.pageSize) {
363
+ url.appendParam("pageSize", listParams.pageSize.toString());
364
+ }
365
+ if (listParams === null || listParams === void 0 ? void 0 : listParams.pageToken) {
366
+ url.appendParam("pageToken", listParams.pageToken);
367
+ }
368
+ const uploadHeaders = getHeaders(url);
369
+ const response = await makeServerRequest(url, uploadHeaders);
370
+ return response.json();
371
+ }
372
+ /**
373
+ * Get metadata for file with given ID.
374
+ *
375
+ * Any fields set in the optional {@link SingleRequestOptions} parameter will take
376
+ * precedence over the {@link RequestOptions} values provided at the time of the
377
+ * {@link GoogleAIFileManager} initialization.
378
+ */
379
+ async getFile(fileId, requestOptions = {}) {
380
+ const filesRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
381
+ const url = new FilesRequestUrl(RpcTask.GET, this.apiKey, filesRequestOptions);
382
+ url.appendPath(parseFileId(fileId));
383
+ const uploadHeaders = getHeaders(url);
384
+ const response = await makeServerRequest(url, uploadHeaders);
385
+ return response.json();
386
+ }
387
+ /**
388
+ * Delete file with given ID.
389
+ */
390
+ async deleteFile(fileId) {
391
+ const url = new FilesRequestUrl(RpcTask.DELETE, this.apiKey, this._requestOptions);
392
+ url.appendPath(parseFileId(fileId));
393
+ const uploadHeaders = getHeaders(url);
394
+ await makeServerRequest(url, uploadHeaders);
395
+ }
396
+ }
397
+ /**
398
+ * If fileId is prepended with "files/", remove prefix
399
+ */
400
+ function parseFileId(fileId) {
401
+ if (fileId.startsWith("files/")) {
402
+ return fileId.split("files/")[1];
403
+ }
404
+ if (!fileId) {
405
+ throw new GoogleGenerativeAIError(`Invalid fileId ${fileId}. ` +
406
+ `Must be in the format "files/filename" or "filename"`);
407
+ }
408
+ return fileId;
409
+ }
410
+ function generateBoundary() {
411
+ let str = "";
412
+ for (let i = 0; i < 2; i++) {
413
+ str = str + Math.random().toString().slice(2);
414
+ }
415
+ return str;
416
+ }
417
+ function getUploadMetadata(inputMetadata) {
418
+ if (!inputMetadata.mimeType) {
419
+ throw new GoogleGenerativeAIRequestInputError("Must provide a mimeType.");
420
+ }
421
+ const uploadMetadata = {
422
+ mimeType: inputMetadata.mimeType,
423
+ displayName: inputMetadata.displayName,
424
+ };
425
+ if (inputMetadata.name) {
426
+ uploadMetadata.name = inputMetadata.name.includes("/")
427
+ ? inputMetadata.name
428
+ : `files/${inputMetadata.name}`;
429
+ }
430
+ return uploadMetadata;
431
+ }
432
+
433
+ /**
434
+ * @license
435
+ * Copyright 2024 Google LLC
436
+ *
437
+ * Licensed under the Apache License, Version 2.0 (the "License");
438
+ * you may not use this file except in compliance with the License.
439
+ * You may obtain a copy of the License at
440
+ *
441
+ * http://www.apache.org/licenses/LICENSE-2.0
442
+ *
443
+ * Unless required by applicable law or agreed to in writing, software
444
+ * distributed under the License is distributed on an "AS IS" BASIS,
445
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
446
+ * See the License for the specific language governing permissions and
447
+ * limitations under the License.
448
+ */
449
+ function formatSystemInstruction(input) {
450
+ // null or undefined
451
+ if (input == null) {
452
+ return undefined;
453
+ }
454
+ else if (typeof input === "string") {
455
+ return { role: "system", parts: [{ text: input }] };
456
+ }
457
+ else if (input.text) {
458
+ return { role: "system", parts: [input] };
459
+ }
460
+ else if (input.parts) {
461
+ if (!input.role) {
462
+ return { role: "system", parts: input.parts };
463
+ }
464
+ else {
465
+ return input;
466
+ }
467
+ }
468
+ }
469
+
470
+ /**
471
+ * @license
472
+ * Copyright 2024 Google LLC
473
+ *
474
+ * Licensed under the Apache License, Version 2.0 (the "License");
475
+ * you may not use this file except in compliance with the License.
476
+ * You may obtain a copy of the License at
477
+ *
478
+ * http://www.apache.org/licenses/LICENSE-2.0
479
+ *
480
+ * Unless required by applicable law or agreed to in writing, software
481
+ * distributed under the License is distributed on an "AS IS" BASIS,
482
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
483
+ * See the License for the specific language governing permissions and
484
+ * limitations under the License.
485
+ */
486
+ /**
487
+ * Class for managing GoogleAI content caches.
488
+ * @public
489
+ */
490
+ class GoogleAICacheManager {
491
+ constructor(apiKey, _requestOptions) {
492
+ this.apiKey = apiKey;
493
+ this._requestOptions = _requestOptions;
494
+ }
495
+ /**
496
+ * Upload a new content cache
497
+ */
498
+ async create(createOptions) {
499
+ const newCachedContent = Object.assign({}, createOptions);
500
+ if (createOptions.ttlSeconds) {
501
+ if (createOptions.expireTime) {
502
+ throw new GoogleGenerativeAIRequestInputError("You cannot specify both `ttlSeconds` and `expireTime` when creating" +
503
+ " a content cache. You must choose one.");
504
+ }
505
+ newCachedContent.ttl = createOptions.ttlSeconds.toString() + "s";
506
+ delete newCachedContent.ttlSeconds;
507
+ }
508
+ if (createOptions.systemInstruction) {
509
+ newCachedContent.systemInstruction = formatSystemInstruction(createOptions.systemInstruction);
510
+ }
511
+ if (!newCachedContent.model) {
512
+ throw new GoogleGenerativeAIRequestInputError("Cached content must contain a `model` field.");
513
+ }
514
+ if (!newCachedContent.model.includes("/")) {
515
+ // If path is not included, assume it's a non-tuned model.
516
+ newCachedContent.model = `models/${newCachedContent.model}`;
517
+ }
518
+ const url = new CachedContentUrl(RpcTask.CREATE, this.apiKey, this._requestOptions);
519
+ const headers = getHeaders(url);
520
+ const response = await makeServerRequest(url, headers, JSON.stringify(newCachedContent));
521
+ return response.json();
522
+ }
523
+ /**
524
+ * List all uploaded content caches
525
+ */
526
+ async list(listParams) {
527
+ const url = new CachedContentUrl(RpcTask.LIST, this.apiKey, this._requestOptions);
528
+ if (listParams === null || listParams === void 0 ? void 0 : listParams.pageSize) {
529
+ url.appendParam("pageSize", listParams.pageSize.toString());
530
+ }
531
+ if (listParams === null || listParams === void 0 ? void 0 : listParams.pageToken) {
532
+ url.appendParam("pageToken", listParams.pageToken);
533
+ }
534
+ const headers = getHeaders(url);
535
+ const response = await makeServerRequest(url, headers);
536
+ return response.json();
537
+ }
538
+ /**
539
+ * Get a content cache
540
+ */
541
+ async get(name) {
542
+ const url = new CachedContentUrl(RpcTask.GET, this.apiKey, this._requestOptions);
543
+ url.appendPath(parseCacheName(name));
544
+ const headers = getHeaders(url);
545
+ const response = await makeServerRequest(url, headers);
546
+ return response.json();
547
+ }
548
+ /**
549
+ * Update an existing content cache
550
+ */
551
+ async update(name, updateParams) {
552
+ const url = new CachedContentUrl(RpcTask.UPDATE, this.apiKey, this._requestOptions);
553
+ url.appendPath(parseCacheName(name));
554
+ const headers = getHeaders(url);
555
+ const formattedCachedContent = Object.assign({}, updateParams.cachedContent);
556
+ if (updateParams.cachedContent.ttlSeconds) {
557
+ formattedCachedContent.ttl =
558
+ updateParams.cachedContent.ttlSeconds.toString() + "s";
559
+ delete formattedCachedContent.ttlSeconds;
560
+ }
561
+ if (updateParams.updateMask) {
562
+ url.appendParam("update_mask", updateParams.updateMask.map((prop) => camelToSnake(prop)).join(","));
563
+ }
564
+ const response = await makeServerRequest(url, headers, JSON.stringify(formattedCachedContent));
565
+ return response.json();
566
+ }
567
+ /**
568
+ * Delete content cache with given name
569
+ */
570
+ async delete(name) {
571
+ const url = new CachedContentUrl(RpcTask.DELETE, this.apiKey, this._requestOptions);
572
+ url.appendPath(parseCacheName(name));
573
+ const headers = getHeaders(url);
574
+ await makeServerRequest(url, headers);
575
+ }
576
+ }
577
+ /**
578
+ * If cache name is prepended with "cachedContents/", remove prefix
579
+ */
580
+ function parseCacheName(name) {
581
+ if (name.startsWith("cachedContents/")) {
582
+ return name.split("cachedContents/")[1];
583
+ }
584
+ if (!name) {
585
+ throw new GoogleGenerativeAIError(`Invalid name ${name}. ` +
586
+ `Must be in the format "cachedContents/name" or "name"`);
587
+ }
588
+ return name;
589
+ }
590
+ function camelToSnake(str) {
591
+ return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
592
+ }
593
+
594
+ /**
595
+ * Processing state of the `File`.
596
+ * @public
597
+ */
598
+ var FileState;
599
+ (function (FileState) {
600
+ // The default value. This value is used if the state is omitted.
601
+ FileState["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED";
602
+ // File is being processed and cannot be used for inference yet.
603
+ FileState["PROCESSING"] = "PROCESSING";
604
+ // File is processed and available for inference.
605
+ FileState["ACTIVE"] = "ACTIVE";
606
+ // File failed processing.
607
+ FileState["FAILED"] = "FAILED";
608
+ })(FileState || (FileState = {}));
609
+
610
+ /**
611
+ * Contains the list of OpenAPI data types
612
+ * as defined by https://swagger.io/docs/specification/data-models/data-types/
613
+ * @public
614
+ */
615
+ var SchemaType;
616
+ (function (SchemaType) {
617
+ /** String type. */
618
+ SchemaType["STRING"] = "string";
619
+ /** Number type. */
620
+ SchemaType["NUMBER"] = "number";
621
+ /** Integer type. */
622
+ SchemaType["INTEGER"] = "integer";
623
+ /** Boolean type. */
624
+ SchemaType["BOOLEAN"] = "boolean";
625
+ /** Array type. */
626
+ SchemaType["ARRAY"] = "array";
627
+ /** Object type. */
628
+ SchemaType["OBJECT"] = "object";
629
+ })(SchemaType || (SchemaType = {}));
630
+
631
+ /**
632
+ * @license
633
+ * Copyright 2024 Google LLC
634
+ *
635
+ * Licensed under the Apache License, Version 2.0 (the "License");
636
+ * you may not use this file except in compliance with the License.
637
+ * You may obtain a copy of the License at
638
+ *
639
+ * http://www.apache.org/licenses/LICENSE-2.0
640
+ *
641
+ * Unless required by applicable law or agreed to in writing, software
642
+ * distributed under the License is distributed on an "AS IS" BASIS,
643
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
644
+ * See the License for the specific language governing permissions and
645
+ * limitations under the License.
646
+ */
647
+ /**
648
+ * @public
649
+ */
650
+ var ExecutableCodeLanguage;
651
+ (function (ExecutableCodeLanguage) {
652
+ ExecutableCodeLanguage["LANGUAGE_UNSPECIFIED"] = "language_unspecified";
653
+ ExecutableCodeLanguage["PYTHON"] = "python";
654
+ })(ExecutableCodeLanguage || (ExecutableCodeLanguage = {}));
655
+ /**
656
+ * Possible outcomes of code execution.
657
+ * @public
658
+ */
659
+ var Outcome;
660
+ (function (Outcome) {
661
+ /**
662
+ * Unspecified status. This value should not be used.
663
+ */
664
+ Outcome["OUTCOME_UNSPECIFIED"] = "outcome_unspecified";
665
+ /**
666
+ * Code execution completed successfully.
667
+ */
668
+ Outcome["OUTCOME_OK"] = "outcome_ok";
669
+ /**
670
+ * Code execution finished but with a failure. `stderr` should contain the
671
+ * reason.
672
+ */
673
+ Outcome["OUTCOME_FAILED"] = "outcome_failed";
674
+ /**
675
+ * Code execution ran for too long, and was cancelled. There may or may not
676
+ * be a partial output present.
677
+ */
678
+ Outcome["OUTCOME_DEADLINE_EXCEEDED"] = "outcome_deadline_exceeded";
679
+ })(Outcome || (Outcome = {}));
680
+
681
+ /**
682
+ * @license
683
+ * Copyright 2024 Google LLC
684
+ *
685
+ * Licensed under the Apache License, Version 2.0 (the "License");
686
+ * you may not use this file except in compliance with the License.
687
+ * You may obtain a copy of the License at
688
+ *
689
+ * http://www.apache.org/licenses/LICENSE-2.0
690
+ *
691
+ * Unless required by applicable law or agreed to in writing, software
692
+ * distributed under the License is distributed on an "AS IS" BASIS,
693
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
694
+ * See the License for the specific language governing permissions and
695
+ * limitations under the License.
696
+ */
697
+ /**
698
+ * Possible roles.
699
+ * @public
700
+ */
701
+ /**
702
+ * Harm categories that would cause prompts or candidates to be blocked.
703
+ * @public
704
+ */
705
+ var HarmCategory;
706
+ (function (HarmCategory) {
707
+ HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED";
708
+ HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH";
709
+ HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT";
710
+ HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT";
711
+ HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT";
712
+ HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY";
713
+ })(HarmCategory || (HarmCategory = {}));
714
+ /**
715
+ * Threshold above which a prompt or candidate will be blocked.
716
+ * @public
717
+ */
718
+ var HarmBlockThreshold;
719
+ (function (HarmBlockThreshold) {
720
+ /** Threshold is unspecified. */
721
+ HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED";
722
+ /** Content with NEGLIGIBLE will be allowed. */
723
+ HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE";
724
+ /** Content with NEGLIGIBLE and LOW will be allowed. */
725
+ HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE";
726
+ /** Content with NEGLIGIBLE, LOW, and MEDIUM will be allowed. */
727
+ HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH";
728
+ /** All content will be allowed. */
729
+ HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE";
730
+ })(HarmBlockThreshold || (HarmBlockThreshold = {}));
731
+ /**
732
+ * Probability that a prompt or candidate matches a harm category.
733
+ * @public
734
+ */
735
+ var HarmProbability;
736
+ (function (HarmProbability) {
737
+ /** Probability is unspecified. */
738
+ HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED";
739
+ /** Content has a negligible chance of being unsafe. */
740
+ HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE";
741
+ /** Content has a low chance of being unsafe. */
742
+ HarmProbability["LOW"] = "LOW";
743
+ /** Content has a medium chance of being unsafe. */
744
+ HarmProbability["MEDIUM"] = "MEDIUM";
745
+ /** Content has a high chance of being unsafe. */
746
+ HarmProbability["HIGH"] = "HIGH";
747
+ })(HarmProbability || (HarmProbability = {}));
748
+ /**
749
+ * Reason that a prompt was blocked.
750
+ * @public
751
+ */
752
+ var BlockReason;
753
+ (function (BlockReason) {
754
+ // A blocked reason was not specified.
755
+ BlockReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED";
756
+ // Content was blocked by safety settings.
757
+ BlockReason["SAFETY"] = "SAFETY";
758
+ // Content was blocked, but the reason is uncategorized.
759
+ BlockReason["OTHER"] = "OTHER";
760
+ })(BlockReason || (BlockReason = {}));
761
+ /**
762
+ * Reason that a candidate finished.
763
+ * @public
764
+ */
765
+ var FinishReason;
766
+ (function (FinishReason) {
767
+ // Default value. This value is unused.
768
+ FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED";
769
+ // Natural stop point of the model or provided stop sequence.
770
+ FinishReason["STOP"] = "STOP";
771
+ // The maximum number of tokens as specified in the request was reached.
772
+ FinishReason["MAX_TOKENS"] = "MAX_TOKENS";
773
+ // The candidate content was flagged for safety reasons.
774
+ FinishReason["SAFETY"] = "SAFETY";
775
+ // The candidate content was flagged for recitation reasons.
776
+ FinishReason["RECITATION"] = "RECITATION";
777
+ // The candidate content was flagged for using an unsupported language.
778
+ FinishReason["LANGUAGE"] = "LANGUAGE";
779
+ // Token generation stopped because the content contains forbidden terms.
780
+ FinishReason["BLOCKLIST"] = "BLOCKLIST";
781
+ // Token generation stopped for potentially containing prohibited content.
782
+ FinishReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT";
783
+ // Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII).
784
+ FinishReason["SPII"] = "SPII";
785
+ // The function call generated by the model is invalid.
786
+ FinishReason["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL";
787
+ // Unknown reason.
788
+ FinishReason["OTHER"] = "OTHER";
789
+ })(FinishReason || (FinishReason = {}));
790
+ /**
791
+ * Task type for embedding content.
792
+ * @public
793
+ */
794
+ var TaskType;
795
+ (function (TaskType) {
796
+ TaskType["TASK_TYPE_UNSPECIFIED"] = "TASK_TYPE_UNSPECIFIED";
797
+ TaskType["RETRIEVAL_QUERY"] = "RETRIEVAL_QUERY";
798
+ TaskType["RETRIEVAL_DOCUMENT"] = "RETRIEVAL_DOCUMENT";
799
+ TaskType["SEMANTIC_SIMILARITY"] = "SEMANTIC_SIMILARITY";
800
+ TaskType["CLASSIFICATION"] = "CLASSIFICATION";
801
+ TaskType["CLUSTERING"] = "CLUSTERING";
802
+ })(TaskType || (TaskType = {}));
803
+ /**
804
+ * @public
805
+ */
806
+ var FunctionCallingMode;
807
+ (function (FunctionCallingMode) {
808
+ // Unspecified function calling mode. This value should not be used.
809
+ FunctionCallingMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
810
+ // Default model behavior, model decides to predict either a function call
811
+ // or a natural language repspose.
812
+ FunctionCallingMode["AUTO"] = "AUTO";
813
+ // Model is constrained to always predicting a function call only.
814
+ // If "allowed_function_names" are set, the predicted function call will be
815
+ // limited to any one of "allowed_function_names", else the predicted
816
+ // function call will be any one of the provided "function_declarations".
817
+ FunctionCallingMode["ANY"] = "ANY";
818
+ // Model will not predict any function call. Model behavior is same as when
819
+ // not passing any function declarations.
820
+ FunctionCallingMode["NONE"] = "NONE";
821
+ })(FunctionCallingMode || (FunctionCallingMode = {}));
822
+ /**
823
+ * The mode of the predictor to be used in dynamic retrieval.
824
+ * @public
825
+ */
826
+ var DynamicRetrievalMode;
827
+ (function (DynamicRetrievalMode) {
828
+ // Unspecified function calling mode. This value should not be used.
829
+ DynamicRetrievalMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
830
+ // Run retrieval only when system decides it is necessary.
831
+ DynamicRetrievalMode["MODE_DYNAMIC"] = "MODE_DYNAMIC";
832
+ })(DynamicRetrievalMode || (DynamicRetrievalMode = {}));
833
+
834
+ export { ExecutableCodeLanguage, FileState, FunctionCallingMode, GoogleAICacheManager, GoogleAIFileManager, Outcome, SchemaType };
835
+ //# sourceMappingURL=index.mjs.map
backend-old/node_modules/@google/generative-ai/dist/server/index.mjs.map ADDED
@@ -0,0 +1 @@
 
 
1
+ {"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
backend-old/node_modules/@google/generative-ai/dist/server/scripts/check-format.d.ts ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2023 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ export {};
backend-old/node_modules/@google/generative-ai/dist/server/scripts/format-patterns.d.ts ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2024 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ export declare const formatPatterns: string[];
18
+ export declare function getFormatPatternsString(): string;
backend-old/node_modules/@google/generative-ai/dist/server/scripts/license.d.ts ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2023 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ export declare function doLicense(write: boolean): Promise<boolean>;
backend-old/node_modules/@google/generative-ai/dist/server/scripts/run-format.d.ts ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2023 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ export {};
backend-old/node_modules/@google/generative-ai/dist/server/server.d.ts ADDED
@@ -0,0 +1,875 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /// <reference types="node" />
2
+
3
+ /**
4
+ * Describes an array, an ordered list of values.
5
+ *
6
+ * @public
7
+ */
8
+ export declare interface ArraySchema extends BaseSchema {
9
+ type: typeof SchemaType.ARRAY;
10
+ /** A schema describing the entries in the array. */
11
+ items: Schema;
12
+ /** The minimum number of items in the array. */
13
+ minItems?: number;
14
+ /** The maximum number of items in the array. */
15
+ maxItems?: number;
16
+ }
17
+
18
+ /**
19
+ * Fields common to all Schema types.
20
+ *
21
+ * @internal
22
+ */
23
+ export declare interface BaseSchema {
24
+ /** Optional. Description of the value. */
25
+ description?: string;
26
+ /** If true, the value can be null. */
27
+ nullable?: boolean;
28
+ }
29
+
30
+ /**
31
+ * Describes a boolean, either 'true' or 'false'.
32
+ *
33
+ * @public
34
+ */
35
+ export declare interface BooleanSchema extends BaseSchema {
36
+ type: typeof SchemaType.BOOLEAN;
37
+ }
38
+
39
+ /**
40
+ * Describes `CachedContent` interface for sending to the server (if creating)
41
+ * or received from the server (using getters or list methods).
42
+ * @public
43
+ */
44
+ export declare interface CachedContent extends CachedContentBase {
45
+ name?: string;
46
+ /**
47
+ * protobuf.Duration format (ex. "3.0001s").
48
+ */
49
+ ttl?: string;
50
+ /**
51
+ * `CachedContent` creation time in ISO string format.
52
+ */
53
+ createTime?: string;
54
+ /**
55
+ * `CachedContent` update time in ISO string format.
56
+ */
57
+ updateTime?: string;
58
+ }
59
+
60
+ /**
61
+ * @public
62
+ */
63
+ export declare interface CachedContentBase {
64
+ model?: string;
65
+ contents: Content[];
66
+ tools?: Tool[];
67
+ toolConfig?: ToolConfig;
68
+ systemInstruction?: string | Part | Content;
69
+ /**
70
+ * Expiration time in ISO string format. Specify either this or `ttlSeconds`
71
+ * when creating a `CachedContent`.
72
+ */
73
+ expireTime?: string;
74
+ displayName?: string;
75
+ }
76
+
77
+ /**
78
+ * Params to pass to {@link GoogleAICacheManager.create}.
79
+ * @public
80
+ */
81
+ export declare interface CachedContentCreateParams extends CachedContentBase {
82
+ /**
83
+ * `CachedContent` ttl in seconds. Specify either this or `expireTime`
84
+ * when creating a `CachedContent`.
85
+ */
86
+ ttlSeconds?: number;
87
+ }
88
+
89
+ /**
90
+ * Fields that can be updated in an existing content cache.
91
+ * @public
92
+ */
93
+ export declare interface CachedContentUpdateInputFields {
94
+ ttlSeconds?: number;
95
+ expireTime?: string;
96
+ }
97
+
98
+ /**
99
+ * Params to pass to {@link GoogleAICacheManager.update}.
100
+ * @public
101
+ */
102
+ export declare interface CachedContentUpdateParams {
103
+ cachedContent: CachedContentUpdateInputFields;
104
+ /**
105
+ * protobuf FieldMask. If not specified, updates all provided fields.
106
+ */
107
+ updateMask?: string[];
108
+ }
109
+
110
+ /**
111
+ * Params as sent to the backend (ttl instead of ttlSeconds).
112
+ * @internal
113
+ */
114
+ export declare interface _CachedContentUpdateRequest {
115
+ cachedContent: _CachedContentUpdateRequestFields;
116
+ /**
117
+ * protobuf FieldMask
118
+ */
119
+ updateMask?: string[];
120
+ }
121
+
122
+ /**
123
+ * Fields that can be updated in an existing content cache.
124
+ * @internal
125
+ */
126
+ export declare interface _CachedContentUpdateRequestFields {
127
+ ttl?: string;
128
+ expireTime?: string;
129
+ }
130
+
131
+ /**
132
+ * Result of executing the `ExecutableCode`.
133
+ * Only generated when using code execution, and always follows a `Part`
134
+ * containing the `ExecutableCode`.
135
+ * @public
136
+ */
137
+ export declare interface CodeExecutionResult {
138
+ /**
139
+ * Outcome of the code execution.
140
+ */
141
+ outcome: Outcome;
142
+ /**
143
+ * Contains stdout when code execution is successful, stderr or other
144
+ * description otherwise.
145
+ */
146
+ output: string;
147
+ }
148
+
149
+ /**
150
+ * Content part containing the result of executed code.
151
+ * @public
152
+ */
153
+ export declare interface CodeExecutionResultPart {
154
+ text?: never;
155
+ inlineData?: never;
156
+ functionCall?: never;
157
+ functionResponse?: never;
158
+ fileData?: never;
159
+ executableCode?: never;
160
+ codeExecutionResult: CodeExecutionResult;
161
+ }
162
+
163
+ /**
164
+ * Enables the model to execute code as part of generation.
165
+ * @public
166
+ */
167
+ export declare interface CodeExecutionTool {
168
+ /**
169
+ * Provide an empty object to enable code execution. This field may have
170
+ * subfields added in the future.
171
+ */
172
+ codeExecution: {};
173
+ }
174
+
175
+ /**
176
+ * Content type for both prompts and response candidates.
177
+ * @public
178
+ */
179
+ export declare interface Content {
180
+ role: string;
181
+ parts: Part[];
182
+ }
183
+
184
+ /**
185
+ * Specifies the dynamic retrieval configuration for the given source.
186
+ * @public
187
+ */
188
+ declare interface DynamicRetrievalConfig {
189
+ /**
190
+ * The mode of the predictor to be used in dynamic retrieval.
191
+ */
192
+ mode?: DynamicRetrievalMode;
193
+ /**
194
+ * The threshold to be used in dynamic retrieval. If not set, a system default
195
+ * value is used.
196
+ */
197
+ dynamicThreshold?: number;
198
+ }
199
+
200
+ /**
201
+ * The mode of the predictor to be used in dynamic retrieval.
202
+ * @public
203
+ */
204
+ declare enum DynamicRetrievalMode {
205
+ MODE_UNSPECIFIED = "MODE_UNSPECIFIED",
206
+ MODE_DYNAMIC = "MODE_DYNAMIC"
207
+ }
208
+
209
+ /**
210
+ * Describes a string enum
211
+ *
212
+ * @public
213
+ */
214
+ export declare interface EnumStringSchema extends BaseSchema {
215
+ type: typeof SchemaType.STRING;
216
+ format: "enum";
217
+ /** Possible values for this enum */
218
+ enum: string[];
219
+ }
220
+
221
+ /**
222
+ * Details object that may be included in an error response.
223
+ * @public
224
+ */
225
+ export declare interface ErrorDetails {
226
+ "@type"?: string;
227
+ reason?: string;
228
+ domain?: string;
229
+ metadata?: Record<string, unknown>;
230
+ [key: string]: unknown;
231
+ }
232
+
233
+ /**
234
+ * Code generated by the model that is meant to be executed, where the result
235
+ * is returned to the model.
236
+ * Only generated when using the code execution tool, in which the code will
237
+ * be automatically executed, and a corresponding `CodeExecutionResult` will
238
+ * also be generated.
239
+ *
240
+ * @public
241
+ */
242
+ export declare interface ExecutableCode {
243
+ /**
244
+ * Programming language of the `code`.
245
+ */
246
+ language: ExecutableCodeLanguage;
247
+ /**
248
+ * The code to be executed.
249
+ */
250
+ code: string;
251
+ }
252
+
253
+ /**
254
+ * @public
255
+ */
256
+ export declare enum ExecutableCodeLanguage {
257
+ LANGUAGE_UNSPECIFIED = "language_unspecified",
258
+ PYTHON = "python"
259
+ }
260
+
261
+ /**
262
+ * Content part containing executable code generated by the model.
263
+ * @public
264
+ */
265
+ export declare interface ExecutableCodePart {
266
+ text?: never;
267
+ inlineData?: never;
268
+ functionCall?: never;
269
+ functionResponse?: never;
270
+ fileData?: never;
271
+ executableCode: ExecutableCode;
272
+ codeExecutionResult?: never;
273
+ }
274
+
275
+ /**
276
+ * Data pointing to a file uploaded with the Files API.
277
+ * @public
278
+ */
279
+ export declare interface FileData {
280
+ mimeType: string;
281
+ fileUri: string;
282
+ }
283
+
284
+ /**
285
+ * Content part interface if the part represents FileData.
286
+ * @public
287
+ */
288
+ export declare interface FileDataPart {
289
+ text?: never;
290
+ inlineData?: never;
291
+ functionCall?: never;
292
+ functionResponse?: never;
293
+ fileData: FileData;
294
+ executableCode?: never;
295
+ codeExecutionResult?: never;
296
+ }
297
+
298
+ /**
299
+ * Metadata to provide alongside a file upload
300
+ * @public
301
+ */
302
+ export declare interface FileMetadata {
303
+ name?: string;
304
+ displayName?: string;
305
+ mimeType: string;
306
+ }
307
+
308
+ /**
309
+ * File metadata response from server.
310
+ * @public
311
+ */
312
+ export declare interface FileMetadataResponse {
313
+ name: string;
314
+ displayName?: string;
315
+ mimeType: string;
316
+ sizeBytes: string;
317
+ createTime: string;
318
+ updateTime: string;
319
+ expirationTime: string;
320
+ sha256Hash: string;
321
+ uri: string;
322
+ state: FileState;
323
+ /**
324
+ * Error populated if file processing has failed.
325
+ */
326
+ error?: RpcStatus;
327
+ /**
328
+ * Video metadata populated after processing is complete.
329
+ */
330
+ videoMetadata?: VideoMetadata;
331
+ }
332
+
333
+ /**
334
+ * Processing state of the `File`.
335
+ * @public
336
+ */
337
+ export declare enum FileState {
338
+ STATE_UNSPECIFIED = "STATE_UNSPECIFIED",
339
+ PROCESSING = "PROCESSING",
340
+ ACTIVE = "ACTIVE",
341
+ FAILED = "FAILED"
342
+ }
343
+
344
+ /**
345
+ * A predicted [FunctionCall] returned from the model
346
+ * that contains a string representing the [FunctionDeclaration.name]
347
+ * and a structured JSON object containing the parameters and their values.
348
+ * @public
349
+ */
350
+ export declare interface FunctionCall {
351
+ name: string;
352
+ args: object;
353
+ }
354
+
355
+ /**
356
+ * @public
357
+ */
358
+ export declare interface FunctionCallingConfig {
359
+ mode?: FunctionCallingMode;
360
+ allowedFunctionNames?: string[];
361
+ }
362
+
363
+ /**
364
+ * @public
365
+ */
366
+ export declare enum FunctionCallingMode {
367
+ MODE_UNSPECIFIED = "MODE_UNSPECIFIED",
368
+ AUTO = "AUTO",
369
+ ANY = "ANY",
370
+ NONE = "NONE"
371
+ }
372
+
373
+ /**
374
+ * Content part interface if the part represents a FunctionCall.
375
+ * @public
376
+ */
377
+ export declare interface FunctionCallPart {
378
+ text?: never;
379
+ inlineData?: never;
380
+ functionCall: FunctionCall;
381
+ functionResponse?: never;
382
+ fileData?: never;
383
+ executableCode?: never;
384
+ codeExecutionResult?: never;
385
+ }
386
+
387
+ /**
388
+ * Structured representation of a function declaration as defined by the
389
+ * [OpenAPI 3.0 specification](https://spec.openapis.org/oas/v3.0.3). Included
390
+ * in this declaration are the function name and parameters. This
391
+ * FunctionDeclaration is a representation of a block of code that can be used
392
+ * as a Tool by the model and executed by the client.
393
+ * @public
394
+ */
395
+ export declare interface FunctionDeclaration {
396
+ /**
397
+ * The name of the function to call. Must start with a letter or an
398
+ * underscore. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with
399
+ * a max length of 64.
400
+ */
401
+ name: string;
402
+ /**
403
+ * Optional. Description and purpose of the function. Model uses it to decide
404
+ * how and whether to call the function.
405
+ */
406
+ description?: string;
407
+ /**
408
+ * Optional. Describes the parameters to this function in JSON Schema Object
409
+ * format. Reflects the Open API 3.03 Parameter Object. string Key: the name
410
+ * of the parameter. Parameter names are case sensitive. Schema Value: the
411
+ * Schema defining the type used for the parameter. For function with no
412
+ * parameters, this can be left unset.
413
+ *
414
+ * @example with 1 required and 1 optional parameter: type: OBJECT properties:
415
+ * ```
416
+ * param1:
417
+ *
418
+ * type: STRING
419
+ * param2:
420
+ *
421
+ * type: INTEGER
422
+ * required:
423
+ *
424
+ * - param1
425
+ * ```
426
+ */
427
+ parameters?: FunctionDeclarationSchema;
428
+ }
429
+
430
+ /**
431
+ * Schema for parameters passed to {@link FunctionDeclaration.parameters}.
432
+ * @public
433
+ */
434
+ export declare interface FunctionDeclarationSchema {
435
+ /** The type of the parameter. */
436
+ type: SchemaType;
437
+ /** The format of the parameter. */
438
+ properties: {
439
+ [k: string]: FunctionDeclarationSchemaProperty;
440
+ };
441
+ /** Optional. Description of the parameter. */
442
+ description?: string;
443
+ /** Optional. Array of required parameters. */
444
+ required?: string[];
445
+ }
446
+
447
+ /**
448
+ * Schema for top-level function declaration
449
+ * @public
450
+ */
451
+ export declare type FunctionDeclarationSchemaProperty = Schema;
452
+
453
+ /**
454
+ * A FunctionDeclarationsTool is a piece of code that enables the system to
455
+ * interact with external systems to perform an action, or set of actions,
456
+ * outside of knowledge and scope of the model.
457
+ * @public
458
+ */
459
+ export declare interface FunctionDeclarationsTool {
460
+ /**
461
+ * Optional. One or more function declarations
462
+ * to be passed to the model along with the current user query. Model may
463
+ * decide to call a subset of these functions by populating
464
+ * [FunctionCall][content.part.functionCall] in the response. User should
465
+ * provide a [FunctionResponse][content.part.functionResponse] for each
466
+ * function call in the next turn. Based on the function responses, Model will
467
+ * generate the final response back to the user. Maximum 64 function
468
+ * declarations can be provided.
469
+ */
470
+ functionDeclarations?: FunctionDeclaration[];
471
+ }
472
+
473
+ /**
474
+ * The result output from a [FunctionCall] that contains a string
475
+ * representing the [FunctionDeclaration.name]
476
+ * and a structured JSON object containing any output
477
+ * from the function is used as context to the model.
478
+ * This should contain the result of a [FunctionCall]
479
+ * made based on model prediction.
480
+ * @public
481
+ */
482
+ export declare interface FunctionResponse {
483
+ name: string;
484
+ response: object;
485
+ }
486
+
487
+ /**
488
+ * Content part interface if the part represents FunctionResponse.
489
+ * @public
490
+ */
491
+ export declare interface FunctionResponsePart {
492
+ text?: never;
493
+ inlineData?: never;
494
+ functionCall?: never;
495
+ functionResponse: FunctionResponse;
496
+ fileData?: never;
497
+ executableCode?: never;
498
+ codeExecutionResult?: never;
499
+ }
500
+
501
+ /**
502
+ * Interface for sending an image.
503
+ * @public
504
+ */
505
+ export declare interface GenerativeContentBlob {
506
+ mimeType: string;
507
+ /**
508
+ * Image as a base64 string.
509
+ */
510
+ data: string;
511
+ }
512
+
513
+ /**
514
+ * Class for managing GoogleAI content caches.
515
+ * @public
516
+ */
517
+ export declare class GoogleAICacheManager {
518
+ apiKey: string;
519
+ private _requestOptions?;
520
+ constructor(apiKey: string, _requestOptions?: RequestOptions);
521
+ /**
522
+ * Upload a new content cache
523
+ */
524
+ create(createOptions: CachedContentCreateParams): Promise<CachedContent>;
525
+ /**
526
+ * List all uploaded content caches
527
+ */
528
+ list(listParams?: ListParams): Promise<ListCacheResponse>;
529
+ /**
530
+ * Get a content cache
531
+ */
532
+ get(name: string): Promise<CachedContent>;
533
+ /**
534
+ * Update an existing content cache
535
+ */
536
+ update(name: string, updateParams: CachedContentUpdateParams): Promise<CachedContent>;
537
+ /**
538
+ * Delete content cache with given name
539
+ */
540
+ delete(name: string): Promise<void>;
541
+ }
542
+
543
+ /**
544
+ * Class for managing GoogleAI file uploads.
545
+ * @public
546
+ */
547
+ export declare class GoogleAIFileManager {
548
+ apiKey: string;
549
+ private _requestOptions;
550
+ constructor(apiKey: string, _requestOptions?: RequestOptions);
551
+ /**
552
+ * Upload a file.
553
+ */
554
+ uploadFile(fileData: string | Buffer, fileMetadata: FileMetadata): Promise<UploadFileResponse>;
555
+ /**
556
+ * List all uploaded files.
557
+ *
558
+ * Any fields set in the optional {@link SingleRequestOptions} parameter will take
559
+ * precedence over the {@link RequestOptions} values provided at the time of the
560
+ * {@link GoogleAIFileManager} initialization.
561
+ */
562
+ listFiles(listParams?: ListParams, requestOptions?: SingleRequestOptions): Promise<ListFilesResponse>;
563
+ /**
564
+ * Get metadata for file with given ID.
565
+ *
566
+ * Any fields set in the optional {@link SingleRequestOptions} parameter will take
567
+ * precedence over the {@link RequestOptions} values provided at the time of the
568
+ * {@link GoogleAIFileManager} initialization.
569
+ */
570
+ getFile(fileId: string, requestOptions?: SingleRequestOptions): Promise<FileMetadataResponse>;
571
+ /**
572
+ * Delete file with given ID.
573
+ */
574
+ deleteFile(fileId: string): Promise<void>;
575
+ }
576
+
577
+ /**
578
+ * Retrieval tool that is powered by Google search.
579
+ * @public
580
+ */
581
+ declare interface GoogleSearchRetrieval {
582
+ /**
583
+ * Specifies the dynamic retrieval configuration for the given source.
584
+ */
585
+ dynamicRetrievalConfig?: DynamicRetrievalConfig;
586
+ }
587
+
588
+ /**
589
+ * Retrieval tool that is powered by Google search.
590
+ * @public
591
+ */
592
+ declare interface GoogleSearchRetrievalTool {
593
+ /**
594
+ * Google search retrieval tool config.
595
+ */
596
+ googleSearchRetrieval?: GoogleSearchRetrieval;
597
+ }
598
+
599
+ /**
600
+ * Content part interface if the part represents an image.
601
+ * @public
602
+ */
603
+ export declare interface InlineDataPart {
604
+ text?: never;
605
+ inlineData: GenerativeContentBlob;
606
+ functionCall?: never;
607
+ functionResponse?: never;
608
+ fileData?: never;
609
+ executableCode?: never;
610
+ codeExecutionResult?: never;
611
+ }
612
+
613
+ /**
614
+ * Describes a JSON-encodable integer.
615
+ *
616
+ * @public
617
+ */
618
+ export declare interface IntegerSchema extends BaseSchema {
619
+ type: typeof SchemaType.INTEGER;
620
+ /** Optional. The format of the number. */
621
+ format?: "int32" | "int64";
622
+ }
623
+
624
+ /**
625
+ * @public
626
+ */
627
+ export declare interface ListCacheResponse {
628
+ cachedContents: CachedContent[];
629
+ nextPageToken?: string;
630
+ }
631
+
632
+ /**
633
+ * Response from calling {@link GoogleAIFileManager.listFiles}
634
+ * @public
635
+ */
636
+ export declare interface ListFilesResponse {
637
+ files: FileMetadataResponse[];
638
+ nextPageToken?: string;
639
+ }
640
+
641
+ /**
642
+ * Params to pass to {@link GoogleAIFileManager.listFiles} or
643
+ * {@link GoogleAICacheManager.list}
644
+ * @public
645
+ */
646
+ export declare interface ListParams {
647
+ pageSize?: number;
648
+ pageToken?: string;
649
+ }
650
+
651
+ /**
652
+ * Describes a JSON-encodable floating point number.
653
+ *
654
+ * @public
655
+ */
656
+ export declare interface NumberSchema extends BaseSchema {
657
+ type: typeof SchemaType.NUMBER;
658
+ /** Optional. The format of the number. */
659
+ format?: "float" | "double";
660
+ }
661
+
662
+ /**
663
+ * Describes a JSON object, a mapping of specific keys to values.
664
+ *
665
+ * @public
666
+ */
667
+ export declare interface ObjectSchema extends BaseSchema {
668
+ type: typeof SchemaType.OBJECT;
669
+ /** Describes the properties of the JSON object. Must not be empty. */
670
+ properties: {
671
+ [k: string]: Schema;
672
+ };
673
+ /**
674
+ * A list of keys declared in the properties object.
675
+ * Required properties will always be present in the generated object.
676
+ */
677
+ required?: string[];
678
+ }
679
+
680
+ /**
681
+ * Possible outcomes of code execution.
682
+ * @public
683
+ */
684
+ export declare enum Outcome {
685
+ /**
686
+ * Unspecified status. This value should not be used.
687
+ */
688
+ OUTCOME_UNSPECIFIED = "outcome_unspecified",
689
+ /**
690
+ * Code execution completed successfully.
691
+ */
692
+ OUTCOME_OK = "outcome_ok",
693
+ /**
694
+ * Code execution finished but with a failure. `stderr` should contain the
695
+ * reason.
696
+ */
697
+ OUTCOME_FAILED = "outcome_failed",
698
+ /**
699
+ * Code execution ran for too long, and was cancelled. There may or may not
700
+ * be a partial output present.
701
+ */
702
+ OUTCOME_DEADLINE_EXCEEDED = "outcome_deadline_exceeded"
703
+ }
704
+
705
+ /**
706
+ * Content part - includes text or image part types.
707
+ * @public
708
+ */
709
+ export declare type Part = TextPart | InlineDataPart | FunctionCallPart | FunctionResponsePart | FileDataPart | ExecutableCodePart | CodeExecutionResultPart;
710
+
711
+ /**
712
+ * Params passed to getGenerativeModel() or GoogleAIFileManager().
713
+ * @public
714
+ */
715
+ export declare interface RequestOptions {
716
+ /**
717
+ * Request timeout in milliseconds.
718
+ */
719
+ timeout?: number;
720
+ /**
721
+ * Version of API endpoint to call (e.g. "v1" or "v1beta"). If not specified,
722
+ * defaults to latest stable version.
723
+ */
724
+ apiVersion?: string;
725
+ /**
726
+ * Additional attribution information to include in the x-goog-api-client header.
727
+ * Used by wrapper SDKs.
728
+ */
729
+ apiClient?: string;
730
+ /**
731
+ * Base endpoint url. Defaults to "https://generativelanguage.googleapis.com"
732
+ */
733
+ baseUrl?: string;
734
+ /**
735
+ * Custom HTTP request headers.
736
+ */
737
+ customHeaders?: Headers | Record<string, string>;
738
+ }
739
+
740
+ /**
741
+ * Schema passed to `GenerationConfig.responseSchema`
742
+ * @public
743
+ */
744
+ export declare type ResponseSchema = Schema;
745
+
746
+ /**
747
+ * Standard RPC error status object.
748
+ * @public
749
+ */
750
+ export declare interface RpcStatus {
751
+ /**
752
+ * Error status code
753
+ */
754
+ code: number;
755
+ /**
756
+ * A developer-facing error message.
757
+ */
758
+ message: string;
759
+ /**
760
+ * A list of messages that carry the error details.
761
+ */
762
+ details?: ErrorDetails[];
763
+ }
764
+
765
+ /**
766
+ * Schema is used to define the format of input/output data.
767
+ * Represents a select subset of an OpenAPI 3.0 schema object.
768
+ * More fields may be added in the future as needed.
769
+ * @public
770
+ */
771
+ export declare type Schema = StringSchema | NumberSchema | IntegerSchema | BooleanSchema | ArraySchema | ObjectSchema;
772
+
773
+ /**
774
+ * Contains the list of OpenAPI data types
775
+ * as defined by https://swagger.io/docs/specification/data-models/data-types/
776
+ * @public
777
+ */
778
+ export declare enum SchemaType {
779
+ /** String type. */
780
+ STRING = "string",
781
+ /** Number type. */
782
+ NUMBER = "number",
783
+ /** Integer type. */
784
+ INTEGER = "integer",
785
+ /** Boolean type. */
786
+ BOOLEAN = "boolean",
787
+ /** Array type. */
788
+ ARRAY = "array",
789
+ /** Object type. */
790
+ OBJECT = "object"
791
+ }
792
+
793
+ /**
794
+ * Describes a simple string schema, with or without format
795
+ *
796
+ * @public
797
+ */
798
+ export declare interface SimpleStringSchema extends BaseSchema {
799
+ type: typeof SchemaType.STRING;
800
+ format?: "date-time" | undefined;
801
+ enum?: never;
802
+ }
803
+
804
+ /**
805
+ * Params passed to atomic asynchronous operations.
806
+ * @public
807
+ */
808
+ export declare interface SingleRequestOptions extends RequestOptions {
809
+ /**
810
+ * An object that may be used to abort asynchronous requests. The request may
811
+ * also be aborted due to the expiration of the timeout value, if provided.
812
+ *
813
+ * NOTE: AbortSignal is a client-only operation. Using it to cancel an
814
+ * operation will not cancel the request in the service. You will still
815
+ * be charged usage for any applicable operations.
816
+ */
817
+ signal?: AbortSignal;
818
+ }
819
+
820
+ /**
821
+ * Describes a string.
822
+ *
823
+ * @public
824
+ */
825
+ export declare type StringSchema = SimpleStringSchema | EnumStringSchema;
826
+
827
+ /**
828
+ * Content part interface if the part represents a text string.
829
+ * @public
830
+ */
831
+ export declare interface TextPart {
832
+ text: string;
833
+ inlineData?: never;
834
+ functionCall?: never;
835
+ functionResponse?: never;
836
+ fileData?: never;
837
+ executableCode?: never;
838
+ codeExecutionResult?: never;
839
+ }
840
+
841
+ /**
842
+ * Defines a tool that model can call to access external knowledge.
843
+ * @public
844
+ */
845
+ export declare type Tool = FunctionDeclarationsTool | CodeExecutionTool | GoogleSearchRetrievalTool;
846
+
847
+ /**
848
+ * Tool config. This config is shared for all tools provided in the request.
849
+ * @public
850
+ */
851
+ export declare interface ToolConfig {
852
+ functionCallingConfig: FunctionCallingConfig;
853
+ }
854
+
855
+ /**
856
+ * Response from calling {@link GoogleAIFileManager.uploadFile}
857
+ * @public
858
+ */
859
+ export declare interface UploadFileResponse {
860
+ file: FileMetadataResponse;
861
+ }
862
+
863
+ /**
864
+ * Metadata populated when video has been processed.
865
+ * @public
866
+ */
867
+ export declare interface VideoMetadata {
868
+ /**
869
+ * The video duration in
870
+ * protobuf {@link https://cloud.google.com/ruby/docs/reference/google-cloud-workflows-v1/latest/Google-Protobuf-Duration#json-mapping | Duration} format.
871
+ */
872
+ videoDuration: string;
873
+ }
874
+
875
+ export { }
backend-old/node_modules/@google/generative-ai/dist/server/src/errors.d.ts ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2024 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { ErrorDetails } from "../types";
18
+ /**
19
+ * Basic error type for this SDK.
20
+ * @public
21
+ */
22
+ export declare class GoogleGenerativeAIError extends Error {
23
+ constructor(message: string);
24
+ }
25
+ /**
26
+ * Errors in the contents of a response from the model. This includes parsing
27
+ * errors, or responses including a safety block reason.
28
+ * @public
29
+ */
30
+ export declare class GoogleGenerativeAIResponseError<T> extends GoogleGenerativeAIError {
31
+ response?: T;
32
+ constructor(message: string, response?: T);
33
+ }
34
+ /**
35
+ * Error class covering HTTP errors when calling the server. Includes HTTP
36
+ * status, statusText, and optional details, if provided in the server response.
37
+ * @public
38
+ */
39
+ export declare class GoogleGenerativeAIFetchError extends GoogleGenerativeAIError {
40
+ status?: number;
41
+ statusText?: string;
42
+ errorDetails?: ErrorDetails[];
43
+ constructor(message: string, status?: number, statusText?: string, errorDetails?: ErrorDetails[]);
44
+ }
45
+ /**
46
+ * Errors in the contents of a request originating from user input.
47
+ * @public
48
+ */
49
+ export declare class GoogleGenerativeAIRequestInputError extends GoogleGenerativeAIError {
50
+ }
51
+ /**
52
+ * Error thrown when a request is aborted, either due to a timeout or
53
+ * intentional cancellation by the user.
54
+ * @public
55
+ */
56
+ export declare class GoogleGenerativeAIAbortError extends GoogleGenerativeAIError {
57
+ }
backend-old/node_modules/@google/generative-ai/dist/server/src/gen-ai.d.ts ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2024 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { CachedContent, ModelParams, RequestOptions } from "../types";
18
+ import { GenerativeModel } from "./models/generative-model";
19
+ export { ChatSession } from "./methods/chat-session";
20
+ export { GenerativeModel };
21
+ /**
22
+ * Top-level class for this SDK
23
+ * @public
24
+ */
25
+ export declare class GoogleGenerativeAI {
26
+ apiKey: string;
27
+ constructor(apiKey: string);
28
+ /**
29
+ * Gets a {@link GenerativeModel} instance for the provided model name.
30
+ */
31
+ getGenerativeModel(modelParams: ModelParams, requestOptions?: RequestOptions): GenerativeModel;
32
+ /**
33
+ * Creates a {@link GenerativeModel} instance from provided content cache.
34
+ */
35
+ getGenerativeModelFromCachedContent(cachedContent: CachedContent, modelParams?: Partial<ModelParams>, requestOptions?: RequestOptions): GenerativeModel;
36
+ }
backend-old/node_modules/@google/generative-ai/dist/server/src/index.d.ts ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2024 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ export * from "../types";
18
+ export * from "./gen-ai";
19
+ export * from "./errors";
backend-old/node_modules/@google/generative-ai/dist/server/src/methods/chat-session-helpers.d.ts ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2024 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { Content, GenerateContentResponse } from "../../types";
18
+ export declare function validateChatHistory(history: Content[]): void;
19
+ /**
20
+ * Returns true if the response is valid (could be appended to the history), flase otherwise.
21
+ */
22
+ export declare function isValidResponse(response: GenerateContentResponse): boolean;
backend-old/node_modules/@google/generative-ai/dist/server/src/methods/chat-session.d.ts ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2024 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { Content, GenerateContentResult, GenerateContentStreamResult, Part, RequestOptions, SingleRequestOptions, StartChatParams } from "../../types";
18
+ /**
19
+ * ChatSession class that enables sending chat messages and stores
20
+ * history of sent and received messages so far.
21
+ *
22
+ * @public
23
+ */
24
+ export declare class ChatSession {
25
+ model: string;
26
+ params?: StartChatParams;
27
+ private _requestOptions;
28
+ private _apiKey;
29
+ private _history;
30
+ private _sendPromise;
31
+ constructor(apiKey: string, model: string, params?: StartChatParams, _requestOptions?: RequestOptions);
32
+ /**
33
+ * Gets the chat history so far. Blocked prompts are not added to history.
34
+ * Blocked candidates are not added to history, nor are the prompts that
35
+ * generated them.
36
+ */
37
+ getHistory(): Promise<Content[]>;
38
+ /**
39
+ * Sends a chat message and receives a non-streaming
40
+ * {@link GenerateContentResult}.
41
+ *
42
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
43
+ * take precedence over the {@link RequestOptions} values provided to
44
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
45
+ */
46
+ sendMessage(request: string | Array<string | Part>, requestOptions?: SingleRequestOptions): Promise<GenerateContentResult>;
47
+ /**
48
+ * Sends a chat message and receives the response as a
49
+ * {@link GenerateContentStreamResult} containing an iterable stream
50
+ * and a response promise.
51
+ *
52
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
53
+ * take precedence over the {@link RequestOptions} values provided to
54
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
55
+ */
56
+ sendMessageStream(request: string | Array<string | Part>, requestOptions?: SingleRequestOptions): Promise<GenerateContentStreamResult>;
57
+ }
backend-old/node_modules/@google/generative-ai/dist/server/src/methods/count-tokens.d.ts ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2024 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { CountTokensRequest, CountTokensResponse, SingleRequestOptions } from "../../types";
18
+ export declare function countTokens(apiKey: string, model: string, params: CountTokensRequest, singleRequestOptions: SingleRequestOptions): Promise<CountTokensResponse>;
backend-old/node_modules/@google/generative-ai/dist/server/src/methods/embed-content.d.ts ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2024 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { BatchEmbedContentsRequest, BatchEmbedContentsResponse, EmbedContentRequest, EmbedContentResponse, RequestOptions } from "../../types";
18
+ export declare function embedContent(apiKey: string, model: string, params: EmbedContentRequest, requestOptions?: RequestOptions): Promise<EmbedContentResponse>;
19
+ export declare function batchEmbedContents(apiKey: string, model: string, params: BatchEmbedContentsRequest, requestOptions?: RequestOptions): Promise<BatchEmbedContentsResponse>;
backend-old/node_modules/@google/generative-ai/dist/server/src/methods/generate-content.d.ts ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2024 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { GenerateContentRequest, GenerateContentResult, GenerateContentStreamResult, SingleRequestOptions } from "../../types";
18
+ export declare function generateContentStream(apiKey: string, model: string, params: GenerateContentRequest, requestOptions: SingleRequestOptions): Promise<GenerateContentStreamResult>;
19
+ export declare function generateContent(apiKey: string, model: string, params: GenerateContentRequest, requestOptions?: SingleRequestOptions): Promise<GenerateContentResult>;
backend-old/node_modules/@google/generative-ai/dist/server/src/models/generative-model.d.ts ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2024 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { BatchEmbedContentsRequest, BatchEmbedContentsResponse, CachedContent, Content, CountTokensRequest, CountTokensResponse, EmbedContentRequest, EmbedContentResponse, GenerateContentRequest, GenerateContentResult, GenerateContentStreamResult, GenerationConfig, ModelParams, Part, RequestOptions, SafetySetting, SingleRequestOptions, StartChatParams, Tool, ToolConfig } from "../../types";
18
+ import { ChatSession } from "../methods/chat-session";
19
+ /**
20
+ * Class for generative model APIs.
21
+ * @public
22
+ */
23
+ export declare class GenerativeModel {
24
+ apiKey: string;
25
+ private _requestOptions;
26
+ model: string;
27
+ generationConfig: GenerationConfig;
28
+ safetySettings: SafetySetting[];
29
+ tools?: Tool[];
30
+ toolConfig?: ToolConfig;
31
+ systemInstruction?: Content;
32
+ cachedContent: CachedContent;
33
+ constructor(apiKey: string, modelParams: ModelParams, _requestOptions?: RequestOptions);
34
+ /**
35
+ * Makes a single non-streaming call to the model
36
+ * and returns an object containing a single {@link GenerateContentResponse}.
37
+ *
38
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
39
+ * take precedence over the {@link RequestOptions} values provided to
40
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
41
+ */
42
+ generateContent(request: GenerateContentRequest | string | Array<string | Part>, requestOptions?: SingleRequestOptions): Promise<GenerateContentResult>;
43
+ /**
44
+ * Makes a single streaming call to the model and returns an object
45
+ * containing an iterable stream that iterates over all chunks in the
46
+ * streaming response as well as a promise that returns the final
47
+ * aggregated response.
48
+ *
49
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
50
+ * take precedence over the {@link RequestOptions} values provided to
51
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
52
+ */
53
+ generateContentStream(request: GenerateContentRequest | string | Array<string | Part>, requestOptions?: SingleRequestOptions): Promise<GenerateContentStreamResult>;
54
+ /**
55
+ * Gets a new {@link ChatSession} instance which can be used for
56
+ * multi-turn chats.
57
+ */
58
+ startChat(startChatParams?: StartChatParams): ChatSession;
59
+ /**
60
+ * Counts the tokens in the provided request.
61
+ *
62
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
63
+ * take precedence over the {@link RequestOptions} values provided to
64
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
65
+ */
66
+ countTokens(request: CountTokensRequest | string | Array<string | Part>, requestOptions?: SingleRequestOptions): Promise<CountTokensResponse>;
67
+ /**
68
+ * Embeds the provided content.
69
+ *
70
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
71
+ * take precedence over the {@link RequestOptions} values provided to
72
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
73
+ */
74
+ embedContent(request: EmbedContentRequest | string | Array<string | Part>, requestOptions?: SingleRequestOptions): Promise<EmbedContentResponse>;
75
+ /**
76
+ * Embeds an array of {@link EmbedContentRequest}s.
77
+ *
78
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
79
+ * take precedence over the {@link RequestOptions} values provided to
80
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
81
+ */
82
+ batchEmbedContents(batchEmbedContentRequest: BatchEmbedContentsRequest, requestOptions?: SingleRequestOptions): Promise<BatchEmbedContentsResponse>;
83
+ }
backend-old/node_modules/@google/generative-ai/dist/server/src/requests/request-helpers.d.ts ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2024 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { Content, CountTokensRequest, EmbedContentRequest, GenerateContentRequest, ModelParams, Part, _CountTokensRequestInternal } from "../../types";
18
+ export declare function formatSystemInstruction(input?: string | Part | Content): Content | undefined;
19
+ export declare function formatNewContent(request: string | Array<string | Part>): Content;
20
+ export declare function formatCountTokensInput(params: CountTokensRequest | string | Array<string | Part>, modelParams?: ModelParams): _CountTokensRequestInternal;
21
+ export declare function formatGenerateContentInput(params: GenerateContentRequest | string | Array<string | Part>): GenerateContentRequest;
22
+ export declare function formatEmbedContentInput(params: EmbedContentRequest | string | Array<string | Part>): EmbedContentRequest;
backend-old/node_modules/@google/generative-ai/dist/server/src/requests/request.d.ts ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2024 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { RequestOptions, SingleRequestOptions } from "../../types";
18
+ export declare const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com";
19
+ export declare const DEFAULT_API_VERSION = "v1beta";
20
+ export declare enum Task {
21
+ GENERATE_CONTENT = "generateContent",
22
+ STREAM_GENERATE_CONTENT = "streamGenerateContent",
23
+ COUNT_TOKENS = "countTokens",
24
+ EMBED_CONTENT = "embedContent",
25
+ BATCH_EMBED_CONTENTS = "batchEmbedContents"
26
+ }
27
+ export declare class RequestUrl {
28
+ model: string;
29
+ task: Task;
30
+ apiKey: string;
31
+ stream: boolean;
32
+ requestOptions: RequestOptions;
33
+ constructor(model: string, task: Task, apiKey: string, stream: boolean, requestOptions: RequestOptions);
34
+ toString(): string;
35
+ }
36
+ /**
37
+ * Simple, but may become more complex if we add more versions to log.
38
+ */
39
+ export declare function getClientHeaders(requestOptions: RequestOptions): string;
40
+ export declare function getHeaders(url: RequestUrl): Promise<Headers>;
41
+ export declare function constructModelRequest(model: string, task: Task, apiKey: string, stream: boolean, body: string, requestOptions: SingleRequestOptions): Promise<{
42
+ url: string;
43
+ fetchOptions: RequestInit;
44
+ }>;
45
+ export declare function makeModelRequest(model: string, task: Task, apiKey: string, stream: boolean, body: string, requestOptions?: SingleRequestOptions, fetchFn?: typeof fetch): Promise<Response>;
46
+ export declare function makeRequest(url: string, fetchOptions: RequestInit, fetchFn?: typeof fetch): Promise<Response>;
backend-old/node_modules/@google/generative-ai/dist/server/src/requests/response-helpers.d.ts ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2024 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { EnhancedGenerateContentResponse, FunctionCall, GenerateContentResponse } from "../../types";
18
+ /**
19
+ * Adds convenience helper methods to a response object, including stream
20
+ * chunks (as long as each chunk is a complete GenerateContentResponse JSON).
21
+ */
22
+ export declare function addHelpers(response: GenerateContentResponse): EnhancedGenerateContentResponse;
23
+ /**
24
+ * Returns all text found in all parts of first candidate.
25
+ */
26
+ export declare function getText(response: GenerateContentResponse): string;
27
+ /**
28
+ * Returns functionCall of first candidate.
29
+ */
30
+ export declare function getFunctionCalls(response: GenerateContentResponse): FunctionCall[];
31
+ export declare function formatBlockErrorMessage(response: GenerateContentResponse): string;
backend-old/node_modules/@google/generative-ai/dist/server/src/requests/stream-reader.d.ts ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2024 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { GenerateContentResponse, GenerateContentStreamResult } from "../../types";
18
+ /**
19
+ * Process a response.body stream from the backend and return an
20
+ * iterator that provides one complete GenerateContentResponse at a time
21
+ * and a promise that resolves with a single aggregated
22
+ * GenerateContentResponse.
23
+ *
24
+ * @param response - Response from a fetch call
25
+ */
26
+ export declare function processStream(response: Response): GenerateContentStreamResult;
27
+ /**
28
+ * Reads a raw stream from the fetch response and join incomplete
29
+ * chunks, returning a new stream that provides a single complete
30
+ * GenerateContentResponse in each iteration.
31
+ */
32
+ export declare function getResponseStream<T>(inputStream: ReadableStream<string>): ReadableStream<T>;
33
+ /**
34
+ * Aggregates an array of `GenerateContentResponse`s into a single
35
+ * GenerateContentResponse.
36
+ */
37
+ export declare function aggregateResponses(responses: GenerateContentResponse[]): GenerateContentResponse;
backend-old/node_modules/@google/generative-ai/dist/server/src/server/cache-manager.d.ts ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2024 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { CachedContent, RequestOptions } from "../../types";
18
+ import { CachedContentCreateParams, CachedContentUpdateParams, ListCacheResponse, ListParams } from "../../types/server";
19
+ /**
20
+ * Class for managing GoogleAI content caches.
21
+ * @public
22
+ */
23
+ export declare class GoogleAICacheManager {
24
+ apiKey: string;
25
+ private _requestOptions?;
26
+ constructor(apiKey: string, _requestOptions?: RequestOptions);
27
+ /**
28
+ * Upload a new content cache
29
+ */
30
+ create(createOptions: CachedContentCreateParams): Promise<CachedContent>;
31
+ /**
32
+ * List all uploaded content caches
33
+ */
34
+ list(listParams?: ListParams): Promise<ListCacheResponse>;
35
+ /**
36
+ * Get a content cache
37
+ */
38
+ get(name: string): Promise<CachedContent>;
39
+ /**
40
+ * Update an existing content cache
41
+ */
42
+ update(name: string, updateParams: CachedContentUpdateParams): Promise<CachedContent>;
43
+ /**
44
+ * Delete content cache with given name
45
+ */
46
+ delete(name: string): Promise<void>;
47
+ }
backend-old/node_modules/@google/generative-ai/dist/server/src/server/constants.d.ts ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2024 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ export declare enum RpcTask {
18
+ UPLOAD = "upload",
19
+ LIST = "list",
20
+ GET = "get",
21
+ DELETE = "delete",
22
+ UPDATE = "update",
23
+ CREATE = "create"
24
+ }
backend-old/node_modules/@google/generative-ai/dist/server/src/server/file-manager.d.ts ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2024 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /// <reference types="node" />
18
+ import { RequestOptions, SingleRequestOptions } from "../../types";
19
+ import { FileMetadata, FileMetadataResponse, ListFilesResponse, ListParams, UploadFileResponse } from "../../types/server";
20
+ export interface UploadMetadata {
21
+ name?: string;
22
+ ["display_name"]?: string;
23
+ }
24
+ /**
25
+ * Class for managing GoogleAI file uploads.
26
+ * @public
27
+ */
28
+ export declare class GoogleAIFileManager {
29
+ apiKey: string;
30
+ private _requestOptions;
31
+ constructor(apiKey: string, _requestOptions?: RequestOptions);
32
+ /**
33
+ * Upload a file.
34
+ */
35
+ uploadFile(fileData: string | Buffer, fileMetadata: FileMetadata): Promise<UploadFileResponse>;
36
+ /**
37
+ * List all uploaded files.
38
+ *
39
+ * Any fields set in the optional {@link SingleRequestOptions} parameter will take
40
+ * precedence over the {@link RequestOptions} values provided at the time of the
41
+ * {@link GoogleAIFileManager} initialization.
42
+ */
43
+ listFiles(listParams?: ListParams, requestOptions?: SingleRequestOptions): Promise<ListFilesResponse>;
44
+ /**
45
+ * Get metadata for file with given ID.
46
+ *
47
+ * Any fields set in the optional {@link SingleRequestOptions} parameter will take
48
+ * precedence over the {@link RequestOptions} values provided at the time of the
49
+ * {@link GoogleAIFileManager} initialization.
50
+ */
51
+ getFile(fileId: string, requestOptions?: SingleRequestOptions): Promise<FileMetadataResponse>;
52
+ /**
53
+ * Delete file with given ID.
54
+ */
55
+ deleteFile(fileId: string): Promise<void>;
56
+ }
57
+ export declare function getUploadMetadata(inputMetadata: FileMetadata): FileMetadata;
backend-old/node_modules/@google/generative-ai/dist/server/src/server/index.d.ts ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2024 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ export { GoogleAIFileManager } from "./file-manager";
18
+ export { GoogleAICacheManager } from "./cache-manager";
19
+ export * from "../../types/server";
backend-old/node_modules/@google/generative-ai/dist/server/src/server/request.d.ts ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2024 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { RequestOptions, SingleRequestOptions } from "../../types";
18
+ import { RpcTask } from "./constants";
19
+ export declare class ServerRequestUrl {
20
+ task: RpcTask;
21
+ apiKey: string;
22
+ requestOptions?: SingleRequestOptions;
23
+ protected _url: URL;
24
+ constructor(task: RpcTask, apiKey: string, requestOptions?: SingleRequestOptions);
25
+ appendPath(path: string): void;
26
+ appendParam(key: string, value: string): void;
27
+ toString(): string;
28
+ }
29
+ export declare class CachedContentUrl extends ServerRequestUrl {
30
+ task: RpcTask;
31
+ apiKey: string;
32
+ requestOptions?: RequestOptions;
33
+ constructor(task: RpcTask, apiKey: string, requestOptions?: RequestOptions);
34
+ }
35
+ export declare class FilesRequestUrl extends ServerRequestUrl {
36
+ task: RpcTask;
37
+ apiKey: string;
38
+ requestOptions?: RequestOptions;
39
+ constructor(task: RpcTask, apiKey: string, requestOptions?: RequestOptions);
40
+ }
41
+ export declare function getHeaders(url: ServerRequestUrl): Headers;
42
+ export declare function makeServerRequest(url: FilesRequestUrl, headers: Headers, body?: Blob | string, fetchFn?: typeof fetch): Promise<Response>;
backend-old/node_modules/@google/generative-ai/dist/server/types/content.d.ts ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2024 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ export * from "./function-calling";
18
+ /**
19
+ * Content type for both prompts and response candidates.
20
+ * @public
21
+ */
22
+ export interface Content {
23
+ role: string;
24
+ parts: Part[];
25
+ }
26
+ /**
27
+ * Content part - includes text or image part types.
28
+ * @public
29
+ */
30
+ export type Part = TextPart | InlineDataPart | FunctionCallPart | FunctionResponsePart | FileDataPart | ExecutableCodePart | CodeExecutionResultPart;
31
+ /**
32
+ * Content part interface if the part represents a text string.
33
+ * @public
34
+ */
35
+ export interface TextPart {
36
+ text: string;
37
+ inlineData?: never;
38
+ functionCall?: never;
39
+ functionResponse?: never;
40
+ fileData?: never;
41
+ executableCode?: never;
42
+ codeExecutionResult?: never;
43
+ }
44
+ /**
45
+ * Content part interface if the part represents an image.
46
+ * @public
47
+ */
48
+ export interface InlineDataPart {
49
+ text?: never;
50
+ inlineData: GenerativeContentBlob;
51
+ functionCall?: never;
52
+ functionResponse?: never;
53
+ fileData?: never;
54
+ executableCode?: never;
55
+ codeExecutionResult?: never;
56
+ }
57
+ /**
58
+ * Content part interface if the part represents a FunctionCall.
59
+ * @public
60
+ */
61
+ export interface FunctionCallPart {
62
+ text?: never;
63
+ inlineData?: never;
64
+ functionCall: FunctionCall;
65
+ functionResponse?: never;
66
+ fileData?: never;
67
+ executableCode?: never;
68
+ codeExecutionResult?: never;
69
+ }
70
+ /**
71
+ * Content part interface if the part represents FunctionResponse.
72
+ * @public
73
+ */
74
+ export interface FunctionResponsePart {
75
+ text?: never;
76
+ inlineData?: never;
77
+ functionCall?: never;
78
+ functionResponse: FunctionResponse;
79
+ fileData?: never;
80
+ executableCode?: never;
81
+ codeExecutionResult?: never;
82
+ }
83
+ /**
84
+ * Content part interface if the part represents FileData.
85
+ * @public
86
+ */
87
+ export interface FileDataPart {
88
+ text?: never;
89
+ inlineData?: never;
90
+ functionCall?: never;
91
+ functionResponse?: never;
92
+ fileData: FileData;
93
+ executableCode?: never;
94
+ codeExecutionResult?: never;
95
+ }
96
+ /**
97
+ * Content part containing executable code generated by the model.
98
+ * @public
99
+ */
100
+ export interface ExecutableCodePart {
101
+ text?: never;
102
+ inlineData?: never;
103
+ functionCall?: never;
104
+ functionResponse?: never;
105
+ fileData?: never;
106
+ executableCode: ExecutableCode;
107
+ codeExecutionResult?: never;
108
+ }
109
+ /**
110
+ * Content part containing the result of executed code.
111
+ * @public
112
+ */
113
+ export interface CodeExecutionResultPart {
114
+ text?: never;
115
+ inlineData?: never;
116
+ functionCall?: never;
117
+ functionResponse?: never;
118
+ fileData?: never;
119
+ executableCode?: never;
120
+ codeExecutionResult: CodeExecutionResult;
121
+ }
122
+ /**
123
+ * A predicted [FunctionCall] returned from the model
124
+ * that contains a string representing the [FunctionDeclaration.name]
125
+ * and a structured JSON object containing the parameters and their values.
126
+ * @public
127
+ */
128
+ export interface FunctionCall {
129
+ name: string;
130
+ args: object;
131
+ }
132
+ /**
133
+ * The result output from a [FunctionCall] that contains a string
134
+ * representing the [FunctionDeclaration.name]
135
+ * and a structured JSON object containing any output
136
+ * from the function is used as context to the model.
137
+ * This should contain the result of a [FunctionCall]
138
+ * made based on model prediction.
139
+ * @public
140
+ */
141
+ export interface FunctionResponse {
142
+ name: string;
143
+ response: object;
144
+ }
145
+ /**
146
+ * Interface for sending an image.
147
+ * @public
148
+ */
149
+ export interface GenerativeContentBlob {
150
+ mimeType: string;
151
+ /**
152
+ * Image as a base64 string.
153
+ */
154
+ data: string;
155
+ }
156
+ /**
157
+ * Data pointing to a file uploaded with the Files API.
158
+ * @public
159
+ */
160
+ export interface FileData {
161
+ mimeType: string;
162
+ fileUri: string;
163
+ }
164
+ /**
165
+ * Code generated by the model that is meant to be executed, where the result
166
+ * is returned to the model.
167
+ * Only generated when using the code execution tool, in which the code will
168
+ * be automatically executed, and a corresponding `CodeExecutionResult` will
169
+ * also be generated.
170
+ *
171
+ * @public
172
+ */
173
+ export interface ExecutableCode {
174
+ /**
175
+ * Programming language of the `code`.
176
+ */
177
+ language: ExecutableCodeLanguage;
178
+ /**
179
+ * The code to be executed.
180
+ */
181
+ code: string;
182
+ }
183
+ /**
184
+ * @public
185
+ */
186
+ export declare enum ExecutableCodeLanguage {
187
+ LANGUAGE_UNSPECIFIED = "language_unspecified",
188
+ PYTHON = "python"
189
+ }
190
+ /**
191
+ * Result of executing the `ExecutableCode`.
192
+ * Only generated when using code execution, and always follows a `Part`
193
+ * containing the `ExecutableCode`.
194
+ * @public
195
+ */
196
+ export interface CodeExecutionResult {
197
+ /**
198
+ * Outcome of the code execution.
199
+ */
200
+ outcome: Outcome;
201
+ /**
202
+ * Contains stdout when code execution is successful, stderr or other
203
+ * description otherwise.
204
+ */
205
+ output: string;
206
+ }
207
+ /**
208
+ * Possible outcomes of code execution.
209
+ * @public
210
+ */
211
+ export declare enum Outcome {
212
+ /**
213
+ * Unspecified status. This value should not be used.
214
+ */
215
+ OUTCOME_UNSPECIFIED = "outcome_unspecified",
216
+ /**
217
+ * Code execution completed successfully.
218
+ */
219
+ OUTCOME_OK = "outcome_ok",
220
+ /**
221
+ * Code execution finished but with a failure. `stderr` should contain the
222
+ * reason.
223
+ */
224
+ OUTCOME_FAILED = "outcome_failed",
225
+ /**
226
+ * Code execution ran for too long, and was cancelled. There may or may not
227
+ * be a partial output present.
228
+ */
229
+ OUTCOME_DEADLINE_EXCEEDED = "outcome_deadline_exceeded"
230
+ }
backend-old/node_modules/@google/generative-ai/dist/server/types/enums.d.ts ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2024 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * Possible roles.
19
+ * @public
20
+ */
21
+ export declare const POSSIBLE_ROLES: readonly ["user", "model", "function", "system"];
22
+ /**
23
+ * Harm categories that would cause prompts or candidates to be blocked.
24
+ * @public
25
+ */
26
+ export declare enum HarmCategory {
27
+ HARM_CATEGORY_UNSPECIFIED = "HARM_CATEGORY_UNSPECIFIED",
28
+ HARM_CATEGORY_HATE_SPEECH = "HARM_CATEGORY_HATE_SPEECH",
29
+ HARM_CATEGORY_SEXUALLY_EXPLICIT = "HARM_CATEGORY_SEXUALLY_EXPLICIT",
30
+ HARM_CATEGORY_HARASSMENT = "HARM_CATEGORY_HARASSMENT",
31
+ HARM_CATEGORY_DANGEROUS_CONTENT = "HARM_CATEGORY_DANGEROUS_CONTENT",
32
+ HARM_CATEGORY_CIVIC_INTEGRITY = "HARM_CATEGORY_CIVIC_INTEGRITY"
33
+ }
34
+ /**
35
+ * Threshold above which a prompt or candidate will be blocked.
36
+ * @public
37
+ */
38
+ export declare enum HarmBlockThreshold {
39
+ /** Threshold is unspecified. */
40
+ HARM_BLOCK_THRESHOLD_UNSPECIFIED = "HARM_BLOCK_THRESHOLD_UNSPECIFIED",
41
+ /** Content with NEGLIGIBLE will be allowed. */
42
+ BLOCK_LOW_AND_ABOVE = "BLOCK_LOW_AND_ABOVE",
43
+ /** Content with NEGLIGIBLE and LOW will be allowed. */
44
+ BLOCK_MEDIUM_AND_ABOVE = "BLOCK_MEDIUM_AND_ABOVE",
45
+ /** Content with NEGLIGIBLE, LOW, and MEDIUM will be allowed. */
46
+ BLOCK_ONLY_HIGH = "BLOCK_ONLY_HIGH",
47
+ /** All content will be allowed. */
48
+ BLOCK_NONE = "BLOCK_NONE"
49
+ }
50
+ /**
51
+ * Probability that a prompt or candidate matches a harm category.
52
+ * @public
53
+ */
54
+ export declare enum HarmProbability {
55
+ /** Probability is unspecified. */
56
+ HARM_PROBABILITY_UNSPECIFIED = "HARM_PROBABILITY_UNSPECIFIED",
57
+ /** Content has a negligible chance of being unsafe. */
58
+ NEGLIGIBLE = "NEGLIGIBLE",
59
+ /** Content has a low chance of being unsafe. */
60
+ LOW = "LOW",
61
+ /** Content has a medium chance of being unsafe. */
62
+ MEDIUM = "MEDIUM",
63
+ /** Content has a high chance of being unsafe. */
64
+ HIGH = "HIGH"
65
+ }
66
+ /**
67
+ * Reason that a prompt was blocked.
68
+ * @public
69
+ */
70
+ export declare enum BlockReason {
71
+ BLOCKED_REASON_UNSPECIFIED = "BLOCKED_REASON_UNSPECIFIED",
72
+ SAFETY = "SAFETY",
73
+ OTHER = "OTHER"
74
+ }
75
+ /**
76
+ * Reason that a candidate finished.
77
+ * @public
78
+ */
79
+ export declare enum FinishReason {
80
+ FINISH_REASON_UNSPECIFIED = "FINISH_REASON_UNSPECIFIED",
81
+ STOP = "STOP",
82
+ MAX_TOKENS = "MAX_TOKENS",
83
+ SAFETY = "SAFETY",
84
+ RECITATION = "RECITATION",
85
+ LANGUAGE = "LANGUAGE",
86
+ BLOCKLIST = "BLOCKLIST",
87
+ PROHIBITED_CONTENT = "PROHIBITED_CONTENT",
88
+ SPII = "SPII",
89
+ MALFORMED_FUNCTION_CALL = "MALFORMED_FUNCTION_CALL",
90
+ OTHER = "OTHER"
91
+ }
92
+ /**
93
+ * Task type for embedding content.
94
+ * @public
95
+ */
96
+ export declare enum TaskType {
97
+ TASK_TYPE_UNSPECIFIED = "TASK_TYPE_UNSPECIFIED",
98
+ RETRIEVAL_QUERY = "RETRIEVAL_QUERY",
99
+ RETRIEVAL_DOCUMENT = "RETRIEVAL_DOCUMENT",
100
+ SEMANTIC_SIMILARITY = "SEMANTIC_SIMILARITY",
101
+ CLASSIFICATION = "CLASSIFICATION",
102
+ CLUSTERING = "CLUSTERING"
103
+ }
104
+ /**
105
+ * @public
106
+ */
107
+ export declare enum FunctionCallingMode {
108
+ MODE_UNSPECIFIED = "MODE_UNSPECIFIED",
109
+ AUTO = "AUTO",
110
+ ANY = "ANY",
111
+ NONE = "NONE"
112
+ }
113
+ /**
114
+ * The mode of the predictor to be used in dynamic retrieval.
115
+ * @public
116
+ */
117
+ export declare enum DynamicRetrievalMode {
118
+ MODE_UNSPECIFIED = "MODE_UNSPECIFIED",
119
+ MODE_DYNAMIC = "MODE_DYNAMIC"
120
+ }
backend-old/node_modules/@google/generative-ai/dist/server/types/function-calling.d.ts ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2024 Google LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { FunctionCallingMode } from "./enums";
18
+ /**
19
+ * Structured representation of a function declaration as defined by the
20
+ * [OpenAPI 3.0 specification](https://spec.openapis.org/oas/v3.0.3). Included
21
+ * in this declaration are the function name and parameters. This
22
+ * FunctionDeclaration is a representation of a block of code that can be used
23
+ * as a Tool by the model and executed by the client.
24
+ * @public
25
+ */
26
+ export declare interface FunctionDeclaration {
27
+ /**
28
+ * The name of the function to call. Must start with a letter or an
29
+ * underscore. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with
30
+ * a max length of 64.
31
+ */
32
+ name: string;
33
+ /**
34
+ * Optional. Description and purpose of the function. Model uses it to decide
35
+ * how and whether to call the function.
36
+ */
37
+ description?: string;
38
+ /**
39
+ * Optional. Describes the parameters to this function in JSON Schema Object
40
+ * format. Reflects the Open API 3.03 Parameter Object. string Key: the name
41
+ * of the parameter. Parameter names are case sensitive. Schema Value: the
42
+ * Schema defining the type used for the parameter. For function with no
43
+ * parameters, this can be left unset.
44
+ *
45
+ * @example with 1 required and 1 optional parameter: type: OBJECT properties:
46
+ * ```
47
+ * param1:
48
+ *
49
+ * type: STRING
50
+ * param2:
51
+ *
52
+ * type: INTEGER
53
+ * required:
54
+ *
55
+ * - param1
56
+ * ```
57
+ */
58
+ parameters?: FunctionDeclarationSchema;
59
+ }
60
+ /**
61
+ * A FunctionDeclarationsTool is a piece of code that enables the system to
62
+ * interact with external systems to perform an action, or set of actions,
63
+ * outside of knowledge and scope of the model.
64
+ * @public
65
+ */
66
+ export declare interface FunctionDeclarationsTool {
67
+ /**
68
+ * Optional. One or more function declarations
69
+ * to be passed to the model along with the current user query. Model may
70
+ * decide to call a subset of these functions by populating
71
+ * [FunctionCall][content.part.functionCall] in the response. User should
72
+ * provide a [FunctionResponse][content.part.functionResponse] for each
73
+ * function call in the next turn. Based on the function responses, Model will
74
+ * generate the final response back to the user. Maximum 64 function
75
+ * declarations can be provided.
76
+ */
77
+ functionDeclarations?: FunctionDeclaration[];
78
+ }
79
+ /**
80
+ * Contains the list of OpenAPI data types
81
+ * as defined by https://swagger.io/docs/specification/data-models/data-types/
82
+ * @public
83
+ */
84
+ export declare enum SchemaType {
85
+ /** String type. */
86
+ STRING = "string",
87
+ /** Number type. */
88
+ NUMBER = "number",
89
+ /** Integer type. */
90
+ INTEGER = "integer",
91
+ /** Boolean type. */
92
+ BOOLEAN = "boolean",
93
+ /** Array type. */
94
+ ARRAY = "array",
95
+ /** Object type. */
96
+ OBJECT = "object"
97
+ }
98
+ /**
99
+ * Schema is used to define the format of input/output data.
100
+ * Represents a select subset of an OpenAPI 3.0 schema object.
101
+ * More fields may be added in the future as needed.
102
+ * @public
103
+ */
104
+ export type Schema = StringSchema | NumberSchema | IntegerSchema | BooleanSchema | ArraySchema | ObjectSchema;
105
+ /**
106
+ * Fields common to all Schema types.
107
+ *
108
+ * @internal
109
+ */
110
+ export interface BaseSchema {
111
+ /** Optional. Description of the value. */
112
+ description?: string;
113
+ /** If true, the value can be null. */
114
+ nullable?: boolean;
115
+ }
116
+ /**
117
+ * Describes a JSON-encodable floating point number.
118
+ *
119
+ * @public
120
+ */
121
+ export interface NumberSchema extends BaseSchema {
122
+ type: typeof SchemaType.NUMBER;
123
+ /** Optional. The format of the number. */
124
+ format?: "float" | "double";
125
+ }
126
+ /**
127
+ * Describes a JSON-encodable integer.
128
+ *
129
+ * @public
130
+ */
131
+ export interface IntegerSchema extends BaseSchema {
132
+ type: typeof SchemaType.INTEGER;
133
+ /** Optional. The format of the number. */
134
+ format?: "int32" | "int64";
135
+ }
136
+ /**
137
+ * Describes a string.
138
+ *
139
+ * @public
140
+ */
141
+ export type StringSchema = SimpleStringSchema | EnumStringSchema;
142
+ /**
143
+ * Describes a simple string schema, with or without format
144
+ *
145
+ * @public
146
+ */
147
+ export interface SimpleStringSchema extends BaseSchema {
148
+ type: typeof SchemaType.STRING;
149
+ format?: "date-time" | undefined;
150
+ enum?: never;
151
+ }
152
+ /**
153
+ * Describes a string enum
154
+ *
155
+ * @public
156
+ */
157
+ export interface EnumStringSchema extends BaseSchema {
158
+ type: typeof SchemaType.STRING;
159
+ format: "enum";
160
+ /** Possible values for this enum */
161
+ enum: string[];
162
+ }
163
+ /**
164
+ * Describes a boolean, either 'true' or 'false'.
165
+ *
166
+ * @public
167
+ */
168
+ export interface BooleanSchema extends BaseSchema {
169
+ type: typeof SchemaType.BOOLEAN;
170
+ }
171
+ /**
172
+ * Describes an array, an ordered list of values.
173
+ *
174
+ * @public
175
+ */
176
+ export interface ArraySchema extends BaseSchema {
177
+ type: typeof SchemaType.ARRAY;
178
+ /** A schema describing the entries in the array. */
179
+ items: Schema;
180
+ /** The minimum number of items in the array. */
181
+ minItems?: number;
182
+ /** The maximum number of items in the array. */
183
+ maxItems?: number;
184
+ }
185
+ /**
186
+ * Describes a JSON object, a mapping of specific keys to values.
187
+ *
188
+ * @public
189
+ */
190
+ export interface ObjectSchema extends BaseSchema {
191
+ type: typeof SchemaType.OBJECT;
192
+ /** Describes the properties of the JSON object. Must not be empty. */
193
+ properties: {
194
+ [k: string]: Schema;
195
+ };
196
+ /**
197
+ * A list of keys declared in the properties object.
198
+ * Required properties will always be present in the generated object.
199
+ */
200
+ required?: string[];
201
+ }
202
+ /**
203
+ * Schema for parameters passed to {@link FunctionDeclaration.parameters}.
204
+ * @public
205
+ */
206
+ export interface FunctionDeclarationSchema {
207
+ /** The type of the parameter. */
208
+ type: SchemaType;
209
+ /** The format of the parameter. */
210
+ properties: {
211
+ [k: string]: FunctionDeclarationSchemaProperty;
212
+ };
213
+ /** Optional. Description of the parameter. */
214
+ description?: string;
215
+ /** Optional. Array of required parameters. */
216
+ required?: string[];
217
+ }
218
+ /**
219
+ * Schema for top-level function declaration
220
+ * @public
221
+ */
222
+ export type FunctionDeclarationSchemaProperty = Schema;
223
+ /**
224
+ * Schema passed to `GenerationConfig.responseSchema`
225
+ * @public
226
+ */
227
+ export type ResponseSchema = Schema;
228
+ /**
229
+ * Tool config. This config is shared for all tools provided in the request.
230
+ * @public
231
+ */
232
+ export interface ToolConfig {
233
+ functionCallingConfig: FunctionCallingConfig;
234
+ }
235
+ /**
236
+ * @public
237
+ */
238
+ export interface FunctionCallingConfig {
239
+ mode?: FunctionCallingMode;
240
+ allowedFunctionNames?: string[];
241
+ }