Aichatbot12321 commited on
Commit
c5ced3c
Β·
verified Β·
1 Parent(s): 8d62efe

Upload server.js

Browse files
Files changed (1) hide show
  1. server.js +355 -195
server.js CHANGED
@@ -534,19 +534,41 @@ async function cleanRedirectUrl(rawUrl) {
534
 
535
 
536
  // =========================================================================
537
- // 🌐 LIVE GOOGLE SEARCH PIPELINE:
538
- // πŸ₯‡ TIER 1: SERPAPI / SERPER GOOGLE SEARCH API (10-12 Results, India gl=in)
539
- // πŸ₯ˆ TIER 2: GEMINI 2.5 FLASH GROUNDING (Fallback 1)
540
- // πŸ₯‰ TIER 3: FIRECRAWL SEARCH API (Fallback 2)
541
- // πŸ… TIER 4: TAVILY SEARCH API (Fallback 3)
542
- // πŸ… TIER 5: HTML SCRAPER (Fallback 4)
 
 
 
 
 
 
 
 
 
 
543
  // =========================================================================
 
 
 
 
 
 
544
  const SERPER_API_KEYS = [
545
  "fed08c19a3c9b7562427c5a6483f27145e61f0ffb2ed16f3689b4f2bf20bd5de",
546
  process.env.SERPER_API_KEY,
547
  process.env.SERPAPI_KEY
548
  ].filter((k, idx, arr) => k && arr.indexOf(k) === idx);
549
 
 
 
 
 
 
 
550
  // Custom URL filter: strictly excludes YouTube and short-video links from web search citations
551
  function isNonYoutubeWebUrl(rawUrl) {
552
  if (!rawUrl || typeof rawUrl !== "string") return false;
@@ -578,7 +600,7 @@ function isNonYoutubeWebUrl(rawUrl) {
578
  }
579
  }
580
 
581
- // IPv4-first HTTPS JSON fetcher (with cfFetch fallback) so SerpApi never hangs on Hugging Face IPv6/TLS!
582
  function fetchSerpJsonIPv4(urlStr, options = {}) {
583
  const method = options.method || "GET";
584
  const headers = Object.assign({
@@ -630,22 +652,68 @@ function fetchSerpJsonIPv4(urlStr, options = {}) {
630
  });
631
  }
632
 
633
- async function performFreeLiveSearch(query, rawUserPrompt, onStatusUpdate) {
634
- query = sanitizeSearchQueryNo2024(query, rawUserPrompt || query);
635
- console.log(`\n🌐 [SEARCH PIPELINE] Initiating live web search for: "${query}"`);
636
- const FIRECRAWL_API_KEY = process.env.FIRECRAWL_API_KEY || "fc-64e57c018ed942c59f5a353ab4b4e665";
 
 
 
 
 
 
 
 
 
 
 
 
 
637
 
638
- let searchResults = [];
639
- let usedEngine = "";
640
- performFreeLiveSearch.lastResults = [];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
641
 
642
- // =========================================================================
643
- // πŸ₯‡ TIER 1: SERPAPI / SERPER GOOGLE SEARCH API (India gl=in, 10-12 Results)
644
- // - Strictly separates 64-char SerpApi keys from 40-char Serper.dev keys (NEVER triggers HTTP 403)
645
- // - Uses fast google_domain=google.co.in&gl=in&hl=en without slow city UULE proxy (NEVER times out)
646
- // =========================================================================
 
 
 
647
  for (const apiKey of SERPER_API_KEYS) {
648
- if (searchResults.length >= 10) break;
649
  const cleanKey = String(apiKey || "").trim();
650
  if (!cleanKey) continue;
651
 
@@ -653,7 +721,7 @@ async function performFreeLiveSearch(query, rawUserPrompt, onStatusUpdate) {
653
 
654
  if (is64CharSerpApiKey) {
655
  try {
656
- console.log(`πŸ” [TIER 1] Querying SerpApi Google Search (India gl=in, IPv4)...`);
657
  const webUrl = `https://serpapi.com/search.json?engine=google&q=${encodeURIComponent(query)}&google_domain=google.co.in&gl=in&hl=en&num=15&api_key=${encodeURIComponent(cleanKey)}`;
658
  const newsUrl = `https://serpapi.com/search.json?engine=google&tbm=nws&q=${encodeURIComponent(query)}&gl=in&hl=en&num=10&api_key=${encodeURIComponent(cleanKey)}`;
659
 
@@ -737,23 +805,17 @@ async function performFreeLiveSearch(query, rawUserPrompt, onStatusUpdate) {
737
  }
738
 
739
  if (collected.length > 0) {
740
- searchResults = collected.slice(0, 12);
741
- usedEngine = "SERPAPI GOOGLE SEARCH (INDIA)";
742
- console.log(`βœ… [TIER 1] SerpApi Google Search retrieved ${searchResults.length} live results.`);
743
- break;
744
- } else {
745
- console.log(`ℹ️ [TIER 1] SerpApi quota/response empty β€” switching seamlessly to Tier 2 Gemini Grounding...`);
746
  }
747
- } catch (e) {
748
- console.log(`ℹ️ [TIER 1] SerpApi fast check skipped β€” switching to Tier 2 Gemini Grounding...`);
749
- }
750
  // NEVER send a 64-character SerpApi key to google.serper.dev/search (prevents HTTP 403!)
751
  continue;
752
  }
753
 
754
  // Only query google.serper.dev/search when the key is a 40-char Serper.dev key
755
  try {
756
- console.log(`πŸ” [TIER 1] Querying Serper.dev Google Search API (gl=in, IPv4)...`);
757
  const serperRes = await fetchSerpJsonIPv4("https://google.serper.dev/search", {
758
  method: "POST",
759
  headers: {
@@ -795,201 +857,299 @@ async function performFreeLiveSearch(query, rawUserPrompt, onStatusUpdate) {
795
  }
796
  }
797
  if (collected.length > 0) {
798
- searchResults = collected.slice(0, 12);
799
- usedEngine = "SERPER GOOGLE SEARCH (INDIA)";
800
- console.log(`βœ… [TIER 1] Serper.dev retrieved ${searchResults.length} live Google results.`);
801
- break;
802
  }
803
  }
804
  } catch (e) {}
805
  }
 
 
806
 
807
- // =========================================================================
808
- // πŸ₯ˆ TIER 2: GEMINI 2.5 FLASH GROUNDING (ONLY IF SERPER FAILS)
809
- // =========================================================================
810
- if (searchResults.length === 0) {
811
- const seenGemKeys = new Set();
812
- const geminiProviders = VISION_PROVIDERS.filter(p => {
813
- if (p.type !== 'gemini' || !p.key || seenGemKeys.has(p.key)) return false;
814
- seenGemKeys.add(p.key);
815
- return true;
816
- });
817
- for (const provider of geminiProviders) {
818
- try {
819
- console.log(`πŸ” [TIER 2] Querying Google Search via Gemini Grounding with ${provider.id}...`);
820
- const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${provider.key}`, {
821
- method: "POST",
822
- headers: { "Content-Type": "application/json" },
823
- body: JSON.stringify({
824
- contents: [{
825
- parts: [{
826
- text: `Search Google (prioritizing India results) for: "${query}". Summarize key facts, official websites, live updates, and numbers. Do NOT cite YouTube links.`
827
- }]
828
- }],
829
- tools: [{ googleSearch: {} }],
830
- safetySettings: [
831
- { category: "HARM_CATEGORY_HARASSMENT", threshold: "BLOCK_NONE" },
832
- { category: "HARM_CATEGORY_HATE_SPEECH", threshold: "BLOCK_NONE" },
833
- { category: "HARM_CATEGORY_SEXUALLY_EXPLICIT", threshold: "BLOCK_NONE" },
834
- { category: "HARM_CATEGORY_DANGEROUS_CONTENT", threshold: "BLOCK_NONE" }
835
- ]
836
- }),
837
- signal: AbortSignal.timeout(12000)
838
- });
839
 
840
- const data = await response.json();
841
- if (!response.ok) throw new Error(data.error?.message || "Gemini Search Rejected");
842
-
843
- const candidate = data.candidates?.[0];
844
- const text = candidate?.content?.parts?.[0]?.text || "";
845
- const chunks = candidate?.groundingMetadata?.groundingChunks || [];
846
-
847
- const resolvedChunkItems = await Promise.all(chunks.slice(0, 12).map(async (c) => {
848
- if (!c.web?.uri) return null;
849
- let realUrl = await cleanRedirectUrl(c.web.uri);
850
- const chunkTitle = c.web?.title || "Google Search Result";
851
- if (/vertexaisearch|googleapis/i.test(realUrl) && chunkTitle && /^[a-z0-9.-]+\.[a-z]{2,}$/i.test(chunkTitle.trim())) {
852
- realUrl = `https://${chunkTitle.trim().replace(/^https?:\/\//i, "")}`;
853
- }
854
- if (realUrl && isNonYoutubeWebUrl(realUrl) && !/vertexaisearch|googleapis/i.test(realUrl)) {
855
- return { title: chunkTitle, url: realUrl, snippet: text.slice(0, 600) };
856
- }
857
- return null;
858
- }));
859
-
860
- const validChunks = resolvedChunkItems.filter(Boolean);
861
- if (validChunks.length > 0) {
862
- searchResults = validChunks;
863
- searchResults[0].snippet = text;
864
- usedEngine = "GEMINI GROUNDING (GOOGLE)";
865
- console.log(`βœ… [TIER 2] Gemini Grounding retrieved ${searchResults.length} live pages.`);
866
- break;
867
- } else if (text) {
868
- searchResults.push({
869
- title: "Google Search Summary",
870
- url: "",
871
- snippet: text
872
- });
873
- usedEngine = "GEMINI GROUNDING (GOOGLE)";
874
- break;
875
  }
876
- } catch (e) {
877
- console.log(`⚠️ [TIER 2] Gemini key ${provider.id} failed: ${e.message}`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
878
  }
 
 
879
  }
880
  }
 
 
881
 
882
- // =========================================================================
883
- // πŸ₯‰ TIER 3: FIRECRAWL SEARCH FALLBACK (ONLY IF SERPER & GEMINI FAIL)
884
- // =========================================================================
885
- if (searchResults.length === 0) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
886
  try {
887
- console.log("πŸ”₯ [TIER 3] Querying Firecrawl API fallback...");
888
- const fcRes = await fetch("https://api.firecrawl.dev/v1/search", {
889
  method: "POST",
890
- headers: { "Authorization": `Bearer ${FIRECRAWL_API_KEY}`, "Content-Type": "application/json" },
891
- body: JSON.stringify({ query: query, limit: 12 }),
892
- signal: AbortSignal.timeout(9000)
 
 
 
 
 
 
 
 
893
  });
894
 
895
- const fcData = await fcRes.json();
896
- const rawResults = fcData.data || fcData.results || [];
897
-
898
- if (fcRes.ok && rawResults.length > 0) {
899
- searchResults = rawResults.map(item => ({
900
- title: item.title || "Web Result",
901
- url: item.url || item.sourceUrl || "",
902
- snippet: (item.markdown || item.description || "").slice(0, 1500)
903
  })).filter(r => r.url && isNonYoutubeWebUrl(r.url)).slice(0, 12);
904
 
905
- if (searchResults.length > 0) {
906
- usedEngine = "FIRECRAWL";
907
- console.log(`βœ… [TIER 3] Firecrawl retrieved ${searchResults.length} verified live pages.`);
908
  }
 
 
909
  }
910
  } catch (e) {
911
- console.log(`⚠️ [TIER 3] Firecrawl search failed: ${e.message}`);
912
  }
913
  }
 
 
914
 
915
- // =========================================================================
916
- // πŸ… TIER 4: TAVILY SEARCH FALLBACK (ONLY IF SERPER, GEMINI & FIRECRAWL FAIL)
917
- // =========================================================================
918
- if (searchResults.length === 0 && TAVILY_KEYS.length > 0) {
919
- const startIndex = tavilyKeyIndex;
920
- tavilyKeyIndex = (tavilyKeyIndex + 1) % TAVILY_KEYS.length;
921
-
922
- const candidateKeys = [];
923
- for (let i = 0; i < TAVILY_KEYS.length; i++) {
924
- const idx = (startIndex + i) % TAVILY_KEYS.length;
925
- candidateKeys.push({ key: TAVILY_KEYS[idx], label: `TAVILY (Key ${idx + 1})` });
 
 
 
 
 
 
926
  }
 
 
 
 
 
 
927
 
928
- for (const target of candidateKeys) {
929
- try {
930
- console.log(`πŸ” [TIER 4] Querying ${target.label}...`);
931
- const tvlyRes = await fetch("https://api.tavily.com/search", {
932
- method: "POST",
933
- headers: {
934
- "Content-Type": "application/json",
935
- "Authorization": `Bearer ${target.key}`
936
- },
937
- body: JSON.stringify({
938
- query: query,
939
- search_depth: "basic",
940
- max_results: 12,
941
- exclude_domains: ["youtube.com", "youtu.be"]
942
- }),
943
- signal: AbortSignal.timeout(8000)
944
- });
945
 
946
- const tvlyData = await tvlyRes.json();
947
- if (tvlyRes.ok && tvlyData.results && tvlyData.results.length > 0) {
948
- searchResults = tvlyData.results.map(item => ({
949
- title: item.title || "Tavily Result",
950
- url: item.url || "",
951
- snippet: item.content || ""
952
- })).filter(r => r.url && isNonYoutubeWebUrl(r.url)).slice(0, 12);
953
-
954
- if (searchResults.length > 0) {
955
- usedEngine = target.label;
956
- console.log(`βœ… [TIER 4] ${target.label} retrieved ${searchResults.length} live pages.`);
957
- break;
958
- }
959
- } else {
960
- throw new Error(tvlyData.detail || "No results returned");
961
- }
962
- } catch (e) {
963
- console.log(`⚠️ [TIER 4] ${target.label} failed: ${e.message}`);
964
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
965
  }
966
  }
967
 
968
- // =========================================================================
969
- // πŸ… TIER 5: HTML FALLBACK SCRAPER (FINAL SAFETY NET)
970
- // =========================================================================
971
- if (searchResults.length === 0) {
 
 
 
 
972
  try {
973
- console.log("πŸ”Ž [TIER 5] Querying HTML fallback scraper...");
974
- const htmlRes = await axios.get(`https://html.duckduckgo.com/html/?q=${encodeURIComponent(query)}`, {
975
- headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)' },
976
- timeout: 6000
977
- });
978
- const matches = [...htmlRes.data.matchAll(/<a class="result__url"[^>]*href="([^"]+)"[^>]*>(.*?)<\/a>[\s\S]*?<a class="result__snippet[^>]*>(.*?)<\/a>/g)];
979
- matches.slice(0, 12).forEach(m => {
980
- let rawUrl = decodeURIComponent(m[1].replace(/.*uddg=/, '').split('&')[0]);
981
- let snippet = m[3].replace(/<[^>]+>/g, '').trim();
982
- if (rawUrl.startsWith('http') && isNonYoutubeWebUrl(rawUrl)) {
983
- searchResults.push({
984
- title: m[2].replace(/<[^>]+>/g, '').trim(),
985
- url: rawUrl,
986
- snippet: snippet
987
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
988
  }
989
- });
990
- if (searchResults.length > 0) usedEngine = "HTML FALLBACK";
991
- } catch (e) {
992
- console.log("⚠️ [TIER 5] HTML fallback failed.");
993
  }
994
  }
995
 
 
534
 
535
 
536
  // =========================================================================
537
+ // 🌐 LIVE WEB SEARCH PIPELINE WITH STICKY 3-CALL FALLBACK LOOP:
538
+ // πŸ₯‡ PROVIDER 1: LANGSEARCH API KEY 1 (sk-b75a0fc3b0ce4c0f9dffc621a3067ec6)
539
+ // πŸ₯ˆ PROVIDER 2: LANGSEARCH API KEY 2 (sk-678f9ae41a304c2d891c8b7aff24f6e3)
540
+ // πŸ₯‰ PROVIDER 3: LANGSEARCH API KEY 3 (sk-a1dc7071a80d4069a6a64368ee32af86)
541
+ // πŸ… PROVIDER 4: SERPAPI / SERPER GOOGLE SEARCH API (India gl=in)
542
+ // πŸ… PROVIDER 5: GEMINI 2.5 FLASH GROUNDING
543
+ // πŸ… PROVIDER 6: FIRECRAWL SEARCH API
544
+ // πŸ… PROVIDER 7: TAVILY SEARCH API
545
+ // πŸ… PROVIDER 8: HTML SCRAPER FALLBACK
546
+ //
547
+ // πŸ”„ STICKY 3-CALL FALLBACK ROTATION:
548
+ // - Starts at Provider 1 (index 0). If it fails, tries Provider 2, then 3, then Serp, Gemini, Firecrawl, Tavily, HTML.
549
+ // - When earlier provider(s) fail/are blocked and a fallback provider (index > 0) succeeds,
550
+ // subsequent new search calls jump directly to that working provider for up to 3 calls (MAX_STICKY_CALLS = 3).
551
+ // - After calling that working fallback provider 3 times on subsequent calls, it automatically resets
552
+ // to Provider 1 (index 0) and loops the cycle (1st -> 2nd -> 3rd -> ... -> sticky 3 times -> 1st).
553
  // =========================================================================
554
+ const LANGSEARCH_API_KEYS = [
555
+ process.env.LANGSEARCH_API_KEY_1 || "sk-b75a0fc3b0ce4c0f9dffc621a3067ec6",
556
+ process.env.LANGSEARCH_API_KEY_2 || "sk-678f9ae41a304c2d891c8b7aff24f6e3",
557
+ process.env.LANGSEARCH_API_KEY_3 || "sk-a1dc7071a80d4069a6a64368ee32af86"
558
+ ].filter((k, idx, arr) => k && arr.indexOf(k) === idx);
559
+
560
  const SERPER_API_KEYS = [
561
  "fed08c19a3c9b7562427c5a6483f27145e61f0ffb2ed16f3689b4f2bf20bd5de",
562
  process.env.SERPER_API_KEY,
563
  process.env.SERPAPI_KEY
564
  ].filter((k, idx, arr) => k && arr.indexOf(k) === idx);
565
 
566
+ const webSearchStickyState = {
567
+ workingIndex: 0,
568
+ stickyCallsUsed: 0,
569
+ maxStickyCalls: 3
570
+ };
571
+
572
  // Custom URL filter: strictly excludes YouTube and short-video links from web search citations
573
  function isNonYoutubeWebUrl(rawUrl) {
574
  if (!rawUrl || typeof rawUrl !== "string") return false;
 
600
  }
601
  }
