Aichatbot12321 commited on
Commit
5ac0268
·
verified ·
1 Parent(s): 53da6c5

Update server.js via HF Space Commander

Browse files
Files changed (1) hide show
  1. server.js +96 -93
server.js CHANGED
@@ -5904,106 +5904,109 @@ async function handleDetectToolIntent(req, res) {
5904
  return reply("WEB_SEARCH", "Web Search", sanitizeSearchQueryNo2024(prompt, prompt));
5905
  }
5906
 
5907
- // 2. Single-Call Decision 1 Router: picks tool AND (when AI Reasoning / NORMAL_CHAT) decides none vs web_search vs gemini_4 vs both!
5908
- const compactRouterSys = `You are Decision 1, a fast single-call JSON router.
5909
- 1) Pick ONE tool from: IMAGE_GEN, EDIT_IMAGE, IMG_TO_PDF, PDF_COMPRESS, QR_CODE, FONT_SIZE, TRANSCRIPT, YOUTUBE_VIDEO, WEB_SEARCH, NORMAL_CHAT.
5910
- - IMAGE_GEN: draw/make/create/generate photo, image, map, poster, logo, art (NOT SVG code/diagrams).
5911
- - EDIT_IMAGE: edit attached image (only if hasImage=${hasImage}).
5912
- - IMG_TO_PDF: convert image to PDF (only if hasImage=${hasImage}).
5913
- - PDF_COMPRESS: compress PDF (only if hasPdf=${hasPdf}).
5914
- - QR_CODE: make QR code.
5915
- - FONT_SIZE: change global app font size (NOT specific paragraph font size).
5916
- - TRANSCRIPT: extract YouTube video transcript.
5917
- - YOUTUBE_VIDEO: search/find/watch YouTube videos (set param to exact topic ONLY, without words like "search youtube for").
5918
- - WEB_SEARCH: live/current facts, news, prices, rates, who is, links (only if searchStrategy!=="off"; searchStrategy=${searchStrategy}).
5919
- - NORMAL_CHAT: general Q&A, coding, math, essays, SVG code/diagrams, or styling paragraphs/colors.
5920
-
5921
- 2) ALSO decide in this SAME JSON response for NORMAL_CHAT / WEB_SEARCH:
5922
- - "useWebSearch": true if live internet search is needed (false if searchStrategy==="off" or not needed).
5923
- - "useGemini4": true if SVG code, vector graphics, geometry/science SVG diagram, or complex SVG visual is needed; false otherwise (so the user's chosen model is used).
5924
- - Both can be true ("both"), either one true ("web_search" or "gemini_4"), or both false ("none").
5925
- - "searchQuery": concise English Google search query ONLY if useWebSearch is true (never write 2024 unless user wrote it).
5926
-
5927
- Return ONLY valid JSON: {"tool":"TOOL_NAME","param":"extracted parameter","useWebSearch":false,"useGemini4":false,"searchQuery":""}`;
5928
-
5929
- const compactRouterUser = (histText ? `History:\n${histText.slice(0, 350)}\n` : "") + `Prompt: "${prompt}"`;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5930
 
5931
  let parsed = null;
 
 
 
5932
 
5933
- // Primary: Groq lowest-token output model (llama-3.1-8b-instant -> ~150-250ms)
5934
- if (process.env.GROQ_API_KEY) {
5935
- const groqModels = ["llama-3.1-8b-instant", "llama-3.3-70b-versatile"];
5936
- for (const gModel of groqModels) {
5937
- try {
5938
- const controller = new AbortController();
5939
- const tId = setTimeout(() => controller.abort(), 1800);
5940
- const r = await fetch("https://api.groq.com/openai/v1/chat/completions", {
5941
- method: "POST",
5942
- headers: {
5943
- "Authorization": `Bearer ${process.env.GROQ_API_KEY}`,
5944
- "Content-Type": "application/json"
5945
- },
5946
- body: JSON.stringify({
5947
- model: gModel,
5948
- temperature: 0,
5949
- max_tokens: 110,
5950
- response_format: { type: "json_object" },
5951
- messages: [
5952
- { role: "system", content: compactRouterSys },
5953
- { role: "user", content: compactRouterUser }
5954
- ]
5955
- }),
5956
- signal: controller.signal
5957
- });
5958
- clearTimeout(tId);
5959
- if (!r.ok) continue;
5960
- const d = await r.json();
5961
- const txt = d.choices?.[0]?.message?.content || "";
5962
- if (txt) {
5963
- parsed = JSON.parse(txt);
5964
- if (parsed && parsed.tool) {
5965
- decisionEngine = "groq:" + gModel;
5966
- rawDecisionOutput = txt;
5967
- break;
5968
- }
5969
- }
5970
- } catch (err) {}
5971
- }
5972
- }
5973
 
