@retrivora-ai/rag-engine 2.2.4 → 2.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.mjs CHANGED
@@ -106,644 +106,6 @@ var init_templateUtils = __esm({
106
106
  }
107
107
  });
108
108
 
109
- // ../../services/llm-gateway/providers/groq.ts
110
- async function handleGroqRequest(req, apiKeyOverride) {
111
- const apiKey = apiKeyOverride || process.env.GROQ_API_KEY;
112
- if (!apiKey) {
113
- throw new Error("LLM service credentials not configured.");
114
- }
115
- const modelName = req.model.replace(/^groq\//i, "");
116
- const payload = __spreadProps(__spreadValues({}, req), {
117
- model: modelName
118
- });
119
- const response = await fetch("https://api.groq.com/openai/v1/chat/completions", {
120
- method: "POST",
121
- headers: {
122
- "Content-Type": "application/json",
123
- "Authorization": `Bearer ${apiKey}`
124
- },
125
- body: JSON.stringify(payload)
126
- });
127
- if (!response.ok) {
128
- const errorText = await response.text();
129
- throw new Error(`Groq API Error (${response.status}): ${errorText}`);
130
- }
131
- if (req.stream && response.body) {
132
- return { stream: response.body };
133
- }
134
- const json = await response.json();
135
- return { response: json };
136
- }
137
- var init_groq = __esm({
138
- "../../services/llm-gateway/providers/groq.ts"() {
139
- "use strict";
140
- }
141
- });
142
-
143
- // ../../services/llm-gateway/providers/openai.ts
144
- async function handleOpenAIRequest(req, apiKeyOverride) {
145
- const apiKey = apiKeyOverride || process.env.OPENAI_API_KEY;
146
- if (!apiKey) {
147
- throw new Error("OpenAI API Key missing. Please set OPENAI_API_KEY in environment variables.");
148
- }
149
- const modelName = req.model.replace(/^(openai|gpt)\//i, "");
150
- const payload = __spreadProps(__spreadValues({}, req), {
151
- model: modelName
152
- });
153
- const response = await fetch("https://api.openai.com/v1/chat/completions", {
154
- method: "POST",
155
- headers: {
156
- "Content-Type": "application/json",
157
- "Authorization": `Bearer ${apiKey}`
158
- },
159
- body: JSON.stringify(payload)
160
- });
161
- if (!response.ok) {
162
- const errorText = await response.text();
163
- throw new Error(`OpenAI API Error (${response.status}): ${errorText}`);
164
- }
165
- if (req.stream && response.body) {
166
- return { stream: response.body };
167
- }
168
- const json = await response.json();
169
- return { response: json };
170
- }
171
- async function handleOpenAIEmbedding(req, apiKeyOverride) {
172
- const apiKey = apiKeyOverride || process.env.OPENAI_API_KEY;
173
- if (!apiKey) {
174
- throw new Error("OpenAI API Key missing. Please set OPENAI_API_KEY in environment variables.");
175
- }
176
- const modelName = req.model.replace(/^(openai)\//i, "");
177
- const response = await fetch("https://api.openai.com/v1/embeddings", {
178
- method: "POST",
179
- headers: {
180
- "Content-Type": "application/json",
181
- "Authorization": `Bearer ${apiKey}`
182
- },
183
- body: JSON.stringify({
184
- model: modelName,
185
- input: req.input
186
- })
187
- });
188
- if (!response.ok) {
189
- const errorText = await response.text();
190
- throw new Error(`OpenAI Embedding API Error (${response.status}): ${errorText}`);
191
- }
192
- return await response.json();
193
- }
194
- var init_openai = __esm({
195
- "../../services/llm-gateway/providers/openai.ts"() {
196
- "use strict";
197
- }
198
- });
199
-
200
- // ../../services/llm-gateway/providers/gemini.ts
201
- async function handleGeminiRequest(req, apiKeyOverride) {
202
- const apiKey = apiKeyOverride || process.env.GEMINI_API_KEY;
203
- if (!apiKey) {
204
- throw new Error("Gemini API Key missing. Please set GEMINI_API_KEY in environment variables.");
205
- }
206
- let modelName = req.model.replace(/^(google|gemini)\//i, "");
207
- if (!modelName.startsWith("gemini-")) {
208
- modelName = `gemini-${modelName}`;
209
- }
210
- const payload = __spreadProps(__spreadValues({}, req), {
211
- model: modelName
212
- });
213
- const response = await fetch("https://generativelanguage.googleapis.com/v1beta/openai/chat/completions", {
214
- method: "POST",
215
- headers: {
216
- "Content-Type": "application/json",
217
- "Authorization": `Bearer ${apiKey}`
218
- },
219
- body: JSON.stringify(payload)
220
- });
221
- if (!response.ok) {
222
- const errorText = await response.text();
223
- throw new Error(`Google Gemini API Error (${response.status}): ${errorText}`);
224
- }
225
- if (req.stream && response.body) {
226
- return { stream: response.body };
227
- }
228
- const json = await response.json();
229
- return { response: json };
230
- }
231
- async function handleGeminiEmbedding(req, apiKeyOverride) {
232
- const apiKey = apiKeyOverride || process.env.GEMINI_API_KEY;
233
- if (!apiKey) {
234
- throw new Error("Gemini API Key missing. Please set GEMINI_API_KEY in environment variables.");
235
- }
236
- let modelName = req.model.replace(/^(google|gemini)\//i, "");
237
- if (!modelName || modelName === "default" || modelName.includes("text-embedding-3") || modelName.includes("ada") || !modelName.startsWith("text-embedding-00") && !modelName.startsWith("embedding-00")) {
238
- modelName = "text-embedding-004";
239
- }
240
- const response = await fetch("https://generativelanguage.googleapis.com/v1beta/openai/embeddings", {
241
- method: "POST",
242
- headers: {
243
- "Content-Type": "application/json",
244
- "Authorization": `Bearer ${apiKey}`
245
- },
246
- body: JSON.stringify({
247
- model: modelName,
248
- input: req.input
249
- })
250
- });
251
- if (!response.ok) {
252
- const errorText = await response.text();
253
- throw new Error(`Google Gemini Embedding API Error (${response.status}): ${errorText}`);
254
- }
255
- return await response.json();
256
- }
257
- var init_gemini = __esm({
258
- "../../services/llm-gateway/providers/gemini.ts"() {
259
- "use strict";
260
- }
261
- });
262
-
263
- // ../../services/llm-gateway/providers/huggingface.ts
264
- async function handleHuggingFaceChatRequest(req, apiKeyOverride) {
265
- var _a2, _b;
266
- const apiKey = apiKeyOverride || process.env.HUGGINGFACE_API_KEY || process.env.HF_TOKEN;
267
- if (!apiKey) {
268
- throw new Error("HuggingFace API Key missing. Set HUGGINGFACE_API_KEY or HF_TOKEN in environment variables.");
269
- }
270
- let modelName = req.model.replace(/^(huggingface|hf)\//i, "");
271
- if (!modelName || modelName === "default" || modelName.toLowerCase() === "qwen" || modelName.toLowerCase() === "qwen-coder") {
272
- modelName = "Qwen/Qwen2.5-Coder-32B-Instruct";
273
- }
274
- const payload = __spreadProps(__spreadValues({}, req), {
275
- model: modelName
276
- });
277
- try {
278
- const response = await fetch("https://router.huggingface.co/v1/chat/completions", {
279
- method: "POST",
280
- headers: {
281
- "Content-Type": "application/json",
282
- "Authorization": `Bearer ${apiKey}`
283
- },
284
- body: JSON.stringify(payload)
285
- });
286
- if (response.ok) {
287
- if (req.stream && response.body) {
288
- return { stream: response.body };
289
- }
290
- const json = await response.json();
291
- return { response: json };
292
- }
293
- } catch (e) {
294
- }
295
- try {
296
- const response = await fetch("https://router.huggingface.co/hf-inference/v1/chat/completions", {
297
- method: "POST",
298
- headers: {
299
- "Content-Type": "application/json",
300
- "Authorization": `Bearer ${apiKey}`
301
- },
302
- body: JSON.stringify(payload)
303
- });
304
- if (response.ok) {
305
- if (req.stream && response.body) {
306
- return { stream: response.body };
307
- }
308
- const json = await response.json();
309
- return { response: json };
310
- }
311
- } catch (e) {
312
- }
313
- const lastUserMsg = ((_a2 = req.messages.filter((m) => m.role === "user").pop()) == null ? void 0 : _a2.content) || "Hello";
314
- const pipelineRes = await fetch(`https://router.huggingface.co/hf-inference/models/${modelName}`, {
315
- method: "POST",
316
- headers: {
317
- "Content-Type": "application/json",
318
- "Authorization": `Bearer ${apiKey}`
319
- },
320
- body: JSON.stringify({
321
- inputs: lastUserMsg,
322
- parameters: { max_new_tokens: req.max_tokens || 256, temperature: req.temperature || 0.7 },
323
- options: { wait_for_model: true }
324
- })
325
- });
326
- if (!pipelineRes.ok) {
327
- const errorText = await pipelineRes.text();
328
- throw new Error(`HuggingFace API Error (${pipelineRes.status}): ${errorText}`);
329
- }
330
- const raw = await pipelineRes.json();
331
- const textOutput = Array.isArray(raw) ? ((_b = raw[0]) == null ? void 0 : _b.generated_text) || JSON.stringify(raw) : JSON.stringify(raw);
332
- const formattedResponse = {
333
- id: `hf-${Date.now()}`,
334
- object: "chat.completion",
335
- created: Math.floor(Date.now() / 1e3),
336
- model: modelName,
337
- choices: [
338
- {
339
- index: 0,
340
- message: {
341
- role: "assistant",
342
- content: textOutput
343
- },
344
- finish_reason: "stop"
345
- }
346
- ],
347
- usage: {
348
- prompt_tokens: lastUserMsg.length,
349
- completion_tokens: textOutput.length,
350
- total_tokens: lastUserMsg.length + textOutput.length
351
- }
352
- };
353
- return { response: formattedResponse };
354
- }
355
- async function handleHuggingFaceEmbedding(req, apiKeyOverride) {
356
- const apiKey = apiKeyOverride || process.env.HUGGINGFACE_API_KEY || process.env.HF_TOKEN;
357
- if (!apiKey) {
358
- throw new Error("HuggingFace API Key missing. Set HUGGINGFACE_API_KEY or HF_TOKEN in environment variables.");
359
- }
360
- let modelName = req.model.replace(/^(huggingface|hf)\//i, "");
361
- if (!modelName || modelName === "default" || modelName.includes("text-embedding-3") || modelName.includes("ada") || !modelName.includes("/") && !modelName.includes("bge") && !modelName.includes("sentence-transformers")) {
362
- modelName = "BAAI/bge-base-en-v1.5";
363
- }
364
- const inputs = Array.isArray(req.input) ? req.input : [req.input];
365
- const fetchEmbeddingFromModel = async (targetModel) => {
366
- try {
367
- const routerRes = await fetch("https://router.huggingface.co/hf-inference/v1/embeddings", {
368
- method: "POST",
369
- headers: {
370
- "Content-Type": "application/json",
371
- "Authorization": `Bearer ${apiKey}`
372
- },
373
- body: JSON.stringify({
374
- model: targetModel,
375
- input: inputs
376
- })
377
- });
378
- if (routerRes.ok) {
379
- const json = await routerRes.json();
380
- if (json && json.data) return json;
381
- }
382
- } catch (e) {
383
- }
384
- const response = await fetch(`https://router.huggingface.co/hf-inference/models/${targetModel}`, {
385
- method: "POST",
386
- headers: {
387
- "Content-Type": "application/json",
388
- "Authorization": `Bearer ${apiKey}`
389
- },
390
- body: JSON.stringify({
391
- inputs,
392
- options: { wait_for_model: true }
393
- })
394
- });
395
- if (!response.ok) {
396
- const errorText = await response.text();
397
- throw new Error(`HuggingFace API Error (${response.status}): ${errorText}`);
398
- }
399
- const rawData = await response.json();
400
- const embeddings = Array.isArray(rawData[0]) ? typeof rawData[0][0] === "number" ? rawData : rawData.map((arr) => arr[0]) : [rawData];
401
- return {
402
- object: "list",
403
- data: embeddings.map((vec, idx) => ({
404
- object: "embedding",
405
- embedding: vec,
406
- index: idx
407
- })),
408
- model: targetModel,
409
- usage: {
410
- prompt_tokens: inputs.reduce((acc, str) => acc + str.length, 0),
411
- completion_tokens: 0,
412
- total_tokens: inputs.reduce((acc, str) => acc + str.length, 0)
413
- }
414
- };
415
- };
416
- try {
417
- return await fetchEmbeddingFromModel(modelName);
418
- } catch (err) {
419
- if (modelName !== "BAAI/bge-base-en-v1.5") {
420
- console.warn(`[LLM Gateway] HuggingFace model ${modelName} failed. Falling back to BAAI/bge-base-en-v1.5...`, err);
421
- return await fetchEmbeddingFromModel("BAAI/bge-base-en-v1.5");
422
- }
423
- throw err;
424
- }
425
- }
426
- var init_huggingface = __esm({
427
- "../../services/llm-gateway/providers/huggingface.ts"() {
428
- "use strict";
429
- }
430
- });
431
-
432
- // ../../services/llm-gateway/providers/anthropic.ts
433
- async function handleAnthropicRequest(req, apiKeyOverride) {
434
- var _a2, _b;
435
- const apiKey = apiKeyOverride || process.env.ANTHROPIC_API_KEY;
436
- if (!apiKey) {
437
- throw new Error("Anthropic API Key missing. Please set ANTHROPIC_API_KEY in environment variables.");
438
- }
439
- const modelName = req.model.replace(/^(anthropic|claude)\//i, "");
440
- let systemPrompt = void 0;
441
- const anthropicMessages = [];
442
- for (const msg of req.messages) {
443
- if (msg.role === "system") {
444
- systemPrompt = systemPrompt ? `${systemPrompt}
445
- ${msg.content}` : msg.content;
446
- } else {
447
- anthropicMessages.push({
448
- role: msg.role === "assistant" ? "assistant" : "user",
449
- content: msg.content
450
- });
451
- }
452
- }
453
- if (anthropicMessages.length === 0) {
454
- anthropicMessages.push({ role: "user", content: "Hello" });
455
- }
456
- const payload = {
457
- model: modelName,
458
- messages: anthropicMessages,
459
- max_tokens: req.max_tokens || req.max_completion_tokens || 1024,
460
- stream: req.stream || false
461
- };
462
- if (systemPrompt) {
463
- payload.system = systemPrompt;
464
- }
465
- if (req.temperature !== void 0) {
466
- payload.temperature = req.temperature;
467
- }
468
- const response = await fetch("https://api.anthropic.com/v1/messages", {
469
- method: "POST",
470
- headers: {
471
- "Content-Type": "application/json",
472
- "x-api-key": apiKey,
473
- "anthropic-version": "2023-06-01"
474
- },
475
- body: JSON.stringify(payload)
476
- });
477
- if (!response.ok) {
478
- const errorText = await response.text();
479
- throw new Error(`Anthropic API Error (${response.status}): ${errorText}`);
480
- }
481
- if (req.stream && response.body) {
482
- return { stream: response.body };
483
- }
484
- const json = await response.json();
485
- const textContent = ((_b = (_a2 = json.content) == null ? void 0 : _a2[0]) == null ? void 0 : _b.text) || "";
486
- const openAIResponse = {
487
- id: json.id || `chatcmpl-${Date.now()}`,
488
- object: "chat.completion",
489
- created: Math.floor(Date.now() / 1e3),
490
- model: json.model || modelName,
491
- choices: [
492
- {
493
- index: 0,
494
- message: {
495
- role: "assistant",
496
- content: textContent
497
- },
498
- finish_reason: json.stop_reason === "end_turn" ? "stop" : json.stop_reason || "stop"
499
- }
500
- ],
501
- usage: json.usage ? {
502
- prompt_tokens: json.usage.input_tokens,
503
- completion_tokens: json.usage.output_tokens,
504
- total_tokens: json.usage.input_tokens + json.usage.output_tokens
505
- } : void 0
506
- };
507
- return { response: openAIResponse };
508
- }
509
- var init_anthropic = __esm({
510
- "../../services/llm-gateway/providers/anthropic.ts"() {
511
- "use strict";
512
- }
513
- });
514
-
515
- // ../../services/llm-gateway/providers/ollama.ts
516
- async function handleOllamaRequest(req, baseUrlOverride) {
517
- const baseUrl = (baseUrlOverride || process.env.OLLAMA_BASE_URL || "http://localhost:11434/v1").replace(/\/+$/, "");
518
- const modelName = req.model.replace(/^ollama\//i, "");
519
- const payload = __spreadProps(__spreadValues({}, req), {
520
- model: modelName
521
- });
522
- const response = await fetch(`${baseUrl}/chat/completions`, {
523
- method: "POST",
524
- headers: {
525
- "Content-Type": "application/json"
526
- },
527
- body: JSON.stringify(payload)
528
- });
529
- if (!response.ok) {
530
- const errorText = await response.text();
531
- throw new Error(`Ollama API Error (${response.status}): ${errorText}`);
532
- }
533
- if (req.stream && response.body) {
534
- return { stream: response.body };
535
- }
536
- const json = await response.json();
537
- return { response: json };
538
- }
539
- var init_ollama = __esm({
540
- "../../services/llm-gateway/providers/ollama.ts"() {
541
- "use strict";
542
- }
543
- });
544
-
545
- // ../../services/llm-gateway/router.ts
546
- var router_exports = {};
547
- __export(router_exports, {
548
- SUPPORTED_MODELS: () => SUPPORTED_MODELS,
549
- dispatchChatCompletion: () => dispatchChatCompletion,
550
- dispatchEmbedding: () => dispatchEmbedding,
551
- resolveProvider: () => resolveProvider
552
- });
553
- function resolveProvider(model) {
554
- const lower = model.toLowerCase();
555
- if (lower.startsWith("huggingface/") || lower.startsWith("hf/")) {
556
- return "huggingface";
557
- }
558
- if (lower.startsWith("ollama/")) {
559
- return "ollama";
560
- }
561
- if (lower.startsWith("groq/") || lower.includes("llama") || lower.includes("qwen") || lower.includes("mixtral")) {
562
- return "groq";
563
- }
564
- if (process.env.GROQ_API_KEY) return "groq";
565
- if (process.env.OPENAI_API_KEY) return "openai";
566
- if (process.env.GEMINI_API_KEY) return "gemini";
567
- if (process.env.ANTHROPIC_API_KEY) return "anthropic";
568
- if (process.env.HF_TOKEN || process.env.HUGGINGFACE_API_KEY) return "huggingface";
569
- return "groq";
570
- }
571
- function cleanApiKeyOverride(apiKeyOverride) {
572
- if (!apiKeyOverride) return void 0;
573
- const key = apiKeyOverride.trim();
574
- if (key === process.env.LITELLM_API_KEY || key === process.env.LITELLM_MASTER_KEY || key.startsWith("sk-retrivora") || !key.startsWith("gsk_") && !key.startsWith("AIza") && !key.startsWith("sk-ant-") && !key.startsWith("sk-proj-")) {
575
- return void 0;
576
- }
577
- return key;
578
- }
579
- async function resolveUserGatewayConfig(apiKeyOverride) {
580
- var _a2;
581
- if (!apiKeyOverride || !process.env.NEXT_PUBLIC_SUPABASE_URL || !process.env.SUPABASE_SERVICE_ROLE_KEY) {
582
- return {};
583
- }
584
- try {
585
- const { createAdminClient } = await import("@/lib/supabase-server");
586
- const supabase = createAdminClient();
587
- const { data: licenseRecord } = await supabase.from("licenses").select("project_id, customer_name, tier").eq("license_key", apiKeyOverride.trim()).single();
588
- if (!licenseRecord) {
589
- return {};
590
- }
591
- const projectId = licenseRecord.project_id;
592
- const { data: configs } = await supabase.from("gateway_config").select("project_id, default_model, provider_keys, is_active").in("project_id", [projectId, "global"]).eq("is_active", true);
593
- if (!configs || configs.length === 0) {
594
- return {};
595
- }
596
- const matchedConfig = configs.find((c) => c.project_id === projectId) || configs.find((c) => c.project_id === "global");
597
- const customGroqKey = (_a2 = matchedConfig == null ? void 0 : matchedConfig.provider_keys) == null ? void 0 : _a2.groq;
598
- const targetModel = matchedConfig == null ? void 0 : matchedConfig.default_model;
599
- return { customGroqKey, targetModel };
600
- } catch (err) {
601
- console.warn("[LLM Gateway Router] Error resolving user gateway_config:", err.message);
602
- return {};
603
- }
604
- }
605
- async function dispatchChatCompletion(req, apiKeyOverride) {
606
- const { customGroqKey, targetModel } = await resolveUserGatewayConfig(apiKeyOverride);
607
- const effectiveKey = customGroqKey || cleanApiKeyOverride(apiKeyOverride);
608
- const activeModel = req.model || targetModel || "llama-3.1-8b-instant";
609
- const provider = resolveProvider(activeModel);
610
- try {
611
- switch (provider) {
612
- case "groq":
613
- return await handleGroqRequest(__spreadProps(__spreadValues({}, req), { model: activeModel }), effectiveKey);
614
- case "openai":
615
- return await handleOpenAIRequest(__spreadProps(__spreadValues({}, req), { model: activeModel }), effectiveKey);
616
- case "gemini":
617
- return await handleGeminiRequest(__spreadProps(__spreadValues({}, req), { model: activeModel }), effectiveKey);
618
- case "anthropic":
619
- return await handleAnthropicRequest(__spreadProps(__spreadValues({}, req), { model: activeModel }), effectiveKey);
620
- case "ollama":
621
- return await handleOllamaRequest(__spreadProps(__spreadValues({}, req), { model: activeModel }));
622
- case "huggingface":
623
- return await handleHuggingFaceChatRequest(__spreadProps(__spreadValues({}, req), { model: activeModel }), effectiveKey);
624
- default:
625
- throw new Error(`Unsupported LLM provider for model: ${activeModel}`);
626
- }
627
- } catch (error) {
628
- console.error(`[LLM Gateway Router] Provider '${provider}' failed for model '${req.model}':`, {
629
- message: error.message,
630
- stack: error.stack
631
- });
632
- if (/rate[- ]?limit|429|exhausted/i.test(error.message)) {
633
- const isGroqKey = process.env.GROQ_API_KEY || effectiveKey && effectiveKey.startsWith("gsk_");
634
- const reqModelLower = req.model.toLowerCase();
635
- if (isGroqKey && !reqModelLower.includes("llama-3.3-70b")) {
636
- console.warn(`[LLM Gateway] Provider ${provider} rate limited (${error.message}). Falling back to secondary Groq model (llama-3.3-70b-versatile)...`);
637
- try {
638
- return await handleGroqRequest(__spreadProps(__spreadValues({}, req), { model: "llama-3.3-70b-versatile" }), effectiveKey);
639
- } catch (fErr) {
640
- console.error("[LLM Gateway] Fallback groq/llama-3.3-70b-versatile failed:", fErr.message);
641
- }
642
- }
643
- const geminiKey = process.env.GEMINI_API_KEY || effectiveKey;
644
- if (provider !== "gemini" && geminiKey && (geminiKey.startsWith("AIza") || !geminiKey.startsWith("AQ."))) {
645
- console.warn(`[LLM Gateway] Provider ${provider} rate limited (${error.message}). Falling back to Google Gemini (gemini-2.5-flash)...`);
646
- try {
647
- return await handleGeminiRequest(__spreadProps(__spreadValues({}, req), { model: "gemini-2.5-flash" }), effectiveKey);
648
- } catch (fErr) {
649
- console.error("[LLM Gateway] Fallback gemini-2.5-flash failed:", fErr.message);
650
- }
651
- }
652
- if (provider !== "huggingface" && (process.env.HF_TOKEN || process.env.HUGGINGFACE_API_KEY)) {
653
- console.warn(`[LLM Gateway] Provider ${provider} rate limited (${error.message}). Falling back to Hugging Face (Qwen/Qwen2.5-Coder-32B-Instruct)...`);
654
- try {
655
- return await handleHuggingFaceChatRequest(__spreadProps(__spreadValues({}, req), { model: "Qwen/Qwen2.5-Coder-32B-Instruct" }), effectiveKey);
656
- } catch (fErr) {
657
- console.error("[LLM Gateway] Fallback HuggingFace Qwen failed:", fErr.message);
658
- }
659
- }
660
- if (provider !== "openai" && process.env.OPENAI_API_KEY) {
661
- console.warn(`[LLM Gateway] Provider ${provider} rate limited (${error.message}). Falling back to OpenAI (gpt-4o-mini)...`);
662
- try {
663
- return await handleOpenAIRequest(__spreadProps(__spreadValues({}, req), { model: "gpt-4o-mini" }), effectiveKey);
664
- } catch (e) {
665
- }
666
- }
667
- console.warn(`[LLM Gateway] Provider ${provider} rate limited (${error.message}). Falling back to local Ollama (llama3.2)...`);
668
- return handleOllamaRequest(__spreadProps(__spreadValues({}, req), { model: "llama3.2" }));
669
- }
670
- throw error;
671
- }
672
- }
673
- async function dispatchEmbedding(req, apiKeyOverride) {
674
- const effectiveKey = cleanApiKeyOverride(apiKeyOverride);
675
- if (req.model.startsWith("hf/") || req.model.startsWith("huggingface/") || req.model.includes("bge-")) {
676
- try {
677
- return await handleHuggingFaceEmbedding(req, effectiveKey);
678
- } catch (err) {
679
- console.warn("[LLM Gateway] HuggingFace explicit model embedding failed, falling back to default gateway chain:", err);
680
- }
681
- }
682
- const geminiKey = process.env.GEMINI_API_KEY || effectiveKey;
683
- const isGeminiKeyValid = Boolean(geminiKey && !geminiKey.startsWith("eyJ"));
684
- if (isGeminiKeyValid) {
685
- try {
686
- return await handleGeminiEmbedding(req, effectiveKey);
687
- } catch (err) {
688
- console.warn("[LLM Gateway] Gemini embedding failed:", err);
689
- }
690
- }
691
- if (process.env.OPENAI_API_KEY) {
692
- try {
693
- return await handleOpenAIEmbedding(req, effectiveKey);
694
- } catch (err) {
695
- console.warn("[LLM Gateway] OpenAI embedding failed:", err);
696
- }
697
- }
698
- if (process.env.HUGGINGFACE_API_KEY || process.env.HF_TOKEN) {
699
- try {
700
- return await handleHuggingFaceEmbedding(req, effectiveKey);
701
- } catch (err) {
702
- console.warn("[LLM Gateway] HuggingFace fallback embedding failed:", err);
703
- }
704
- }
705
- return handleGeminiEmbedding(req, effectiveKey);
706
- }
707
- var SUPPORTED_MODELS;
708
- var init_router = __esm({
709
- "../../services/llm-gateway/router.ts"() {
710
- "use strict";
711
- init_groq();
712
- init_openai();
713
- init_gemini();
714
- init_huggingface();
715
- init_anthropic();
716
- init_ollama();
717
- SUPPORTED_MODELS = [
718
- { id: "groq/llama-3.1-8b-instant", object: "model", created: 17e8, owned_by: "groq" },
719
- { id: "llama-3.1-8b-instant", object: "model", created: 17e8, owned_by: "groq" },
720
- { id: "groq/llama-3.3-70b-versatile", object: "model", created: 17e8, owned_by: "groq" },
721
- { id: "llama-3.3-70b-versatile", object: "model", created: 17e8, owned_by: "groq" },
722
- { id: "gpt-4o-mini", object: "model", created: 17e8, owned_by: "openai" },
723
- { id: "openai/gpt-4o-mini", object: "model", created: 17e8, owned_by: "openai" },
724
- { id: "gpt-4o", object: "model", created: 17e8, owned_by: "openai" },
725
- { id: "gemini-2.5-flash", object: "model", created: 17e8, owned_by: "google" },
726
- { id: "google/gemini-2.5-flash", object: "model", created: 17e8, owned_by: "google" },
727
- { id: "claude-3-5-haiku-20241022", object: "model", created: 17e8, owned_by: "anthropic" },
728
- { id: "anthropic/claude-3-5-haiku-20241022", object: "model", created: 17e8, owned_by: "anthropic" },
729
- { id: "text-embedding-004", object: "model", created: 17e8, owned_by: "google" },
730
- { id: "google/text-embedding-004", object: "model", created: 17e8, owned_by: "google" },
731
- { id: "BAAI/bge-base-en-v1.5", object: "model", created: 17e8, owned_by: "huggingface" },
732
- { id: "huggingface/BAAI/bge-base-en-v1.5", object: "model", created: 17e8, owned_by: "huggingface" },
733
- { id: "groq/qwen3-32b", object: "model", created: 17e8, owned_by: "groq" },
734
- { id: "qwen/qwen3-32b", object: "model", created: 17e8, owned_by: "groq" },
735
- { id: "qwen/qwen3-embedding-8b", object: "model", created: 17e8, owned_by: "qwen" },
736
- { id: "qwen3-embedding-8b", object: "model", created: 17e8, owned_by: "qwen" },
737
- { id: "ollama/llama3.2", object: "model", created: 17e8, owned_by: "ollama" }
738
- ];
739
- if (typeof globalThis !== "undefined") {
740
- const _g2 = globalThis;
741
- _g2.__retrivoraDispatchChat = dispatchChatCompletion;
742
- _g2.__retrivoraDispatchEmbedding = dispatchEmbedding;
743
- }
744
- }
745
- });
746
-
747
109
  // src/providers/vectordb/BaseVectorProvider.ts
748
110
  var BaseVectorProvider;
749
111
  var init_BaseVectorProvider = __esm({
@@ -800,8 +162,8 @@ var init_ConfigFetcher = __esm({
800
162
  process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL,
801
163
  "https://www.retrivora.com",
802
164
  "https://retrivora.com",
803
- "http://localhost:3001",
804
- "http://localhost:3000"
165
+ "http://localhost:3000",
166
+ "http://localhost:3001"
805
167
  ].filter(Boolean);
806
168
  for (const baseUrl of controlPlaneUrls) {
807
169
  try {
@@ -3356,7 +2718,7 @@ function getEnvConfig(env = process.env, base) {
3356
2718
  },
3357
2719
  telemetry: {
3358
2720
  enabled: telemetryEnabled,
3359
- url: (_Kb = (_Jb = (_Hb = readString(env, "TELEMETRY_URL")) != null ? _Hb : readString(env, "NEXT_PUBLIC_TELEMETRY_URL")) != null ? _Jb : (_Ib = base == null ? void 0 : base.telemetry) == null ? void 0 : _Ib.url) != null ? _Kb : process.env.NODE_ENV === "development" ? "http://localhost:3001/api/telemetry" : "https://retrivora.com/api/telemetry"
2721
+ url: (_Kb = (_Jb = (_Hb = readString(env, "TELEMETRY_URL")) != null ? _Hb : readString(env, "NEXT_PUBLIC_TELEMETRY_URL")) != null ? _Jb : (_Ib = base == null ? void 0 : base.telemetry) == null ? void 0 : _Ib.url) != null ? _Kb : "https://www.retrivora.com/api/telemetry"
3360
2722
  }
3361
2723
  }, readString(env, "GRAPH_DB_PROVIDER") ? {
3362
2724
  graphDb: {
@@ -4605,9 +3967,7 @@ var OPENAI_BASE = {
4605
3967
  };
4606
3968
  var LLM_PROFILES = {
4607
3969
  "openai-compatible": OPENAI_BASE,
4608
- "litellm": __spreadProps(__spreadValues({}, OPENAI_BASE), {
4609
- chatPayloadTemplate: '{"model":"{{model}}","messages":{{messages}},"max_tokens":{{maxTokens}},"temperature":{{temperature}},"stream":false}'
4610
- }),
3970
+ "litellm": __spreadValues({}, OPENAI_BASE),
4611
3971
  "anthropic-claude": {
4612
3972
  chatPath: "/v1/messages",
4613
3973
  responseExtractPath: "content[0].text",
@@ -4752,18 +4112,7 @@ ${context != null ? context : "None"}` },
4752
4112
  }
4753
4113
  } catch (httpErr) {
4754
4114
  const _g2 = globalThis;
4755
- let dispatch = _g2.__retrivoraDispatchChat;
4756
- if (typeof dispatch !== "function") {
4757
- try {
4758
- const gateway = await Promise.resolve().then(() => (init_router(), router_exports));
4759
- if (gateway == null ? void 0 : gateway.dispatchChatCompletion) {
4760
- _g2.__retrivoraDispatchChat = gateway.dispatchChatCompletion;
4761
- _g2.__retrivoraDispatchEmbedding = gateway.dispatchEmbedding;
4762
- dispatch = gateway.dispatchChatCompletion;
4763
- }
4764
- } catch (e) {
4765
- }
4766
- }
4115
+ const dispatch = _g2.__retrivoraDispatchChat;
4767
4116
  if (typeof dispatch === "function") {
4768
4117
  const res = await dispatch({
4769
4118
  model: this.model,
@@ -4789,11 +4138,10 @@ ${context != null ? context : "None"}` },
4789
4138
  /**
4790
4139
  * Streaming chat using native fetch + ReadableStream.
4791
4140
  * Parses OpenAI-compatible SSE frames: `data: {...}\n\n`
4792
- * Works with vLLM, LMStudio, Together AI, Fireworks, and any OpenAI-compatible API.
4793
4141
  */
4794
4142
  chatStream(messages, context) {
4795
4143
  return __asyncGenerator(this, null, function* () {
4796
- var _a2, _b, _c, _d, _e;
4144
+ var _a2, _b, _c, _d, _e, _f;
4797
4145
  const path2 = (_a2 = this.opts.chatPath) != null ? _a2 : "/chat/completions";
4798
4146
  const url = `${this.baseUrl.replace(/\/$/, "")}${path2}`;
4799
4147
  const extractPath = ((_b = this.opts.responseExtractPath) != null ? _b : "choices[0].message.content").replace("message.content", "delta.content");
@@ -4828,22 +4176,35 @@ ${context != null ? context : "None"}` },
4828
4176
  stream: true
4829
4177
  };
4830
4178
  }
4831
- const isSelfHost = this.baseUrl.includes("retrivora.com") || this.baseUrl.includes("localhost");
4832
4179
  let streamBody = null;
4833
- if (isSelfHost || Boolean(process.env.VERCEL)) {
4834
- const _g2 = globalThis;
4835
- let dispatch = _g2.__retrivoraDispatchChat;
4836
- if (typeof dispatch !== "function") {
4837
- try {
4838
- const gateway = yield new __await(Promise.resolve().then(() => (init_router(), router_exports)));
4839
- if (gateway == null ? void 0 : gateway.dispatchChatCompletion) {
4840
- _g2.__retrivoraDispatchChat = gateway.dispatchChatCompletion;
4841
- _g2.__retrivoraDispatchEmbedding = gateway.dispatchEmbedding;
4842
- dispatch = gateway.dispatchChatCompletion;
4180
+ try {
4181
+ const response = yield new __await(fetch(url, {
4182
+ method: "POST",
4183
+ headers: this.resolvedHeaders,
4184
+ body: typeof payload === "string" ? payload : JSON.stringify(payload)
4185
+ }));
4186
+ if (response.ok) {
4187
+ const contentType = response.headers.get("content-type") || "";
4188
+ if (contentType.includes("application/json")) {
4189
+ const json = yield new __await(response.json());
4190
+ const text = (_c = resolvePath(json, extractPath)) != null ? _c : extractContent(json);
4191
+ if (text && typeof text === "string") {
4192
+ yield text;
4193
+ return;
4843
4194
  }
4844
- } catch (e) {
4195
+ } else if (response.body) {
4196
+ streamBody = response.body;
4845
4197
  }
4198
+ } else {
4199
+ const errorText = yield new __await(response.text().catch(() => response.statusText));
4200
+ console.warn(`[UniversalLLMAdapter] Remote HTTP stream returned ${response.status}: ${errorText}. Attempting in-process fallback...`);
4846
4201
  }
4202
+ } catch (fetchErr) {
4203
+ console.warn(`[UniversalLLMAdapter] Remote HTTP stream fetch warning: ${fetchErr == null ? void 0 : fetchErr.message}. Attempting in-process fallback...`);
4204
+ }
4205
+ if (!streamBody) {
4206
+ const _g2 = globalThis;
4207
+ const dispatch = _g2.__retrivoraDispatchChat;
4847
4208
  if (typeof dispatch === "function") {
4848
4209
  try {
4849
4210
  const res = yield new __await(dispatch({
@@ -4861,29 +4222,14 @@ ${context != null ? context : "None"}` },
4861
4222
  yield content;
4862
4223
  return;
4863
4224
  }
4864
- throw new Error(`[UniversalLLMAdapter] In-process dispatch stream returned empty response for model: ${this.model}`);
4865
4225
  }
4866
4226
  } catch (dispatchErr) {
4867
- throw dispatchErr;
4227
+ console.warn("[UniversalLLMAdapter] In-process dispatch error:", dispatchErr);
4868
4228
  }
4869
- } else {
4870
- throw new Error(`[UniversalLLMAdapter] In-process gateway dispatch not registered. Direct self-referential HTTP calls to ${this.baseUrl} are disabled on Vercel to prevent HTTP 508 Loop Detected.`);
4871
4229
  }
4872
4230
  }
4873
4231
  if (!streamBody) {
4874
- const response = yield new __await(fetch(url, {
4875
- method: "POST",
4876
- headers: this.resolvedHeaders,
4877
- body: JSON.stringify(payload)
4878
- }));
4879
- if (!response.ok) {
4880
- const errorText = yield new __await(response.text().catch(() => response.statusText));
4881
- throw new Error(`[UniversalLLMAdapter] Streaming request failed (${response.status}): ${errorText}`);
4882
- }
4883
- if (!response.body) {
4884
- throw new Error("[UniversalLLMAdapter] Response body is null \u2014 server did not send a streaming response.");
4885
- }
4886
- streamBody = response.body;
4232
+ throw new Error(`[UniversalLLMAdapter] Streaming request failed. Ensure RETRIVORA_LICENSE_KEY is valid or LLM service is available.`);
4887
4233
  }
4888
4234
  const reader = streamBody.getReader();
4889
4235
  const decoder = new TextDecoder("utf-8");
@@ -4894,14 +4240,14 @@ ${context != null ? context : "None"}` },
4894
4240
  if (done) break;
4895
4241
  buffer += decoder.decode(value, { stream: true });
4896
4242
  const lines = buffer.split("\n");
4897
- buffer = (_c = lines.pop()) != null ? _c : "";
4243
+ buffer = (_d = lines.pop()) != null ? _d : "";
4898
4244
  for (const line of lines) {
4899
4245
  const trimmed = line.trim();
4900
4246
  if (!trimmed || trimmed === "data: [DONE]") continue;
4901
4247
  if (!trimmed.startsWith("data:")) continue;
4902
4248
  try {
4903
4249
  const json = JSON.parse(trimmed.slice(5).trim());
4904
- const text = (_d = resolvePath(json, extractPath)) != null ? _d : extractContent(json);
4250
+ const text = (_e = resolvePath(json, extractPath)) != null ? _e : extractContent(json);
4905
4251
  if (text && typeof text === "string") yield text;
4906
4252
  } catch (e) {
4907
4253
  }
@@ -4911,7 +4257,7 @@ ${context != null ? context : "None"}` },
4911
4257
  const jsonStr = buffer.replace(/^data:\s*/, "").trim();
4912
4258
  try {
4913
4259
  const json = JSON.parse(jsonStr);
4914
- const text = (_e = resolvePath(json, extractPath)) != null ? _e : extractContent(json);
4260
+ const text = (_f = resolvePath(json, extractPath)) != null ? _f : extractContent(json);
4915
4261
  if (text && typeof text === "string") yield text;
4916
4262
  } catch (e) {
4917
4263
  }
@@ -4924,74 +4270,42 @@ ${context != null ? context : "None"}` },
4924
4270
  async embed(text) {
4925
4271
  var _a2, _b, _c, _d, _e;
4926
4272
  const path2 = (_a2 = this.opts.embedPath) != null ? _a2 : "/embeddings";
4927
- let payload;
4928
- if (this.opts.embedPayloadTemplate) {
4929
- payload = buildPayload(this.opts.embedPayloadTemplate, {
4930
- model: this.model,
4931
- input: text
4932
- });
4933
- } else {
4934
- payload = {
4935
- model: this.model,
4936
- input: text
4937
- };
4938
- }
4273
+ const payload = this.opts.embedPayloadTemplate ? buildPayload(this.opts.embedPayloadTemplate, { input: text, model: this.model }) : { input: text, model: this.model };
4939
4274
  try {
4940
4275
  const { data: data2 } = await this.http.post(path2, payload);
4941
4276
  const extractPath2 = (_b = this.opts.embedExtractPath) != null ? _b : "data[0].embedding";
4942
4277
  const vector2 = resolvePath(data2, extractPath2);
4943
- if (Array.isArray(vector2)) {
4944
- return vector2;
4945
- }
4946
- } catch (httpErr) {
4947
- console.warn(`[UniversalLLMAdapter] Direct HTTP embedding POST to ${this.baseUrl}${path2} failed (${httpErr.message}). Attempting in-process gateway dispatch fallback...`);
4278
+ if (Array.isArray(vector2)) return vector2;
4279
+ } catch (e) {
4948
4280
  const _g2 = globalThis;
4949
- let dispatch = _g2.__retrivoraDispatchEmbedding;
4950
- if (typeof dispatch !== "function") {
4951
- try {
4952
- const gateway = await Promise.resolve().then(() => (init_router(), router_exports));
4953
- if (gateway == null ? void 0 : gateway.dispatchEmbedding) {
4954
- _g2.__retrivoraDispatchChat = gateway.dispatchChatCompletion;
4955
- _g2.__retrivoraDispatchEmbedding = gateway.dispatchEmbedding;
4956
- dispatch = gateway.dispatchEmbedding;
4957
- }
4958
- } catch (e) {
4959
- }
4960
- }
4961
- if (typeof dispatch === "function") {
4962
- const res = await dispatch({
4963
- model: this.model,
4964
- input: text
4965
- }, this.apiKey);
4281
+ const dispatchEmbed = _g2.__retrivoraDispatchEmbedding;
4282
+ if (typeof dispatchEmbed === "function") {
4283
+ const res = await dispatchEmbed({ input: text, model: this.model }, this.apiKey);
4966
4284
  if ((_d = (_c = res == null ? void 0 : res.data) == null ? void 0 : _c[0]) == null ? void 0 : _d.embedding) {
4967
4285
  return res.data[0].embedding;
4968
4286
  }
4969
4287
  }
4970
- throw httpErr;
4971
4288
  }
4972
4289
  const { data } = await this.http.post(path2, payload);
4973
4290
  const extractPath = (_e = this.opts.embedExtractPath) != null ? _e : "data[0].embedding";
4974
4291
  const vector = resolvePath(data, extractPath);
4975
4292
  if (!Array.isArray(vector)) {
4976
- throw new Error(`[UniversalLLMAdapter] Expected a number array at '${extractPath}' for embeddings.`);
4293
+ throw new Error(`[UniversalLLMAdapter] Could not extract embedding vector from path '${extractPath}' in response.`);
4977
4294
  }
4978
4295
  return vector;
4979
4296
  }
4980
4297
  async batchEmbed(texts) {
4981
- const vectors = [];
4298
+ const results = [];
4982
4299
  for (const text of texts) {
4983
- vectors.push(await this.embed(text));
4300
+ results.push(await this.embed(text));
4984
4301
  }
4985
- return vectors;
4302
+ return results;
4986
4303
  }
4987
4304
  async ping() {
4988
4305
  try {
4989
- if (this.opts.pingPath) {
4990
- await this.http.get(this.opts.pingPath);
4991
- }
4306
+ await this.embed("ping");
4992
4307
  return true;
4993
- } catch (err) {
4994
- console.error("[UniversalLLMAdapter] Ping failed:", err);
4308
+ } catch (e) {
4995
4309
  return false;
4996
4310
  }
4997
4311
  }
@@ -5397,7 +4711,7 @@ var ConfigValidator = class {
5397
4711
  // package.json
5398
4712
  var package_default = {
5399
4713
  name: "@retrivora-ai/rag-engine",
5400
- version: "2.2.4",
4714
+ version: "2.2.6",
5401
4715
  description: "Retrivora AI is a plug-and-play AI engine for RAG chat experiences \u2014 generic vector DB + LLM provider, embeddable or standalone.",
5402
4716
  author: "Abhinav Alkuchi",
5403
4717
  license: "UNLICENSED",
@@ -5434,6 +4748,8 @@ var package_default = {
5434
4748
  import: "./dist/index.mjs"
5435
4749
  },
5436
4750
  "./style.css": "./dist/index.css",
4751
+ "./index.css": "./dist/index.css",
4752
+ "./styles.css": "./dist/index.css",
5437
4753
  "./handlers": {
5438
4754
  types: "./dist/handlers/index.d.ts",
5439
4755
  require: "./dist/handlers/index.js",
@@ -7616,19 +6932,6 @@ var UITransformer = class _UITransformer {
7616
6932
  if (!retrievedData || retrievedData.length === 0) {
7617
6933
  return this.createTextResponse("No data available", "No relevant data found for your query.");
7618
6934
  }
7619
- console.log("[UITransformer.transform] Processing retrievedData:", {
7620
- userQuery,
7621
- retrievedCount: retrievedData.length,
7622
- sample: retrievedData.slice(0, 2).map((item) => {
7623
- var _a3;
7624
- return {
7625
- id: item == null ? void 0 : item.id,
7626
- contentType: typeof (item == null ? void 0 : item.content),
7627
- contentSnippet: String((_a3 = item == null ? void 0 : item.content) != null ? _a3 : "").substring(0, 150),
7628
- metadataKeys: Object.keys((item == null ? void 0 : item.metadata) || {})
7629
- };
7630
- })
7631
- });
7632
6935
  const resolvedIntent = intent != null ? intent : this.detectIntentHeuristic(userQuery);
7633
6936
  const filteredData = resolvedIntent.filterInStockOnly ? retrievedData.filter((item) => this.determineStockStatus(item)) : retrievedData;
7634
6937
  const profile = this.profileData(filteredData);
@@ -8968,59 +8271,70 @@ RULES:
8968
8271
  var SchemaMapper = class {
8969
8272
  /**
8970
8273
  * Trains the plugin on a set of keys.
8971
- * This is done once per schema and cached.
8274
+ * Results are cached in-process; concurrent calls for the same key set are
8275
+ * deduplicated to a single LLM request.
8972
8276
  */
8973
8277
  static async train(llm, projectId, keys) {
8974
- const cacheKey = `${projectId}:${keys.sort().join(",")}`;
8278
+ const cacheKey = `${projectId}:${keys.slice().sort().join(",")}`;
8975
8279
  if (this.cache.has(cacheKey)) {
8976
8280
  return this.cache.get(cacheKey);
8977
8281
  }
8978
- console.log(`[SchemaMapper] \u{1F9E0} Training AI on new schema keys: ${keys.join(", ")}`);
8282
+ if (this.pending.has(cacheKey)) {
8283
+ return this.pending.get(cacheKey);
8284
+ }
8285
+ const promise = this._doTrain(llm, cacheKey, keys);
8286
+ this.pending.set(cacheKey, promise);
8287
+ promise.finally(() => this.pending.delete(cacheKey));
8288
+ return promise;
8289
+ }
8290
+ static async _doTrain(llm, cacheKey, keys) {
8291
+ var _a2, _b, _c, _d, _e, _f, _g2, _h, _i, _j, _k;
8292
+ console.log(`[SchemaMapper] \u{1F9E0} Training on new schema keys: ${keys.join(", ")}`);
8979
8293
  const propertyList = Object.entries(this.TARGET_PROPERTIES).map(([prop, desc]) => `- ${prop} (${desc})`).join("\n");
8980
- const prompt = `
8981
- Given these metadata keys from a database: [${keys.join(", ")}]
8294
+ const messages = [
8295
+ { role: "system", content: "You are a database schema expert. Respond ONLY with valid JSON." },
8296
+ {
8297
+ role: "user",
8298
+ content: `Keys: [${keys.join(", ")}]
8982
8299
 
8983
- Identify which keys best correspond to these standard UI properties:
8300
+ Map to:
8984
8301
  ${propertyList}
8985
8302
 
8986
- Return ONLY a valid JSON object where the keys are the UI properties and the values are the EXACT matching database keys from the list above.
8987
- If no good match is found for a property, omit it.
8988
-
8989
- Example:
8990
- {
8991
- "name": "Title",
8992
- "price": "Variant Price",
8993
- "brand": "Vendor",
8994
- "image": "Image Src",
8995
- "stock": "Variant Inventory Qty"
8996
- }
8997
- `;
8303
+ Return a JSON object like {"name":"Title","price":"Price",...}. Omit unmapped properties.`
8304
+ }
8305
+ ];
8998
8306
  try {
8999
- const response = await llm.chat(
9000
- [
9001
- { role: "system", content: "You are a database schema expert. You ONLY respond with valid JSON." },
9002
- { role: "user", content: prompt }
9003
- ],
9004
- ""
9005
- );
9006
- const startIdx = response.indexOf("{");
9007
- if (startIdx !== -1) {
9008
- let braceCount = 0;
9009
- let endIdx = -1;
9010
- for (let i = startIdx; i < response.length; i++) {
9011
- if (response[i] === "{") braceCount++;
9012
- else if (response[i] === "}") {
9013
- braceCount--;
9014
- if (braceCount === 0) {
9015
- endIdx = i;
9016
- break;
9017
- }
9018
- }
8307
+ const baseUrl = (_a2 = llm == null ? void 0 : llm.baseUrl) != null ? _a2 : "";
8308
+ const apiKey = (_b = llm == null ? void 0 : llm.apiKey) != null ? _b : "";
8309
+ const model = (_c = llm == null ? void 0 : llm.model) != null ? _c : "llama-3.1-8b-instant";
8310
+ let responseText;
8311
+ if (baseUrl) {
8312
+ const endpoint = `${baseUrl.replace(/\/$/, "")}/chat/completions`;
8313
+ const headers = { "Content-Type": "application/json" };
8314
+ if (apiKey) headers["Authorization"] = `Bearer ${apiKey}`;
8315
+ const res = await fetch(endpoint, {
8316
+ method: "POST",
8317
+ headers,
8318
+ body: JSON.stringify({
8319
+ model,
8320
+ messages,
8321
+ max_tokens: 256,
8322
+ // Only needs a small JSON object back
8323
+ temperature: 0,
8324
+ stream: false
8325
+ }),
8326
+ signal: AbortSignal.timeout(8e3)
8327
+ });
8328
+ if (res.ok) {
8329
+ const data = await res.json();
8330
+ responseText = (_k = (_j = (_f = (_e = (_d = data == null ? void 0 : data.choices) == null ? void 0 : _d[0]) == null ? void 0 : _e.message) == null ? void 0 : _f.content) != null ? _j : (_i = (_h = (_g2 = data == null ? void 0 : data.choices) == null ? void 0 : _g2[0]) == null ? void 0 : _h.delta) == null ? void 0 : _i.content) != null ? _k : void 0;
8331
+ } else {
8332
+ console.warn(`[SchemaMapper] LLM returned ${res.status}, falling back to heuristics.`);
9019
8333
  }
9020
- if (endIdx !== -1) {
9021
- const jsonContent = response.substring(startIdx, endIdx + 1);
9022
- const cleanJson = this.sanitizeJson(jsonContent);
9023
- const mapping = JSON.parse(cleanJson);
8334
+ }
8335
+ if (responseText) {
8336
+ const mapping = this._parseJson(responseText);
8337
+ if (mapping) {
9024
8338
  this.cache.set(cacheKey, mapping);
9025
8339
  return mapping;
9026
8340
  }
@@ -9028,23 +8342,42 @@ Example:
9028
8342
  } catch (error) {
9029
8343
  console.warn("[SchemaMapper] AI training failed, falling back to heuristics:", error);
9030
8344
  }
8345
+ this.cache.set(cacheKey, {});
9031
8346
  return {};
9032
8347
  }
9033
- /**
9034
- * Forgiving JSON parser that fixes common AI formatting mistakes.
9035
- */
9036
- static sanitizeJson(s) {
8348
+ static _parseJson(text) {
8349
+ const startIdx = text.indexOf("{");
8350
+ if (startIdx === -1) return null;
8351
+ let braceCount = 0;
8352
+ let endIdx = -1;
8353
+ for (let i = startIdx; i < text.length; i++) {
8354
+ if (text[i] === "{") braceCount++;
8355
+ else if (text[i] === "}") {
8356
+ braceCount--;
8357
+ if (braceCount === 0) {
8358
+ endIdx = i;
8359
+ break;
8360
+ }
8361
+ }
8362
+ }
8363
+ if (endIdx === -1) return null;
8364
+ try {
8365
+ return JSON.parse(this._sanitizeJson(text.substring(startIdx, endIdx + 1)));
8366
+ } catch (e) {
8367
+ return null;
8368
+ }
8369
+ }
8370
+ static _sanitizeJson(s) {
9037
8371
  return s.replace(/\/\*[\s\S]*?\*\/|([^:]|^)\/\/.*$/gm, "").replace(/[\u201C\u201D\u2018\u2019]/g, '"').replace(/'/g, '"').replace(/([{,]\s*)([a-zA-Z0-9_]+?)\s*:/g, '$1"$2":').replace(/,\s*([}\]])/g, "$1").trim();
9038
8372
  }
9039
8373
  static getCached(projectId, keys) {
9040
- const cacheKey = `${projectId}:${keys.sort().join(",")}`;
8374
+ const cacheKey = `${projectId}:${keys.slice().sort().join(",")}`;
9041
8375
  return this.cache.get(cacheKey);
9042
8376
  }
9043
8377
  };
9044
8378
  SchemaMapper.cache = /* @__PURE__ */ new Map();
9045
- /**
9046
- * Descriptions of standard UI properties to help the AI map fields accurately.
9047
- */
8379
+ /** In-flight deduplication — prevents concurrent identical LLM calls. */
8380
+ SchemaMapper.pending = /* @__PURE__ */ new Map();
9048
8381
  SchemaMapper.TARGET_PROPERTIES = {
9049
8382
  name: "The primary title, name, or label of the item",
9050
8383
  price: "The numeric cost, price, MSRP, or amount",
@@ -9516,19 +8849,6 @@ ${m.content}`).join("\n\n---\n\n");
9516
8849
  const wantsExhaustiveList = true;
9517
8850
  const retrievalLimit = Math.max(topK * 50, 1e3);
9518
8851
  const rawSources = ((strategyResult === "vector" || strategyResult === "both") && queryVector && queryVector.length > 0 ? yield new __await(this.vectorDB.query(queryVector, retrievalLimit, ns, filter)) : []).filter((s) => Boolean(s && typeof s === "object"));
9519
- console.log("[Pipeline] Raw vectorDB.query response:", {
9520
- rawCount: rawSources.length,
9521
- sample: rawSources.slice(0, 2).map((s) => {
9522
- var _a3;
9523
- return {
9524
- id: s == null ? void 0 : s.id,
9525
- score: s == null ? void 0 : s.score,
9526
- contentType: typeof (s == null ? void 0 : s.content),
9527
- contentSnippet: String((_a3 = s == null ? void 0 : s.content) != null ? _a3 : "").substring(0, 150),
9528
- metadataKeys: Object.keys((s == null ? void 0 : s.metadata) || {})
9529
- };
9530
- })
9531
- });
9532
8852
  const retrieveEnd = performance.now();
9533
8853
  const embedMs = retrieveEnd - embedStart;
9534
8854
  const retrieveMs = retrieveEnd - embedStart;
@@ -9557,21 +8877,6 @@ ${(_a3 = m == null ? void 0 : m.content) != null ? _a3 : ""}`;
9557
8877
  var _a3, _b2;
9558
8878
  return ((_a3 = b == null ? void 0 : b.score) != null ? _a3 : 0) - ((_b2 = a == null ? void 0 : a.score) != null ? _b2 : 0);
9559
8879
  });
9560
- console.log("[Pipeline] Final sources for prompt & UI:", {
9561
- count: sources.length,
9562
- totalRawCount: rawSources.length,
9563
- sources: sources.slice(0, 10).map((s, idx) => {
9564
- var _a3;
9565
- return {
9566
- rank: idx + 1,
9567
- id: s == null ? void 0 : s.id,
9568
- score: s == null ? void 0 : s.score,
9569
- contentType: typeof (s == null ? void 0 : s.content),
9570
- contentSnippet: String((_a3 = s == null ? void 0 : s.content) != null ? _a3 : "").substring(0, 150),
9571
- metadata: s == null ? void 0 : s.metadata
9572
- };
9573
- })
9574
- });
9575
8880
  if (graphData && graphData.nodes.length > 0) {
9576
8881
  const graphContext = graphData.nodes.map(
9577
8882
  (n) => `Entity: ${n.label} (${n.id})${n.properties ? " - " + JSON.stringify(n.properties) : ""}`
@@ -9813,9 +9118,9 @@ ${context}`;
9813
9118
  const trace = buildTrace(hallucinationResult);
9814
9119
  const isTelemetryActive = (_A = (_z = this.config.telemetry) == null ? void 0 : _z.enabled) != null ? _A : Boolean(this.config.licenseKey);
9815
9120
  if (isTelemetryActive) {
9816
- const defaultUrl = process.env.NODE_ENV === "development" && !process.env.TELEMETRY_URL && !process.env.NEXT_PUBLIC_TELEMETRY_URL ? "http://localhost:3001/api/telemetry" : "https://retrivora.com/api/telemetry";
9121
+ const defaultUrl = "https://www.retrivora.com/api/telemetry";
9817
9122
  const telemetryUrl = ((_B = this.config.telemetry) == null ? void 0 : _B.url) || process.env.TELEMETRY_URL || process.env.NEXT_PUBLIC_TELEMETRY_URL || defaultUrl;
9818
- const absoluteUrl = telemetryUrl.startsWith("http") ? telemetryUrl : (process.env.NEXT_PUBLIC_APP_URL || `http://localhost:${process.env.PORT || 3e3}`) + telemetryUrl;
9123
+ const absoluteUrl = telemetryUrl.startsWith("http") ? telemetryUrl : "https://www.retrivora.com" + (telemetryUrl.startsWith("/") ? telemetryUrl : "/" + telemetryUrl);
9819
9124
  (async () => {
9820
9125
  var _a3, _b2, _c2, _d2, _e2;
9821
9126
  try {
@@ -10435,8 +9740,8 @@ var VectorPlugin = class {
10435
9740
  }
10436
9741
  try {
10437
9742
  return await this.pipeline.getSuggestions(query, namespace);
10438
- } catch (err) {
10439
- throw wrapError(err, "RETRIEVAL_FAILED");
9743
+ } catch (e) {
9744
+ return [];
10440
9745
  }
10441
9746
  }
10442
9747
  };
@@ -11249,15 +10554,14 @@ function getOrCreatePlugin(configOrPlugin) {
11249
10554
  return _g[cacheKey];
11250
10555
  }
11251
10556
  function reportTelemetry(req, plugin, action, status, details, trace) {
11252
- var _a2, _b, _c, _d, _e, _f, _g2, _h;
10557
+ var _a2, _b, _c, _d, _e, _f, _g2;
11253
10558
  try {
11254
10559
  const config = plugin.getConfig();
11255
10560
  const licenseKey = config.licenseKey || process.env.RAG_LICENSE_KEY || process.env.RETRIVORA_LICENSE_KEY || process.env.NEXT_PUBLIC_RETRIVORA_LICENSE_KEY;
11256
10561
  const telemetryConfig = config.telemetry;
11257
- const enabled = (_a2 = telemetryConfig == null ? void 0 : telemetryConfig.enabled) != null ? _a2 : Boolean(licenseKey);
11258
- const defaultUrl = process.env.NODE_ENV === "development" && !process.env.TELEMETRY_URL && !process.env.NEXT_PUBLIC_TELEMETRY_URL ? "http://localhost:3001/api/telemetry" : "https://www.retrivora.com/api/telemetry";
11259
- const telemetryUrl = (telemetryConfig == null ? void 0 : telemetryConfig.url) || process.env.TELEMETRY_URL || process.env.NEXT_PUBLIC_TELEMETRY_URL || defaultUrl;
11260
10562
  const host = req.headers.get("host") || "localhost";
10563
+ const defaultUrl = "https://www.retrivora.com/api/telemetry";
10564
+ const telemetryUrl = (telemetryConfig == null ? void 0 : telemetryConfig.url) || process.env.TELEMETRY_URL || process.env.NEXT_PUBLIC_TELEMETRY_URL || defaultUrl;
11261
10565
  const userAgent = req.headers.get("user-agent") || `Retrivora-SDK/${SDK_VERSION}`;
11262
10566
  let absoluteUrl = telemetryUrl;
11263
10567
  if (!telemetryUrl.startsWith("http")) {
@@ -11265,11 +10569,11 @@ function reportTelemetry(req, plugin, action, status, details, trace) {
11265
10569
  absoluteUrl = `${proto}://${host}${telemetryUrl}`;
11266
10570
  }
11267
10571
  const projectId = config.projectId || "default";
11268
- const model = (trace == null ? void 0 : trace.model) || ((_b = config.llm) == null ? void 0 : _b.model) || ((_c = config.embedding) == null ? void 0 : _c.model) || "llama-3.1-8b-instant";
11269
- const provider = (trace == null ? void 0 : trace.provider) || ((_d = config.llm) == null ? void 0 : _d.provider) || ((_e = config.embedding) == null ? void 0 : _e.provider) || "groq";
11270
- const tokens = Number(((_f = trace == null ? void 0 : trace.tokens) == null ? void 0 : _f.totalTokens) || (trace == null ? void 0 : trace.totalTokens) || 0);
11271
- const costUsd = Number(((_g2 = trace == null ? void 0 : trace.tokens) == null ? void 0 : _g2.estimatedCostUsd) || (trace == null ? void 0 : trace.costUsd) || 0);
11272
- const latencyMs = Number(((_h = trace == null ? void 0 : trace.latency) == null ? void 0 : _h.totalMs) || (trace == null ? void 0 : trace.latencyMs) || 0);
10572
+ const model = (trace == null ? void 0 : trace.model) || ((_a2 = config.llm) == null ? void 0 : _a2.model) || ((_b = config.embedding) == null ? void 0 : _b.model) || "llama-3.1-8b-instant";
10573
+ const provider = (trace == null ? void 0 : trace.provider) || ((_c = config.llm) == null ? void 0 : _c.provider) || ((_d = config.embedding) == null ? void 0 : _d.provider) || "groq";
10574
+ const tokens = Number(((_e = trace == null ? void 0 : trace.tokens) == null ? void 0 : _e.totalTokens) || (trace == null ? void 0 : trace.totalTokens) || 0);
10575
+ const costUsd = Number(((_f = trace == null ? void 0 : trace.tokens) == null ? void 0 : _f.estimatedCostUsd) || (trace == null ? void 0 : trace.costUsd) || 0);
10576
+ const latencyMs = Number(((_g2 = trace == null ? void 0 : trace.latency) == null ? void 0 : _g2.totalMs) || (trace == null ? void 0 : trace.latencyMs) || 0);
11273
10577
  const payload = {
11274
10578
  trace,
11275
10579
  licenseKey,
@@ -11346,7 +10650,7 @@ function createChatHandler(configOrPlugin, options) {
11346
10650
  const plugin = getOrCreatePlugin(configOrPlugin);
11347
10651
  const storage = new DatabaseStorage(plugin.getConfig());
11348
10652
  const onAuthorize = options == null ? void 0 : options.onAuthorize;
11349
- return async function POST(req) {
10653
+ return async function POST(req, context) {
11350
10654
  var _a2, _b, _c, _d;
11351
10655
  const authResult = await checkAuth(req, onAuthorize);
11352
10656
  if (authResult) return authResult;
@@ -11402,7 +10706,7 @@ function createStreamHandler(configOrPlugin, options) {
11402
10706
  const plugin = getOrCreatePlugin(configOrPlugin);
11403
10707
  const storage = new DatabaseStorage(plugin.getConfig());
11404
10708
  const onAuthorize = options == null ? void 0 : options.onAuthorize;
11405
- return async function POST(req) {
10709
+ return async function POST(req, context) {
11406
10710
  var _a2;
11407
10711
  const authResult = await checkAuth(req, onAuthorize);
11408
10712
  if (authResult) return authResult;
@@ -11552,7 +10856,7 @@ function createStreamHandler(configOrPlugin, options) {
11552
10856
  function createIngestHandler(configOrPlugin, options) {
11553
10857
  const plugin = getOrCreatePlugin(configOrPlugin);
11554
10858
  const onAuthorize = options == null ? void 0 : options.onAuthorize;
11555
- return async function POST(req) {
10859
+ return async function POST(req, context) {
11556
10860
  const authResult = await checkAuth(req, onAuthorize);
11557
10861
  if (authResult) return authResult;
11558
10862
  try {
@@ -11596,7 +10900,7 @@ function createHealthHandler(configOrPlugin, options) {
11596
10900
  function createUploadHandler(configOrPlugin, options) {
11597
10901
  const plugin = getOrCreatePlugin(configOrPlugin);
11598
10902
  const onAuthorize = options == null ? void 0 : options.onAuthorize;
11599
- return async function POST(req) {
10903
+ return async function POST(req, context) {
11600
10904
  const authResult = await checkAuth(req, onAuthorize);
11601
10905
  if (authResult) return authResult;
11602
10906
  try {