@retrivora-ai/rag-engine 2.2.3 → 2.2.5

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,645 +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("Groq API Key missing. Please set GROQ_API_KEY in environment variables.");
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
- console.log(`[LLM Gateway Router] Dispatching chat request: model=${activeModel}, provider=${provider}, hasCustomKey=${Boolean(customGroqKey)}, hasGlobalGroqKey=${Boolean(process.env.GROQ_API_KEY)}`);
611
- try {
612
- switch (provider) {
613
- case "groq":
614
- return await handleGroqRequest(__spreadProps(__spreadValues({}, req), { model: activeModel }), effectiveKey);
615
- case "openai":
616
- return await handleOpenAIRequest(__spreadProps(__spreadValues({}, req), { model: activeModel }), effectiveKey);
617
- case "gemini":
618
- return await handleGeminiRequest(__spreadProps(__spreadValues({}, req), { model: activeModel }), effectiveKey);
619
- case "anthropic":
620
- return await handleAnthropicRequest(__spreadProps(__spreadValues({}, req), { model: activeModel }), effectiveKey);
621
- case "ollama":
622
- return await handleOllamaRequest(__spreadProps(__spreadValues({}, req), { model: activeModel }));
623
- case "huggingface":
624
- return await handleHuggingFaceChatRequest(__spreadProps(__spreadValues({}, req), { model: activeModel }), effectiveKey);
625
- default:
626
- throw new Error(`Unsupported LLM provider for model: ${activeModel}`);
627
- }
628
- } catch (error) {
629
- console.error(`[LLM Gateway Router] Provider '${provider}' failed for model '${req.model}':`, {
630
- message: error.message,
631
- stack: error.stack
632
- });
633
- if (/rate[- ]?limit|429|exhausted/i.test(error.message)) {
634
- const isGroqKey = process.env.GROQ_API_KEY || effectiveKey && effectiveKey.startsWith("gsk_");
635
- const reqModelLower = req.model.toLowerCase();
636
- if (isGroqKey && !reqModelLower.includes("llama-3.3-70b")) {
637
- console.warn(`[LLM Gateway] Provider ${provider} rate limited (${error.message}). Falling back to secondary Groq model (llama-3.3-70b-versatile)...`);
638
- try {
639
- return await handleGroqRequest(__spreadProps(__spreadValues({}, req), { model: "llama-3.3-70b-versatile" }), effectiveKey);
640
- } catch (fErr) {
641
- console.error("[LLM Gateway] Fallback groq/llama-3.3-70b-versatile failed:", fErr.message);
642
- }
643
- }
644
- const geminiKey = process.env.GEMINI_API_KEY || effectiveKey;
645
- if (provider !== "gemini" && geminiKey && (geminiKey.startsWith("AIza") || !geminiKey.startsWith("AQ."))) {
646
- console.warn(`[LLM Gateway] Provider ${provider} rate limited (${error.message}). Falling back to Google Gemini (gemini-2.5-flash)...`);
647
- try {
648
- return await handleGeminiRequest(__spreadProps(__spreadValues({}, req), { model: "gemini-2.5-flash" }), effectiveKey);
649
- } catch (fErr) {
650
- console.error("[LLM Gateway] Fallback gemini-2.5-flash failed:", fErr.message);
651
- }
652
- }
653
- if (provider !== "huggingface" && (process.env.HF_TOKEN || process.env.HUGGINGFACE_API_KEY)) {
654
- console.warn(`[LLM Gateway] Provider ${provider} rate limited (${error.message}). Falling back to Hugging Face (Qwen/Qwen2.5-Coder-32B-Instruct)...`);
655
- try {
656
- return await handleHuggingFaceChatRequest(__spreadProps(__spreadValues({}, req), { model: "Qwen/Qwen2.5-Coder-32B-Instruct" }), effectiveKey);
657
- } catch (fErr) {
658
- console.error("[LLM Gateway] Fallback HuggingFace Qwen failed:", fErr.message);
659
- }
660
- }
661
- if (provider !== "openai" && process.env.OPENAI_API_KEY) {
662
- console.warn(`[LLM Gateway] Provider ${provider} rate limited (${error.message}). Falling back to OpenAI (gpt-4o-mini)...`);
663
- try {
664
- return await handleOpenAIRequest(__spreadProps(__spreadValues({}, req), { model: "gpt-4o-mini" }), effectiveKey);
665
- } catch (e) {
666
- }
667
- }
668
- console.warn(`[LLM Gateway] Provider ${provider} rate limited (${error.message}). Falling back to local Ollama (llama3.2)...`);
669
- return handleOllamaRequest(__spreadProps(__spreadValues({}, req), { model: "llama3.2" }));
670
- }
671
- throw error;
672
- }
673
- }
674
- async function dispatchEmbedding(req, apiKeyOverride) {
675
- const effectiveKey = cleanApiKeyOverride(apiKeyOverride);
676
- if (req.model.startsWith("hf/") || req.model.startsWith("huggingface/") || req.model.includes("bge-")) {
677
- try {
678
- return await handleHuggingFaceEmbedding(req, effectiveKey);
679
- } catch (err) {
680
- console.warn("[LLM Gateway] HuggingFace explicit model embedding failed, falling back to default gateway chain:", err);
681
- }
682
- }
683
- const geminiKey = process.env.GEMINI_API_KEY || effectiveKey;
684
- const isGeminiKeyValid = Boolean(geminiKey && !geminiKey.startsWith("eyJ"));
685
- if (isGeminiKeyValid) {
686
- try {
687
- return await handleGeminiEmbedding(req, effectiveKey);
688
- } catch (err) {
689
- console.warn("[LLM Gateway] Gemini embedding failed:", err);
690
- }
691
- }
692
- if (process.env.OPENAI_API_KEY) {
693
- try {
694
- return await handleOpenAIEmbedding(req, effectiveKey);
695
- } catch (err) {
696
- console.warn("[LLM Gateway] OpenAI embedding failed:", err);
697
- }
698
- }
699
- if (process.env.HUGGINGFACE_API_KEY || process.env.HF_TOKEN) {
700
- try {
701
- return await handleHuggingFaceEmbedding(req, effectiveKey);
702
- } catch (err) {
703
- console.warn("[LLM Gateway] HuggingFace fallback embedding failed:", err);
704
- }
705
- }
706
- return handleGeminiEmbedding(req, effectiveKey);
707
- }
708
- var SUPPORTED_MODELS;
709
- var init_router = __esm({
710
- "../../services/llm-gateway/router.ts"() {
711
- "use strict";
712
- init_groq();
713
- init_openai();
714
- init_gemini();
715
- init_huggingface();
716
- init_anthropic();
717
- init_ollama();
718
- SUPPORTED_MODELS = [
719
- { id: "groq/llama-3.1-8b-instant", object: "model", created: 17e8, owned_by: "groq" },
720
- { id: "llama-3.1-8b-instant", object: "model", created: 17e8, owned_by: "groq" },
721
- { id: "groq/llama-3.3-70b-versatile", object: "model", created: 17e8, owned_by: "groq" },
722
- { id: "llama-3.3-70b-versatile", object: "model", created: 17e8, owned_by: "groq" },
723
- { id: "gpt-4o-mini", object: "model", created: 17e8, owned_by: "openai" },
724
- { id: "openai/gpt-4o-mini", object: "model", created: 17e8, owned_by: "openai" },
725
- { id: "gpt-4o", object: "model", created: 17e8, owned_by: "openai" },
726
- { id: "gemini-2.5-flash", object: "model", created: 17e8, owned_by: "google" },
727
- { id: "google/gemini-2.5-flash", object: "model", created: 17e8, owned_by: "google" },
728
- { id: "claude-3-5-haiku-20241022", object: "model", created: 17e8, owned_by: "anthropic" },
729
- { id: "anthropic/claude-3-5-haiku-20241022", object: "model", created: 17e8, owned_by: "anthropic" },
730
- { id: "text-embedding-004", object: "model", created: 17e8, owned_by: "google" },
731
- { id: "google/text-embedding-004", object: "model", created: 17e8, owned_by: "google" },
732
- { id: "BAAI/bge-base-en-v1.5", object: "model", created: 17e8, owned_by: "huggingface" },
733
- { id: "huggingface/BAAI/bge-base-en-v1.5", object: "model", created: 17e8, owned_by: "huggingface" },
734
- { id: "groq/qwen3-32b", object: "model", created: 17e8, owned_by: "groq" },
735
- { id: "qwen/qwen3-32b", object: "model", created: 17e8, owned_by: "groq" },
736
- { id: "qwen/qwen3-embedding-8b", object: "model", created: 17e8, owned_by: "qwen" },
737
- { id: "qwen3-embedding-8b", object: "model", created: 17e8, owned_by: "qwen" },
738
- { id: "ollama/llama3.2", object: "model", created: 17e8, owned_by: "ollama" }
739
- ];
740
- if (typeof globalThis !== "undefined") {
741
- const _g2 = globalThis;
742
- _g2.__retrivoraDispatchChat = dispatchChatCompletion;
743
- _g2.__retrivoraDispatchEmbedding = dispatchEmbedding;
744
- }
745
- }
746
- });
747
-
748
109
  // src/providers/vectordb/BaseVectorProvider.ts