5974
- // Fallback: Gemini 2.5 Flash direct (if Groq key missing or unreachable)
5975
- if (!parsed) {
5976
- const gemKey = process.env.GEMINI_API_KEY_1 || process.env.GEMINI_API_KEY_2;
5977
- if (gemKey) {
5978
- try {
5979
- const controller = new AbortController();
5980
- const tId = setTimeout(() => controller.abort(), 2200);
5981
- const r = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${gemKey}`, {
5982
- method: "POST",
5983
- headers: { "Content-Type": "application/json" },
5984
- body: JSON.stringify({
5985
- contents: [{ role: "user", parts: [{ text: compactRouterSys + "\n\n" + compactRouterUser }] }],
5986
- generationConfig: { temperature: 0, maxOutputTokens: 110, responseMimeType: "application/json" }
5987
- }),
5988
- signal: controller.signal
5989
- });
5990
- clearTimeout(tId);
5991
- if (r.ok) {
5992
- const d = await r.json();
5993
- const txt = d.candidates?.[0]?.content?.parts?.[0]?.text || "";
5994
- if (txt) {
5995
- parsed = JSON.parse(txt);
5996
- decisionEngine = "gemini:gemini-2.5-flash";
5997
- rawDecisionOutput = txt;
5998
- }
5999
- }
6000
- } catch (err) {}
 
 
 
 
 
 
 
 
 
 
 
 
 
6001
  }
6002
  }
6003
 
6004
  if (!parsed) {
6005
- if (searchStrategy === "always") return reply("WEB_SEARCH", "Web Search", sanitizeSearchQueryNo2024(prompt, prompt));
6006
- return reply("NORMAL_CHAT", "AI Reasoning", prompt);
6007
  }
6008
 
6009
  const normMap = {
@@ -6043,7 +6046,7 @@ Return ONLY valid JSON: {"tool":"TOOL_NAME","param":"extracted parameter","useWe
6043
  aiRoute: decAiRoute,
6044
  searchQuery: decSearchQuery,
6045
  engine: decisionEngine,
6046
- debugInput: compactRouterUser,
6047
  rawOutput: rawDecisionOutput
6048
  }
6049
  );
 
5904
  return reply("WEB_SEARCH", "Web Search", sanitizeSearchQueryNo2024(prompt, prompt));
5905
  }
5906
 
5907
+ // 2. Real Gemini Decisions API (POST /v1beta/decisions, model: "gemini-decision-1")
5908
+ // Evaluates tool selection + web_search (noul) + gemini_4 (noul) in ONE single forward pass (0 output tokens)!
5909
+ const decisionInputText = (histText ? `Recent History:\n${histText.slice(0, 450)}\n---\n` : "")
5910
+ + `Metadata: hasImage=${hasImage}, hasPdf=${hasPdf}, searchStrategy=${searchStrategy}\n`
5911
+ + `User Prompt: ${prompt}`;
5912
+
5913
+ const decisionRequestBody = {
5914
+ model: "gemini-decision-1",
5915
+ input: decisionInputText,
5916
+ questions: {
5917
+ tool: {
5918
+ type: "choice",
5919
+ instructions: "Which single tool should handle this user request?",
5920
+ criteria: {
5921
+ NORMAL_CHAT: "General Q&A, explanations, coding, math, essays, summaries, SVG code/diagrams, live/current web questions, or styling specific paragraphs/colors.",
5922
+ YOUTUBE_VIDEO: "User explicitly wants to search, find, or watch YouTube videos.",
5923
+ IMAGE_GEN: "User wants to draw, make, create, or generate a raster photo, image, wallpaper, poster, logo, or map (NOT SVG code or vector diagrams).",
5924
+ EDIT_IMAGE: "User wants to edit an attached image (ONLY when hasImage=true).",
5925
+ IMG_TO_PDF: "User wants to convert attached image(s) into a PDF (ONLY when hasImage=true).",
5926
+ PDF_COMPRESS: "User wants to compress or reduce the file size of an attached PDF (ONLY when hasPdf=true).",
5927
+ QR_CODE: "User wants to generate a QR code.",
5928
+ FONT_SIZE: "User wants to change the global app/UI font size everywhere (NOT just a specific paragraph).",
5929
+ TRANSCRIPT: "User wants to extract a YouTube video transcript or subtitles."
5930
+ }
5931
+ },
5932
+ use_web_search: {
5933
+ type: "noul",
5934
+ instructions: "Does this request require live web search on the internet?",
5935
+ criteria: {
5936
+ true_description: "Needs live or current internet info, latest news, real-time prices/rates/scores, current officeholders (PM/CM/CEO), recent releases, or websites/URLs (and searchStrategy is not off).",
5937
+ false_description: "Can be answered without web search: general knowledge, coding, math, SVG drawing, greetings, creative writing, or searchStrategy is off."
5938
+ }
5939
+ },
5940
+ use_gemini_4: {
5941
+ type: "noul",
5942
+ instructions: "Should this request be routed to Gemini 4 Hydrogen instead of the default chosen model?",
5943
+ criteria: {
5944
+ true_description: "User asks for SVG code, vector graphics, geometry/math/science SVG diagrams, or drawing a diagram/figure in SVG.",
5945
+ false_description: "Regular chat, normal coding without SVG, general Q&A, or standard tasks that should use the user's selected model."
5946
+ }
5947
+ }
5948
+ }
5949
+ };
5950
 
5951
  let parsed = null;
5952
+ let decisionEngine = "heuristic-fallback";
5953
+ let rawDecisionOutput = "";
5954
+ let rawDecisionInputLog = JSON.stringify(decisionRequestBody, null, 2);
5955
 
5956
+ const decisionKeys = [
5957
+ { id: "API 1", key: process.env.GEMINI_API_KEY_1 },
5958
+ { id: "API 2", key: process.env.GEMINI_API_KEY_2 },
5959
+ { id: "API 3", key: process.env.GEMINI_API_KEY_3 },
5960
+ { id: "API 4", key: process.env.GEMINI_API_KEY_4 },
5961
+ { id: "API 5", key: process.env.GEMINI_API_KEY_5 }
5962
+ ].filter(k => String(k.key || "").trim());
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5963
 
5964
+ for (const dk of decisionKeys) {
5965
+ try {
5966
+ const controller = new AbortController();
5967
+ const tId = setTimeout(() => controller.abort(), 3500);
5968
+ const r = await fetch("https://generativelanguage.googleapis.com/v1beta/decisions", {
5969
+ method: "POST",
5970
+ headers: {
5971
+ "x-goog-api-key": String(dk.key).trim(),
5972
+ "Content-Type": "application/json"
5973
+ },
5974
+ body: JSON.stringify(decisionRequestBody),
5975
+ signal: controller.signal
5976
+ });
5977
+ clearTimeout(tId);
5978
+ const rawText = await r.text();
5979
+ if (!r.ok) {
5980
+ console.log(`⚠️ [DECISION 1] ${dk.id} (gemini-decision-1) failed (${r.status}): ${rawText.slice(0, 220)}`);
5981
+ continue;
5982
+ }
5983
+ const d = JSON.parse(rawText);
5984
+ const ans = d && d.answers ? d.answers : null;
5985
+ if (ans && ans.tool && ans.tool.choice) {
5986
+ const pickedTool = String(ans.tool.choice).toUpperCase();
5987
+ const webProb = Number(ans.use_web_search && ans.use_web_search.noul != null ? ans.use_web_search.noul : 0);
5988
+ const g4Prob = Number(ans.use_gemini_4 && ans.use_gemini_4.noul != null ? ans.use_gemini_4.noul : 0);
5989
+ const wantsWeb = searchStrategy !== "off" && webProb >= 0.5;
5990
+ const wantsG4 = g4Prob >= 0.5;
5991
+ parsed = {
5992
+ tool: (pickedTool === "NORMAL_CHAT" && wantsWeb && !wantsG4) ? "WEB_SEARCH" : pickedTool,
5993
+ param: prompt,
5994
+ useWebSearch: wantsWeb,
5995
+ useGemini4: wantsG4,
5996
+ searchQuery: wantsWeb ? sanitizeSearchQueryNo2024(prompt, prompt) : ""
5997
+ };
5998
+ decisionEngine = `gemini-decision-1 (${dk.id})`;
5999
+ rawDecisionOutput = JSON.stringify(d, null, 2);
6000
+ break;
6001
+ }
6002
+ } catch (err) {
6003
+ console.log(`⚠️ [DECISION 1] ${dk.id} (gemini-decision-1) error: ${err.message}`);
6004
  }
6005
  }
6006
 
6007
  if (!parsed) {
6008
+ if (searchStrategy === "always") return reply("WEB_SEARCH", "Web Search", sanitizeSearchQueryNo2024(prompt, prompt), { engine: "fallback-always-search", debugInput: rawDecisionInputLog });
6009
+ return reply("NORMAL_CHAT", "AI Reasoning", prompt, { engine: "fallback-normal-chat", debugInput: rawDecisionInputLog });
6010
  }
6011
 
6012
  const normMap = {
 
6046
  aiRoute: decAiRoute,
6047
  searchQuery: decSearchQuery,
6048
  engine: decisionEngine,
6049
+ debugInput: rawDecisionInputLog,
6050
  rawOutput: rawDecisionOutput
6051
  }
6052
  );