602
 
603
+ // IPv4-first HTTPS JSON fetcher (with cfFetch fallback) so LangSearch/SerpApi never hang on Hugging Face IPv6/TLS!
604
  function fetchSerpJsonIPv4(urlStr, options = {}) {
605
  const method = options.method || "GET";
606
  const headers = Object.assign({
 
652
  });
653
  }
654
 
655
+ async function queryLangSearchProvider(query, apiKey, keyLabel) {
656
+ console.log(`πŸ” [LANGSEARCH] Querying ${keyLabel} (https://api.langsearch.com/v1/web-search)...`);
657
+ const lsRes = await fetchSerpJsonIPv4("https://api.langsearch.com/v1/web-search", {
658
+ method: "POST",
659
+ headers: {
660
+ "Authorization": `Bearer ${String(apiKey || "").trim()}`,
661
+ "Content-Type": "application/json"
662
+ },
663
+ body: {
664
+ query: query,
665
+ count: 12,
666
+ freshness: "noLimit",
667
+ summary: true,
668
+ excludeDomains: ["youtube.com", "youtu.be"]
669
+ },
670
+ timeoutMs: 9000
671
+ });
672
 
673
+ if (!lsRes.ok || !lsRes.data) {
674
+ const errDetail = (lsRes.data && (lsRes.data.msg || lsRes.data.message || lsRes.data.error)) || `HTTP ${lsRes.status}`;
675
+ throw new Error(`${keyLabel} failed: ${errDetail}`);
676
+ }
677
+ if (typeof lsRes.data.code === "number" && lsRes.data.code !== 200) {
678
+ throw new Error(`${keyLabel} returned code ${lsRes.data.code}: ${lsRes.data.msg || "Rejected"}`);
679
+ }
680
+
681
+ const rawItems =
682
+ lsRes.data?.data?.webPages?.value ||
683
+ lsRes.data?.webPages?.value ||
684
+ (Array.isArray(lsRes.data?.data) ? lsRes.data.data : null) ||
685
+ (Array.isArray(lsRes.data?.results) ? lsRes.data.results : []);
686
+
687
+ if (!Array.isArray(rawItems) || rawItems.length === 0) {
688
+ throw new Error(`${keyLabel} returned 0 results`);
689
+ }
690
+
691
+ const collected = [];
692
+ const seenUrls = new Set();
693
+ for (const item of rawItems) {
694
+ if (!item) continue;
695
+ const url = String(item.url || item.link || "").trim();
696
+ if (!url || !isNonYoutubeWebUrl(url) || seenUrls.has(url)) continue;
697
+ seenUrls.add(url);
698
+ const title = String(item.name || item.title || "LangSearch Result").trim();
699
+ const dateStr = item.datePublished || item.dateLastCrawled || item.date || "";
700
+ const bodyText = String(item.summary || item.snippet || item.text || item.description || "").trim();
701
+ collected.push({
702
+ title,
703
+ url,
704
+ snippet: `${dateStr ? `[${dateStr}] ` : ""}${bodyText}`.slice(0, 1500)
705
+ });
706
+ }
707
 
708
+ if (collected.length === 0) {
709
+ throw new Error(`${keyLabel} had no valid non-YouTube web URLs`);
710
+ }
711
+ console.log(`βœ… [${keyLabel}] Retrieved ${collected.length} live results from LangSearch.`);
712
+ return { results: collected.slice(0, 12), engine: keyLabel };
713
+ }
714
+
715
+ async function querySerpProvider(query) {
716
  for (const apiKey of SERPER_API_KEYS) {
 
717
  const cleanKey = String(apiKey || "").trim();
718
  if (!cleanKey) continue;
719
 
 
721
 
722
  if (is64CharSerpApiKey) {
723
  try {
724
+ console.log(`πŸ” [SERPAPI] Querying SerpApi Google Search (India gl=in, IPv4)...`);
725
  const webUrl = `https://serpapi.com/search.json?engine=google&q=${encodeURIComponent(query)}&google_domain=google.co.in&gl=in&hl=en&num=15&api_key=${encodeURIComponent(cleanKey)}`;
726
  const newsUrl = `https://serpapi.com/search.json?engine=google&tbm=nws&q=${encodeURIComponent(query)}&gl=in&hl=en&num=10&api_key=${encodeURIComponent(cleanKey)}`;
727
 
 
805
  }
806
 
807
  if (collected.length > 0) {
808
+ console.log(`βœ… [SERPAPI] SerpApi Google Search retrieved ${collected.length} live results.`);
809
+ return { results: collected.slice(0, 12), engine: "SERPAPI GOOGLE SEARCH (INDIA)" };
 
 
 
 
810
  }
811
+ } catch (e) {}
 
 
812
  // NEVER send a 64-character SerpApi key to google.serper.dev/search (prevents HTTP 403!)
813
  continue;
814
  }
815
 
816
  // Only query google.serper.dev/search when the key is a 40-char Serper.dev key
817
  try {
818
+ console.log(`πŸ” [SERPER] Querying Serper.dev Google Search API (gl=in, IPv4)...`);
819
  const serperRes = await fetchSerpJsonIPv4("https://google.serper.dev/search", {
820
  method: "POST",
821
  headers: {
 
857
  }
858
  }
859
  if (collected.length > 0) {
860
+ console.log(`βœ… [SERPER] Serper.dev retrieved ${collected.length} live Google results.`);
861
+ return { results: collected.slice(0, 12), engine: "SERPER GOOGLE SEARCH (INDIA)" };
 
 
862
  }
863
  }
864
  } catch (e) {}
865
  }