749
110
  var BaseVectorProvider;
750
111
  var init_BaseVectorProvider = __esm({
@@ -801,8 +162,8 @@ var init_ConfigFetcher = __esm({
801
162
  process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL,
802
163
  "https://www.retrivora.com",
803
164
  "https://retrivora.com",
804
- "http://localhost:3001",
805
- "http://localhost:3000"
165
+ "http://localhost:3000",
166
+ "http://localhost:3001"
806
167
  ].filter(Boolean);
807
168
  for (const baseUrl of controlPlaneUrls) {
808
169
  try {
@@ -3357,7 +2718,7 @@ function getEnvConfig(env = process.env, base) {
3357
2718
  },
3358
2719
  telemetry: {
3359
2720
  enabled: telemetryEnabled,
3360
- 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"
3361
2722
  }
3362
2723
  }, readString(env, "GRAPH_DB_PROVIDER") ? {
3363
2724
  graphDb: {
@@ -4606,9 +3967,7 @@ var OPENAI_BASE = {
4606
3967
  };
4607
3968
  var LLM_PROFILES = {
4608
3969
  "openai-compatible": OPENAI_BASE,
4609
- "litellm": __spreadProps(__spreadValues({}, OPENAI_BASE), {
4610
- chatPayloadTemplate: '{"model":"{{model}}","messages":{{messages}},"max_tokens":{{maxTokens}},"temperature":{{temperature}},"stream":false}'
4611
- }),
3970
+ "litellm": __spreadValues({}, OPENAI_BASE),
4612
3971
  "anthropic-claude": {
4613
3972
  chatPath: "/v1/messages",
4614
3973
  responseExtractPath: "content[0].text",
@@ -4752,20 +4111,8 @@ ${context != null ? context : "None"}` },
4752
4111
  return String(result2);
4753
4112
  }
4754
4113
  } catch (httpErr) {
4755
- console.warn(`[UniversalLLMAdapter] Direct HTTP POST to ${this.baseUrl}${path2} failed (${httpErr.message}). Attempting in-process gateway dispatch fallback...`);
4756
4114
  const _g2 = globalThis;
4757
- let dispatch = _g2.__retrivoraDispatchChat;
4758
- if (typeof dispatch !== "function") {
4759
- try {
4760
- const gateway = await Promise.resolve().then(() => (init_router(), router_exports));
4761
- if (gateway == null ? void 0 : gateway.dispatchChatCompletion) {
4762
- _g2.__retrivoraDispatchChat = gateway.dispatchChatCompletion;
4763
- _g2.__retrivoraDispatchEmbedding = gateway.dispatchEmbedding;
4764
- dispatch = gateway.dispatchChatCompletion;
4765
- }
4766
- } catch (e) {
4767
- }
4768
- }
4115
+ const dispatch = _g2.__retrivoraDispatchChat;
4769
4116
  if (typeof dispatch === "function") {
4770
4117
  const res = await dispatch({
4771
4118
  model: this.model,
@@ -4791,11 +4138,10 @@ ${context != null ? context : "None"}` },
4791
4138
  /**
4792
4139
  * Streaming chat using native fetch + ReadableStream.
4793
4140
  * Parses OpenAI-compatible SSE frames: `data: {...}\n\n`
4794
- * Works with vLLM, LMStudio, Together AI, Fireworks, and any OpenAI-compatible API.
4795
4141
  */
4796
4142
  chatStream(messages, context) {
4797
4143
  return __asyncGenerator(this, null, function* () {
4798
- var _a2, _b, _c, _d, _e;
4144
+ var _a2, _b, _c, _d, _e, _f;
4799
4145
  const path2 = (_a2 = this.opts.chatPath) != null ? _a2 : "/chat/completions";
4800
4146
  const url = `${this.baseUrl.replace(/\/$/, "")}${path2}`;
4801
4147
  const extractPath = ((_b = this.opts.responseExtractPath) != null ? _b : "choices[0].message.content").replace("message.content", "delta.content");
@@ -4830,22 +4176,35 @@ ${context != null ? context : "None"}` },
4830
4176
  stream: true
4831
4177
  };
4832
4178
  }
4833
- const isSelfHost = this.baseUrl.includes("retrivora.com") || this.baseUrl.includes("localhost");
4834
4179
  let streamBody = null;
4835
- if (isSelfHost || Boolean(process.env.VERCEL)) {
4836
- const _g2 = globalThis;
4837
- let dispatch = _g2.__retrivoraDispatchChat;
4838
- if (typeof dispatch !== "function") {
4839
- try {
4840
- const gateway = yield new __await(Promise.resolve().then(() => (init_router(), router_exports)));
4841
- if (gateway == null ? void 0 : gateway.dispatchChatCompletion) {
4842
- _g2.__retrivoraDispatchChat = gateway.dispatchChatCompletion;
4843
- _g2.__retrivoraDispatchEmbedding = gateway.dispatchEmbedding;
4844
- 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;
4845
4194
  }
4846
- } catch (e) {
4195
+ } else if (response.body) {
4196
+ streamBody = response.body;
4847
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...`);
4848
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;
4849
4208
  if (typeof dispatch === "function") {
4850
4209
  try {
4851
4210
  const res = yield new __await(dispatch({
@@ -4863,29 +4222,14 @@ ${context != null ? context : "None"}` },
4863
4222
  yield content;
4864
4223
  return;
4865
4224
  }
4866
- throw new Error(`[UniversalLLMAdapter] In-process dispatch stream returned empty response for model: ${this.model}`);
4867
4225
  }
4868
4226
  } catch (dispatchErr) {
4869
- throw dispatchErr;
4227
+ console.warn("[UniversalLLMAdapter] In-process dispatch error:", dispatchErr);
4870
4228
  }
4871
- } else {
4872
- 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.`);
4873
4229
  }
4874
4230
  }
4875
4231
  if (!streamBody) {
4876
- const response = yield new __await(fetch(url, {
4877
- method: "POST",
4878
- headers: this.resolvedHeaders,
4879
- body: JSON.stringify(payload)
4880
- }));
4881
- if (!response.ok) {
4882
- const errorText = yield new __await(response.text().catch(() => response.statusText));
4883
- throw new Error(`[UniversalLLMAdapter] Streaming request failed (${response.status}): ${errorText}`);
4884
- }
4885
- if (!response.body) {
4886
- throw new Error("[UniversalLLMAdapter] Response body is null \u2014 server did not send a streaming response.");
4887
- }
4888
- streamBody = response.body;
4232
+ throw new Error(`[UniversalLLMAdapter] Streaming request failed. Ensure RETRIVORA_LICENSE_KEY is valid or LLM service is available.`);
4889
4233
  }
4890
4234
  const reader = streamBody.getReader();
4891
4235
  const decoder = new TextDecoder("utf-8");
@@ -4896,14 +4240,14 @@ ${context != null ? context : "None"}` },
4896
4240
  if (done) break;
4897
4241
  buffer += decoder.decode(value, { stream: true });
4898
4242
  const lines = buffer.split("\n");
4899
- buffer = (_c = lines.pop()) != null ? _c : "";
4243
+ buffer = (_d = lines.pop()) != null ? _d : "";
4900
4244
  for (const line of lines) {
4901
4245
  const trimmed = line.trim();
4902
4246
  if (!trimmed || trimmed === "data: [DONE]") continue;
4903
4247
  if (!trimmed.startsWith("data:")) continue;
4904
4248
  try {
4905
4249
  const json = JSON.parse(trimmed.slice(5).trim());
4906
- const text = (_d = resolvePath(json, extractPath)) != null ? _d : extractContent(json);
4250
+ const text = (_e = resolvePath(json, extractPath)) != null ? _e : extractContent(json);
4907
4251
  if (text && typeof text === "string") yield text;
4908
4252
  } catch (e) {
4909
4253
  }
@@ -4913,7 +4257,7 @@ ${context != null ? context : "None"}` },
4913
4257
  const jsonStr = buffer.replace(/^data:\s*/, "").trim();
4914
4258
  try {
4915
4259
  const json = JSON.parse(jsonStr);
4916
- const text = (_e = resolvePath(json, extractPath)) != null ? _e : extractContent(json);
4260
+ const text = (_f = resolvePath(json, extractPath)) != null ? _f : extractContent(json);
4917
4261
  if (text && typeof text === "string") yield text;
4918
4262
  } catch (e) {
4919
4263
  }
@@ -4926,74 +4270,42 @@ ${context != null ? context : "None"}` },
4926
4270
  async embed(text) {
4927
4271
  var _a2, _b, _c, _d, _e;
4928
4272
  const path2 = (_a2 = this.opts.embedPath) != null ? _a2 : "/embeddings";
4929
- let payload;
4930
- if (this.opts.embedPayloadTemplate) {
4931
- payload = buildPayload(this.opts.embedPayloadTemplate, {
4932
- model: this.model,
4933
- input: text
4934
- });
4935
- } else {
4936
- payload = {
4937
- model: this.model,
4938
- input: text
4939
- };
4940
- }
4273
+ const payload = this.opts.embedPayloadTemplate ? buildPayload(this.opts.embedPayloadTemplate, { input: text, model: this.model }) : { input: text, model: this.model };
4941
4274
  try {
4942
4275
  const { data: data2 } = await this.http.post(path2, payload);
4943
4276
  const extractPath2 = (_b = this.opts.embedExtractPath) != null ? _b : "data[0].embedding";
4944
4277
  const vector2 = resolvePath(data2, extractPath2);
4945
- if (Array.isArray(vector2)) {
4946
- return vector2;
4947
- }
4948
- } catch (httpErr) {
4949
- 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) {
4950
4280
  const _g2 = globalThis;
4951
- let dispatch = _g2.__retrivoraDispatchEmbedding;
4952
- if (typeof dispatch !== "function") {
4953
- try {
4954
- const gateway = await Promise.resolve().then(() => (init_router(), router_exports));
4955
- if (gateway == null ? void 0 : gateway.dispatchEmbedding) {
4956
- _g2.__retrivoraDispatchChat = gateway.dispatchChatCompletion;
4957
- _g2.__retrivoraDispatchEmbedding = gateway.dispatchEmbedding;
4958
- dispatch = gateway.dispatchEmbedding;
4959
- }
4960
- } catch (e) {
4961
- }
4962
- }
4963
- if (typeof dispatch === "function") {
4964
- const res = await dispatch({
4965
- model: this.model,
4966
- input: text
4967
- }, this.apiKey);
4281
+ const dispatchEmbed = _g2.__retrivoraDispatchEmbedding;
4282
+ if (typeof dispatchEmbed === "function") {
4283
+ const res = await dispatchEmbed({ input: text, model: this.model }, this.apiKey);
4968
4284
  if ((_d = (_c = res == null ? void 0 : res.data) == null ? void 0 : _c[0]) == null ? void 0 : _d.embedding) {
4969
4285
  return res.data[0].embedding;
4970
4286
  }
4971
4287
  }
4972
- throw httpErr;
4973
4288
  }
4974
4289
  const { data } = await this.http.post(path2, payload);
4975
4290
  const extractPath = (_e = this.opts.embedExtractPath) != null ? _e : "data[0].embedding";
4976
4291
  const vector = resolvePath(data, extractPath);
4977
4292
  if (!Array.isArray(vector)) {
4978
- 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.`);
4979
4294
  }
4980
4295
  return vector;
4981
4296
  }
4982
4297
  async batchEmbed(texts) {
4983
- const vectors = [];
4298
+ const results = [];
4984
4299
  for (const text of texts) {
4985
- vectors.push(await this.embed(text));
4300
+ results.push(await this.embed(text));
4986
4301
  }
4987
- return vectors;
4302
+ return results;
4988
4303
  }
4989
4304
  async ping() {
4990
4305
  try {
4991
- if (this.opts.pingPath) {
4992
- await this.http.get(this.opts.pingPath);
4993
- }
4306
+ await this.embed("ping");
4994
4307
  return true;
4995
- } catch (err) {
4996
- console.error("[UniversalLLMAdapter] Ping failed:", err);
4308
+ } catch (e) {
4997
4309
  return false;
4998
4310
  }
4999
4311
  }
@@ -5399,7 +4711,7 @@ var ConfigValidator = class {
5399
4711
  // package.json
5400
4712
  var package_default = {
5401
4713
  name: "@retrivora-ai/rag-engine",
5402
- version: "2.2.3",
4714
+ version: "2.2.5",
5403
4715
  description: "Retrivora AI is a plug-and-play AI engine for RAG chat experiences \u2014 generic vector DB + LLM provider, embeddable or standalone.",
5404
4716
  author: "Abhinav Alkuchi",
5405
4717
  license: "UNLICENSED",
@@ -5436,6 +4748,8 @@ var package_default = {
5436
4748
  import: "./dist/index.mjs"
5437
4749
  },
5438
4750
  "./style.css": "./dist/index.css",
4751
+ "./index.css": "./dist/index.css",
4752
+ "./styles.css": "./dist/index.css",
5439
4753
  "./handlers": {
5440
4754
  types: "./dist/handlers/index.d.ts",
5441
4755
  require: "./dist/handlers/index.js",
@@ -7618,19 +6932,6 @@ var UITransformer = class _UITransformer {
7618
6932
  if (!retrievedData || retrievedData.length === 0) {
7619
6933
  return this.createTextResponse("No data available", "No relevant data found for your query.");
7620
6934
  }
7621
- console.log("[UITransformer.transform] Processing retrievedData:", {
7622
- userQuery,
7623
- retrievedCount: retrievedData.length,
7624
- sample: retrievedData.slice(0, 2).map((item) => {
7625
- var _a3;
7626
- return {
7627
- id: item == null ? void 0 : item.id,
7628
- contentType: typeof (item == null ? void 0 : item.content),
7629
- contentSnippet: String((_a3 = item == null ? void 0 : item.content) != null ? _a3 : "").substring(0, 150),
7630
- metadataKeys: Object.keys((item == null ? void 0 : item.metadata) || {})
7631
- };
7632
- })
7633
- });
7634
6935
  const resolvedIntent = intent != null ? intent : this.detectIntentHeuristic(userQuery);
7635
6936
  const filteredData = resolvedIntent.filterInStockOnly ? retrievedData.filter((item) => this.determineStockStatus(item)) : retrievedData;
7636
6937
  const profile = this.profileData(filteredData);
@@ -8970,59 +8271,70 @@ RULES:
8970
8271
  var SchemaMapper = class {
8971
8272
  /**
8972
8273
  * Trains the plugin on a set of keys.
8973
- * 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.
8974
8276
  */
8975
8277
  static async train(llm, projectId, keys) {
8976
- const cacheKey = `${projectId}:${keys.sort().join(",")}`;
8278
+ const cacheKey = `${projectId}:${keys.slice().sort().join(",")}`;
8977
8279
  if (this.cache.has(cacheKey)) {
8978
8280
  return this.cache.get(cacheKey);
8979
8281
  }
8980
- 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(", ")}`);
8981
8293
  const propertyList = Object.entries(this.TARGET_PROPERTIES).map(([prop, desc]) => `- ${prop} (${desc})`).join("\n");
8982
- const prompt = `
8983
- 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(", ")}]
8984
8299
 
8985
- Identify which keys best correspond to these standard UI properties:
8300
+ Map to:
8986
8301
  ${propertyList}
8987
8302
 
8988
- 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.
8989
- If no good match is found for a property, omit it.
8990
-
8991
- Example:
8992
- {
8993
- "name": "Title",
8994
- "price": "Variant Price",
8995
- "brand": "Vendor",
8996
- "image": "Image Src",
8997
- "stock": "Variant Inventory Qty"
8998
- }
8999
- `;
8303
+ Return a JSON object like {"name":"Title","price":"Price",...}. Omit unmapped properties.`
8304
+ }
8305
+ ];
9000
8306
  try {
9001
- const response = await llm.chat(
9002
- [
9003
- { role: "system", content: "You are a database schema expert. You ONLY respond with valid JSON." },
9004
- { role: "user", content: prompt }
9005
- ],
9006
- ""
9007
- );
9008
- const startIdx = response.indexOf("{");
9009
- if (startIdx !== -1) {
9010
- let braceCount = 0;
9011
- let endIdx = -1;
9012
- for (let i = startIdx; i < response.length; i++) {
9013
- if (response[i] === "{") braceCount++;
9014
- else if (response[i] === "}") {
9015
- braceCount--;
9016
- if (braceCount === 0) {
9017
- endIdx = i;
9018
- break;
9019
- }
9020
- }
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.`);
9021
8333
  }
9022
- if (endIdx !== -1) {
9023
- const jsonContent = response.substring(startIdx, endIdx + 1);
9024
- const cleanJson = this.sanitizeJson(jsonContent);
9025
- const mapping = JSON.parse(cleanJson);
8334
+ }
8335
+ if (responseText) {
8336
+ const mapping = this._parseJson(responseText);
8337
+ if (mapping) {
9026
8338
  this.cache.set(cacheKey, mapping);
9027
8339
  return mapping;
9028
8340
  }
@@ -9030,23 +8342,42 @@ Example:
9030
8342
  } catch (error) {
9031
8343
  console.warn("[SchemaMapper] AI training failed, falling back to heuristics:", error);
9032
8344
  }
8345
+ this.cache.set(cacheKey, {});
9033
8346
  return {};
9034
8347
  }
9035
- /**
9036
- * Forgiving JSON parser that fixes common AI formatting mistakes.
9037
- */
9038
- 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) {
9039
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();
9040
8372
  }
9041
8373
  static getCached(projectId, keys) {
9042
- const cacheKey = `${projectId}:${keys.sort().join(",")}`;
8374
+ const cacheKey = `${projectId}:${keys.slice().sort().join(",")}`;
9043
8375
  return this.cache.get(cacheKey);
9044
8376
  }
9045
8377
  };
9046
8378
  SchemaMapper.cache = /* @__PURE__ */ new Map();
9047
- /**
9048
- * Descriptions of standard UI properties to help the AI map fields accurately.
9049
- */
8379
+ /** In-flight deduplication — prevents concurrent identical LLM calls. */
8380
+ SchemaMapper.pending = /* @__PURE__ */ new Map();
9050
8381
  SchemaMapper.TARGET_PROPERTIES = {
9051
8382
  name: "The primary title, name, or label of the item",
9052
8383
  price: "The numeric cost, price, MSRP, or amount",
@@ -9518,19 +8849,6 @@ ${m.content}`).join("\n\n---\n\n");
9518
8849
  const wantsExhaustiveList = true;
9519
8850
  const retrievalLimit = Math.max(topK * 50, 1e3);
9520
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"));
9521
- console.log("[Pipeline] Raw vectorDB.query response:", {
9522
- rawCount: rawSources.length,
9523
- sample: rawSources.slice(0, 2).map((s) => {
9524
- var _a3;
9525
- return {
9526
- id: s == null ? void 0 : s.id,
9527
- score: s == null ? void 0 : s.score,
9528
- contentType: typeof (s == null ? void 0 : s.content),
9529
- contentSnippet: String((_a3 = s == null ? void 0 : s.content) != null ? _a3 : "").substring(0, 150),
9530
- metadataKeys: Object.keys((s == null ? void 0 : s.metadata) || {})
9531
- };
9532
- })
9533
- });
9534
8852
  const retrieveEnd = performance.now();
9535
8853
  const embedMs = retrieveEnd - embedStart;
9536
8854
  const retrieveMs = retrieveEnd - embedStart;
@@ -9559,21 +8877,6 @@ ${(_a3 = m == null ? void 0 : m.content) != null ? _a3 : ""}`;
9559
8877
  var _a3, _b2;
9560
8878
  return ((_a3 = b == null ? void 0 : b.score) != null ? _a3 : 0) - ((_b2 = a == null ? void 0 : a.score) != null ? _b2 : 0);
9561
8879
  });
9562
- console.log("[Pipeline] Final sources for prompt & UI:", {
9563
- count: sources.length,
9564
- totalRawCount: rawSources.length,
9565
- sources: sources.slice(0, 10).map((s, idx) => {
9566
- var _a3;
9567
- return {
9568
- rank: idx + 1,
9569
- id: s == null ? void 0 : s.id,
9570
- score: s == null ? void 0 : s.score,
9571
- contentType: typeof (s == null ? void 0 : s.content),
9572
- contentSnippet: String((_a3 = s == null ? void 0 : s.content) != null ? _a3 : "").substring(0, 150),
9573
- metadata: s == null ? void 0 : s.metadata
9574
- };
9575
- })
9576
- });
9577
8880
  if (graphData && graphData.nodes.length > 0) {
9578
8881
  const graphContext = graphData.nodes.map(
9579
8882
  (n) => `Entity: ${n.label} (${n.id})${n.properties ? " - " + JSON.stringify(n.properties) : ""}`
@@ -9815,9 +9118,9 @@ ${context}`;
9815
9118
  const trace = buildTrace(hallucinationResult);
9816
9119
  const isTelemetryActive = (_A = (_z = this.config.telemetry) == null ? void 0 : _z.enabled) != null ? _A : Boolean(this.config.licenseKey);
9817
9120
  if (isTelemetryActive) {
9818
- 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";
9819
9122
  const telemetryUrl = ((_B = this.config.telemetry) == null ? void 0 : _B.url) || process.env.TELEMETRY_URL || process.env.NEXT_PUBLIC_TELEMETRY_URL || defaultUrl;
9820
- 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);
9821
9124
  (async () => {
9822
9125
  var _a3, _b2, _c2, _d2, _e2;
9823
9126
  try {
@@ -9833,7 +9136,7 @@ ${context}`;
9833
9136
  const tokenCount = Number(((_c2 = finalTrace == null ? void 0 : finalTrace.tokens) == null ? void 0 : _c2.totalTokens) || 0);
9834
9137
  const costEst = Number(((_d2 = finalTrace == null ? void 0 : finalTrace.tokens) == null ? void 0 : _d2.estimatedCostUsd) || 0);
9835
9138
  const latencyDuration = Number(((_e2 = finalTrace == null ? void 0 : finalTrace.latency) == null ? void 0 : _e2.totalMs) || 0);
9836
- console.log(`[Retrivora Pipeline Telemetry] \u{1F4CA} Dispatching RAG telemetry -> Project: "${ns}", Model: "${providerName}/${modelName}", Tokens: ${tokenCount}, Latency: ${latencyDuration}ms`);
9139
+ console.log(`[Retrivora Pipeline Telemetry] \u{1F4CA} Dispatching RAG telemetry -> Project: "${ns}", Tokens: ${tokenCount}, Latency: ${latencyDuration}ms`);
9837
9140
  await fetch(absoluteUrl, {
9838
9141
  method: "POST",
9839
9142
  headers: {
@@ -10437,8 +9740,8 @@ var VectorPlugin = class {
10437
9740
  }
10438
9741
  try {
10439
9742
  return await this.pipeline.getSuggestions(query, namespace);
10440
- } catch (err) {
10441
- throw wrapError(err, "RETRIEVAL_FAILED");
9743
+ } catch (e) {
9744
+ return [];
10442
9745
  }
10443
9746
  }
10444
9747
  };
@@ -11251,15 +10554,14 @@ function getOrCreatePlugin(configOrPlugin) {
11251
10554
  return _g[cacheKey];
11252
10555
  }
11253
10556
  function reportTelemetry(req, plugin, action, status, details, trace) {
11254
- var _a2, _b, _c, _d, _e, _f, _g2, _h;
10557
+ var _a2, _b, _c, _d, _e, _f, _g2;
11255
10558
  try {
11256
10559
  const config = plugin.getConfig();
11257
10560
  const licenseKey = config.licenseKey || process.env.RAG_LICENSE_KEY || process.env.RETRIVORA_LICENSE_KEY || process.env.NEXT_PUBLIC_RETRIVORA_LICENSE_KEY;
11258
10561
  const telemetryConfig = config.telemetry;
11259
- const enabled = (_a2 = telemetryConfig == null ? void 0 : telemetryConfig.enabled) != null ? _a2 : Boolean(licenseKey);
11260
- 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";
11261
- const telemetryUrl = (telemetryConfig == null ? void 0 : telemetryConfig.url) || process.env.TELEMETRY_URL || process.env.NEXT_PUBLIC_TELEMETRY_URL || defaultUrl;
11262
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;
11263
10565
  const userAgent = req.headers.get("user-agent") || `Retrivora-SDK/${SDK_VERSION}`;
11264
10566
  let absoluteUrl = telemetryUrl;
11265
10567
  if (!telemetryUrl.startsWith("http")) {
@@ -11267,11 +10569,11 @@ function reportTelemetry(req, plugin, action, status, details, trace) {
11267
10569
  absoluteUrl = `${proto}://${host}${telemetryUrl}`;
11268
10570
  }
11269
10571
  const projectId = config.projectId || "default";
11270
- 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";
11271
- 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";
11272
- const tokens = Number(((_f = trace == null ? void 0 : trace.tokens) == null ? void 0 : _f.totalTokens) || (trace == null ? void 0 : trace.totalTokens) || 0);
11273
- const costUsd = Number(((_g2 = trace == null ? void 0 : trace.tokens) == null ? void 0 : _g2.estimatedCostUsd) || (trace == null ? void 0 : trace.costUsd) || 0);
11274
- 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);
11275
10577
  const payload = {
11276
10578
  trace,
11277
10579
  licenseKey,
@@ -11291,7 +10593,7 @@ function reportTelemetry(req, plugin, action, status, details, trace) {
11291
10593
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
11292
10594
  details
11293
10595
  };
11294
- console.log(`[Retrivora SDK Telemetry] \u{1F4CA} Dispatching telemetry -> Feature: "${action}", Status: "${status}", Project: "${projectId}", Model: "${provider}/${model}", Latency: ${latencyMs}ms`);
10596
+ console.log(`[Retrivora SDK Telemetry] Dispatching telemetry -> Feature: "${action}", Status: "${status}", Project: "${projectId}", Latency: ${latencyMs}ms`);
11295
10597
  fetch(absoluteUrl, {
11296
10598
  method: "POST",
11297
10599
  headers: {
@@ -11348,7 +10650,7 @@ function createChatHandler(configOrPlugin, options) {
11348
10650
  const plugin = getOrCreatePlugin(configOrPlugin);
11349
10651
  const storage = new DatabaseStorage(plugin.getConfig());
11350
10652
  const onAuthorize = options == null ? void 0 : options.onAuthorize;
11351
- return async function POST(req) {
10653
+ return async function POST(req, context) {
11352
10654
  var _a2, _b, _c, _d;
11353
10655
  const authResult = await checkAuth(req, onAuthorize);
11354
10656
  if (authResult) return authResult;
@@ -11404,7 +10706,7 @@ function createStreamHandler(configOrPlugin, options) {
11404
10706
  const plugin = getOrCreatePlugin(configOrPlugin);
11405
10707
  const storage = new DatabaseStorage(plugin.getConfig());
11406
10708
  const onAuthorize = options == null ? void 0 : options.onAuthorize;
11407
- return async function POST(req) {
10709
+ return async function POST(req, context) {
11408
10710
  var _a2;
11409
10711
  const authResult = await checkAuth(req, onAuthorize);
11410
10712
  if (authResult) return authResult;
@@ -11554,7 +10856,7 @@ function createStreamHandler(configOrPlugin, options) {
11554
10856
  function createIngestHandler(configOrPlugin, options) {
11555
10857
  const plugin = getOrCreatePlugin(configOrPlugin);
11556
10858
  const onAuthorize = options == null ? void 0 : options.onAuthorize;
11557
- return async function POST(req) {
10859
+ return async function POST(req, context) {
11558
10860
  const authResult = await checkAuth(req, onAuthorize);
11559
10861
  if (authResult) return authResult;
11560
10862
  try {
@@ -11598,7 +10900,7 @@ function createHealthHandler(configOrPlugin, options) {
11598
10900
  function createUploadHandler(configOrPlugin, options) {
11599
10901
  const plugin = getOrCreatePlugin(configOrPlugin);
11600
10902
  const onAuthorize = options == null ? void 0 : options.onAuthorize;
11601
- return async function POST(req) {
10903
+ return async function POST(req, context) {
11602
10904
  const authResult = await checkAuth(req, onAuthorize);
11603
10905
  if (authResult) return authResult;
11604
10906
  try {
@@ -11731,8 +11033,8 @@ function createSuggestionsHandler(configOrPlugin, options) {
11731
11033
  query = url.searchParams.get("query") || "";
11732
11034
  namespace = url.searchParams.get("namespace") || void 0;
11733
11035
  }
11734
- if (typeof query !== "string") {
11735
- return NextResponse.json({ error: "query is required" }, { status: 400 });
11036
+ if (!query || typeof query !== "string" || !query.trim()) {
11037
+ return NextResponse.json({ suggestions: [] });
11736
11038
  }
11737
11039
  const suggestions = await plugin.getSuggestions(query, namespace);
11738
11040
  reportTelemetry(req, plugin, "AUTO_SUGGESTIONS", "success", `Fetched ${suggestions.length} suggestions for: ${query.slice(0, 30)}`);