866
+ throw new Error("SerpApi / Serper returned no results");
867
+ }
868
 
869
+ async function queryGeminiGroundingProvider(query) {
870
+ const seenGemKeys = new Set();
871
+ const geminiProviders = VISION_PROVIDERS.filter(p => {
872
+ if (p.type !== 'gemini' || !p.key || seenGemKeys.has(p.key)) return false;
873
+ seenGemKeys.add(p.key);
874
+ return true;
875
+ });
876
+ for (const provider of geminiProviders) {
877
+ try {
878
+ console.log(`πŸ” [GEMINI GROUNDING] Querying Google Search via Gemini Grounding with ${provider.id}...`);
879
+ const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${provider.key}`, {
880
+ method: "POST",
881
+ headers: { "Content-Type": "application/json" },
882
+ body: JSON.stringify({
883
+ contents: [{
884
+ parts: [{
885
+ text: `Search Google (prioritizing India results) for: "${query}". Summarize key facts, official websites, live updates, and numbers. Do NOT cite YouTube links.`
886
+ }]
887
+ }],
888
+ tools: [{ googleSearch: {} }],
889
+ safetySettings: [
890
+ { category: "HARM_CATEGORY_HARASSMENT", threshold: "BLOCK_NONE" },
891
+ { category: "HARM_CATEGORY_HATE_SPEECH", threshold: "BLOCK_NONE" },
892
+ { category: "HARM_CATEGORY_SEXUALLY_EXPLICIT", threshold: "BLOCK_NONE" },
893
+ { category: "HARM_CATEGORY_DANGEROUS_CONTENT", threshold: "BLOCK_NONE" }
894
+ ]
895
+ }),
896
+ signal: AbortSignal.timeout(12000)
897
+ });
 
 
 
898
 
899
+ const data = await response.json();
900
+ if (!response.ok) throw new Error(data.error?.message || "Gemini Search Rejected");
901
+
902
+ const candidate = data.candidates?.[0];
903
+ const text = candidate?.content?.parts?.[0]?.text || "";
904
+ const chunks = candidate?.groundingMetadata?.groundingChunks || [];
905
+
906
+ const resolvedChunkItems = await Promise.all(chunks.slice(0, 12).map(async (c) => {
907
+ if (!c.web?.uri) return null;
908
+ let realUrl = await cleanRedirectUrl(c.web.uri);
909
+ const chunkTitle = c.web?.title || "Google Search Result";
910
+ if (/vertexaisearch|googleapis/i.test(realUrl) && chunkTitle && /^[a-z0-9.-]+\.[a-z]{2,}$/i.test(chunkTitle.trim())) {
911
+ realUrl = `https://${chunkTitle.trim().replace(/^https?:\/\//i, "")}`;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
912
  }
913
+ if (realUrl && isNonYoutubeWebUrl(realUrl) && !/vertexaisearch|googleapis/i.test(realUrl)) {
914
+ return { title: chunkTitle, url: realUrl, snippet: text.slice(0, 600) };
915
+ }
916
+ return null;
917
+ }));
918
+
919
+ const validChunks = resolvedChunkItems.filter(Boolean);
920
+ if (validChunks.length > 0) {
921
+ validChunks[0].snippet = text;
922
+ console.log(`βœ… [GEMINI GROUNDING] Retrieved ${validChunks.length} live pages.`);
923
+ return { results: validChunks, engine: "GEMINI GROUNDING (GOOGLE)" };
924
+ } else if (text) {
925
+ return {
926
+ results: [{ title: "Google Search Summary", url: "", snippet: text }],
927
+ engine: "GEMINI GROUNDING (GOOGLE)"
928
+ };
929
  }
930
+ } catch (e) {
931
+ console.log(`⚠️ [GEMINI GROUNDING] Key ${provider.id} failed: ${e.message}`);
932
  }
933
  }
934
+ throw new Error("All Gemini Grounding keys failed");
935
+ }
936
 
937
+ async function queryFirecrawlProvider(query, firecrawlApiKey) {
938
+ console.log("πŸ”₯ [FIRECRAWL] Querying Firecrawl API...");
939
+ const fcRes = await fetch("https://api.firecrawl.dev/v1/search", {
940
+ method: "POST",
941
+ headers: { "Authorization": `Bearer ${firecrawlApiKey}`, "Content-Type": "application/json" },
942
+ body: JSON.stringify({ query: query, limit: 12 }),
943
+ signal: AbortSignal.timeout(9000)
944
+ });
945
+
946
+ const fcData = await fcRes.json();
947
+ const rawResults = fcData.data || fcData.results || [];
948
+
949
+ if (fcRes.ok && rawResults.length > 0) {
950
+ const results = rawResults.map(item => ({
951
+ title: item.title || "Web Result",
952
+ url: item.url || item.sourceUrl || "",
953
+ snippet: (item.markdown || item.description || "").slice(0, 1500)
954
+ })).filter(r => r.url && isNonYoutubeWebUrl(r.url)).slice(0, 12);
955
+
956
+ if (results.length > 0) {
957
+ console.log(`βœ… [FIRECRAWL] Retrieved ${results.length} verified live pages.`);
958
+ return { results, engine: "FIRECRAWL" };
959
+ }
960
+ }
961
+ throw new Error("Firecrawl returned no valid results");
962
+ }
963
+
964
+ async function queryTavilyProvider(query) {
965
+ if (!TAVILY_KEYS.length) throw new Error("No Tavily keys configured");
966
+ const startIndex = tavilyKeyIndex;
967
+ tavilyKeyIndex = (tavilyKeyIndex + 1) % TAVILY_KEYS.length;
968
+
969
+ const candidateKeys = [];
970
+ for (let i = 0; i < TAVILY_KEYS.length; i++) {
971
+ const idx = (startIndex + i) % TAVILY_KEYS.length;
972
+ candidateKeys.push({ key: TAVILY_KEYS[idx], label: `TAVILY (Key ${idx + 1})` });
973
+ }
974
+
975
+ for (const target of candidateKeys) {
976
  try {
977
+ console.log(`πŸ” [TAVILY] Querying ${target.label}...`);
978
+ const tvlyRes = await fetch("https://api.tavily.com/search", {
979
  method: "POST",
980
+ headers: {
981
+ "Content-Type": "application/json",
982
+ "Authorization": `Bearer ${target.key}`
983
+ },
984
+ body: JSON.stringify({
985
+ query: query,
986
+ search_depth: "basic",
987
+ max_results: 12,
988
+ exclude_domains: ["youtube.com", "youtu.be"]
989
+ }),
990
+ signal: AbortSignal.timeout(8000)
991
  });
992
 
993
+ const tvlyData = await tvlyRes.json();
994
+ if (tvlyRes.ok && tvlyData.results && tvlyData.results.length > 0) {
995
+ const results = tvlyData.results.map(item => ({
996
+ title: item.title || "Tavily Result",
997
+ url: item.url || "",
998
+ snippet: item.content || ""
 
 
999
  })).filter(r => r.url && isNonYoutubeWebUrl(r.url)).slice(0, 12);
1000
 
1001
+ if (results.length > 0) {
1002
+ console.log(`βœ… [${target.label}] Retrieved ${results.length} live pages.`);
1003
+ return { results, engine: target.label };
1004
  }
1005
+ } else {
1006
+ throw new Error(tvlyData.detail || "No results returned");
1007
  }
1008
  } catch (e) {
1009
+ console.log(`⚠️ [${target.label}] Failed: ${e.message}`);
1010
  }
1011
  }
1012
+ throw new Error("All Tavily keys failed");
1013
+ }
1014
 
1015
+ async function queryHtmlScraperProvider(query) {
1016
+ console.log("πŸ”Ž [HTML FALLBACK] Querying HTML fallback scraper...");
1017
+ const htmlRes = await axios.get(`https://html.duckduckgo.com/html/?q=${encodeURIComponent(query)}`, {
1018
+ headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)' },
1019
+ timeout: 6000
1020
+ });
1021
+ const matches = [...htmlRes.data.matchAll(/<a class="result__url"[^>]*href="([^"]+)"[^>]*>(.*?)<\/a>[\s\S]*?<a class="result__snippet[^>]*>(.*?)<\/a>/g)];
1022
+ const results = [];
1023
+ matches.slice(0, 12).forEach(m => {
1024
+ let rawUrl = decodeURIComponent(m[1].replace(/.*uddg=/, '').split('&')[0]);
1025
+ let snippet = m[3].replace(/<[^>]+>/g, '').trim();
1026
+ if (rawUrl.startsWith('http') && isNonYoutubeWebUrl(rawUrl)) {
1027
+ results.push({
1028
+ title: m[2].replace(/<[^>]+>/g, '').trim(),
1029
+ url: rawUrl,
1030
+ snippet: snippet
1031
+ });
1032
  }
1033
+ });
1034
+ if (results.length > 0) {
1035
+ return { results, engine: "HTML FALLBACK" };
1036
+ }
1037
+ throw new Error("HTML fallback scraper returned no results");
1038
+ }
1039
 
1040
+ async function performFreeLiveSearch(query, rawUserPrompt, onStatusUpdate) {
1041
+ query = sanitizeSearchQueryNo2024(query, rawUserPrompt || query);
1042
+ console.log(`\n🌐 [SEARCH PIPELINE] Initiating live web search for: "${query}"`);
1043
+ const FIRECRAWL_API_KEY = process.env.FIRECRAWL_API_KEY || "fc-64e57c018ed942c59f5a353ab4b4e665";
 
 
 
 
 
 
 
 
 
 
 
 
 
1044
 
1045
+ let searchResults = [];
1046
+ let usedEngine = "";
1047
+ performFreeLiveSearch.lastResults = [];
1048
+
1049
+ // Build the ordered provider chain:
1050
+ // 1. LangSearch Key 1 -> 2. LangSearch Key 2 -> 3. LangSearch Key 3 -> 4. Serp -> 5. Gemini -> 6. Firecrawl -> 7. Tavily -> 8. HTML Scraper
1051
+ const providerChain = [
1052
+ ...LANGSEARCH_API_KEYS.map((key, idx) => ({
1053
+ name: `LANGSEARCH (Key ${idx + 1})`,
1054
+ run: () => queryLangSearchProvider(query, key, `LANGSEARCH (Key ${idx + 1})`)
1055
+ })),
1056
+ {
1057
+ name: "SERPAPI / SERPER GOOGLE SEARCH",
1058
+ run: () => querySerpProvider(query)
1059
+ },
1060
+ {
1061
+ name: "GEMINI GROUNDING (GOOGLE)",
1062
+ run: () => queryGeminiGroundingProvider(query)
1063
+ },
1064
+ {
1065
+ name: "FIRECRAWL",
1066
+ run: () => queryFirecrawlProvider(query, FIRECRAWL_API_KEY)
1067
+ },
1068
+ {
1069
+ name: "TAVILY",
1070
+ run: () => queryTavilyProvider(query)
1071
+ },
1072
+ {
1073
+ name: "HTML FALLBACK",
1074
+ run: () => queryHtmlScraperProvider(query)
1075
+ }
1076
+ ];
1077
+
1078
+ // Determine starting provider index using the sticky 3-call rotation state machine:
1079
+ // - If a fallback provider (workingIndex > 0) succeeded previously because earlier providers were blocked/failed,
1080
+ // use that working provider directly for up to maxStickyCalls (3) new search calls.
1081
+ // - Once it has been called 3 times, reset workingIndex back to 0 (1st provider) to loop the cycle.
1082
+ let startIdx = 0;
1083
+ let isStickyAttempt = false;
1084
+ if (
1085
+ webSearchStickyState.workingIndex > 0 &&
1086
+ webSearchStickyState.workingIndex < providerChain.length
1087
+ ) {
1088
+ if (webSearchStickyState.stickyCallsUsed < webSearchStickyState.maxStickyCalls) {
1089
+ startIdx = webSearchStickyState.workingIndex;
1090
+ isStickyAttempt = true;
1091
+ console.log(
1092
+ `πŸ”„ [STICKY SEARCH ${webSearchStickyState.stickyCallsUsed + 1}/${webSearchStickyState.maxStickyCalls}] ` +
1093
+ `Previous provider(s) failed earlier β€” calling working provider #${startIdx + 1} (${providerChain[startIdx].name}) directly...`
1094
+ );
1095
+ } else {
1096
+ console.log(
1097
+ `πŸ” [STICKY LOOP RESET] Reached ${webSearchStickyState.maxStickyCalls}/${webSearchStickyState.maxStickyCalls} calls on ` +
1098
+ `${providerChain[webSearchStickyState.workingIndex].name}. Resetting to 1st provider (${providerChain[0].name})!`
1099
+ );
1100
+ webSearchStickyState.workingIndex = 0;
1101
+ webSearchStickyState.stickyCallsUsed = 0;
1102
+ startIdx = 0;
1103
  }
1104
  }
1105
 
1106
+ // Order of execution: start at `startIdx`, try through the end of `providerChain`,
1107
+ // and if started at a sticky fallback that itself failed, also wrap around to `0 .. startIdx - 1` as a safety net.
1108
+ const executionOrder = [];
1109
+ for (let i = startIdx; i < providerChain.length; i++) executionOrder.push(i);
1110
+ for (let i = 0; i < startIdx; i++) executionOrder.push(i);
1111
+
1112
+ for (const providerIdx of executionOrder) {
1113
+ const provider = providerChain[providerIdx];
1114
  try {
1115
+ const out = await provider.run();
1116
+ if (out && Array.isArray(out.results) && out.results.length > 0) {
1117
+ searchResults = out.results;
1118
+ usedEngine = out.engine || provider.name;
1119
+ apiUsageStats[`SEARCH: ${usedEngine}`] = (apiUsageStats[`SEARCH: ${usedEngine}`] || 0) + 1;
1120
+
1121
+ if (providerIdx === 0) {
1122
+ // 1st provider succeeded -> keep state at 0
1123
+ webSearchStickyState.workingIndex = 0;
1124
+ webSearchStickyState.stickyCallsUsed = 0;
1125
+ } else if (isStickyAttempt && providerIdx === startIdx) {
1126
+ // Sticky fallback provider succeeded on this new call -> increment sticky call counter (max 3)
1127
+ webSearchStickyState.stickyCallsUsed += 1;
1128
+ console.log(
1129
+ `πŸ“Œ [STICKY SEARCH] ${provider.name} succeeded (${webSearchStickyState.stickyCallsUsed}/${webSearchStickyState.maxStickyCalls} sticky calls used).`
1130
+ );
1131
+ if (webSearchStickyState.stickyCallsUsed >= webSearchStickyState.maxStickyCalls) {
1132
+ console.log(
1133
+ `πŸ” [STICKY LOOP] Completed ${webSearchStickyState.maxStickyCalls} sticky calls on ${provider.name}. ` +
1134
+ `Next search call will loop back to 1st provider (${providerChain[0].name})!`
1135
+ );
1136
+ webSearchStickyState.workingIndex = 0;
1137
+ webSearchStickyState.stickyCallsUsed = 0;
1138
+ }
1139
+ } else {
1140
+ // Earlier provider(s) failed on this call and fallback `providerIdx` (> 0) worked!
1141
+ // Remember `providerIdx` so the next 3 new search calls use it directly before looping back to 1st provider.
1142
+ webSearchStickyState.workingIndex = providerIdx;
1143
+ webSearchStickyState.stickyCallsUsed = 0;
1144
+ console.log(
1145
+ `πŸ“Œ [STICKY SEARCH SET] Provider #${providerIdx + 1} (${provider.name}) succeeded after earlier provider(s) failed. ` +
1146
+ `Will use ${provider.name} directly for the next ${webSearchStickyState.maxStickyCalls} calls before looping back to 1st provider!`
1147
+ );
1148
  }
1149
+ break;
1150
+ }
1151
+ } catch (err) {
1152
+ console.log(`⚠️ [SEARCH FALLBACK] Provider #${providerIdx + 1} (${provider.name}) failed: ${err.message}`);
1153
  }
1154
  }
1155