Spaces:
Running
Running
Update server.js via HF Space Commander
Browse files
server.js
CHANGED
|
@@ -5773,22 +5773,11 @@ async function handleDetectToolIntent(req, res) {
|
|
| 5773 |
const history = Array.isArray(body.history) ? body.history.slice(-6) : [];
|
| 5774 |
if (!prompt) return sendJson(res, 200, { tool: "NORMAL_CHAT", label: "AI Reasoning", param: "", query: "", suggestedTools: [] });
|
| 5775 |
|
| 5776 |
-
const pLow = prompt.toLowerCase();
|
| 5777 |
-
const lastHistItem = history.length > 0 ? history[history.length - 1] : null;
|
| 5778 |
const histText = history.map((h, idx) => {
|
| 5779 |
const isLast = (idx === history.length - 1);
|
| 5780 |
-
const tag = isLast ? "
|
| 5781 |
return `${tag}\nUser: ${String(h.q || h.question || "").slice(0, isLast ? 450 : 220)}\nAI: ${String(h.a || h.answer || "").slice(0, isLast ? 600 : 220)}`;
|
| 5782 |
}).join("\n---\n");
|
| 5783 |
-
const combinedContext = (histText + "\n" + prompt).toLowerCase();
|
| 5784 |
-
|
| 5785 |
-
// Weather & Weather Follow-up Guard: never trigger web search or random tools when asking about weather or a follow-up location to weather!
|
| 5786 |
-
if (isWeatherFollowUpServer(prompt, history, "")) {
|
| 5787 |
-
return sendJson(res, 200, { tool: "NORMAL_CHAT", label: "AI Reasoning", param: prompt, query: prompt, suggestedTools: [] });
|
| 5788 |
-
}
|
| 5789 |
-
|
| 5790 |
-
// Suggested Tools bar is permanently disabled per user request
|
| 5791 |
-
const computeSuggestions = () => [];
|
| 5792 |
|
| 5793 |
const reply = (tool, label, paramVal, routeOpts = {}) => {
|
| 5794 |
let p = paramVal != null ? String(paramVal) : prompt;
|
|
@@ -5811,30 +5800,27 @@ async function handleDetectToolIntent(req, res) {
|
|
| 5811 |
} else if (tool === "YOUTUBE_VIDEO") {
|
| 5812 |
const cleanYt = extractYoutubeSearchQueryServer(p) || extractYoutubeSearchQueryServer(prompt) || p;
|
| 5813 |
p = !/\b2024\b/.test(prompt) ? cleanYt.replace(/\b2024\b/g, "current").trim() : cleanYt.trim();
|
| 5814 |
-
}
|
| 5815 |
-
|
| 5816 |
-
|
| 5817 |
-
|
| 5818 |
-
|
| 5819 |
-
|
| 5820 |
-
|
| 5821 |
-
|
| 5822 |
-
|
| 5823 |
-
|
| 5824 |
-
const
|
| 5825 |
-
|
| 5826 |
-
|
| 5827 |
-
|
| 5828 |
-
|
| 5829 |
-
|
| 5830 |
-
|
| 5831 |
-
|
| 5832 |
-
console.log(`
|
| 5833 |
-
console.log(`
|
| 5834 |
-
|
| 5835 |
-
console.log(`📥 INPUT:\n${decisionDebug.input}`);
|
| 5836 |
-
console.log(`📤 OUTPUT:\n${decisionDebug.output}`);
|
| 5837 |
-
console.log(`=================================================\n`);
|
| 5838 |
return sendJson(res, 200, {
|
| 5839 |
tool,
|
| 5840 |
label,
|
|
@@ -5844,7 +5830,6 @@ async function handleDetectToolIntent(req, res) {
|
|
| 5844 |
useWebSearch,
|
| 5845 |
useGemini4,
|
| 5846 |
searchQuery: searchQueryOut,
|
| 5847 |
-
decisionDebug,
|
| 5848 |
qrText: tool === "QR_CODE" ? p : undefined,
|
| 5849 |
fontSize: tool === "FONT_SIZE" ? p : undefined,
|
| 5850 |
url: tool === "TRANSCRIPT" ? p : undefined,
|
|
@@ -5852,86 +5837,8 @@ async function handleDetectToolIntent(req, res) {
|
|
| 5852 |
});
|
| 5853 |
};
|
| 5854 |
|
| 5855 |
-
//
|
| 5856 |
-
const
|
| 5857 |
-
if (extractedYtUrl && (pLow.includes("transcript") || pLow.includes("subtitle") || pLow.includes("caption") || pLow.includes("extract") || pLow.includes("ट्रांसक्रिप्ट") || /transcript/i.test(histText))) {
|
| 5858 |
-
return reply("TRANSCRIPT", "Creating Transcript", extractedYtUrl);
|
| 5859 |
-
}
|
| 5860 |
-
if (/\b(extract|get|make|create|generate|give)\b[\s\S]{0,30}\b(transcript|subtitles?|captions?)\b|ट्रांसक्रिप्ट/i.test(prompt)) {
|
| 5861 |
-
return reply("TRANSCRIPT", "Creating Transcript", extractedYtUrl || prompt);
|
| 5862 |
-
}
|
| 5863 |
-
if (hasPdf && /\b(compress|reduce|shrink|smaller|size|optimize)\b[\s\S]{0,25}\bpdf\b|\bpdf\b[\s\S]{0,25}\b(compress|reduce|shrink|smaller)\b/i.test(prompt)) {
|
| 5864 |
-
return reply("PDF_COMPRESS", "PDF Compressor", prompt);
|
| 5865 |
-
}
|
| 5866 |
-
if (hasImage && (/\b(image|img|photo|pic|pictures?)\s*(to|into|in)\s*pdf\b|\bconvert\b[\s\S]{0,25}\bpdf\b|\bmake\s+a?\s*pdf\b/i.test(prompt))) {
|
| 5867 |
-
return reply("IMG_TO_PDF", "Image to PDF", prompt);
|
| 5868 |
-
}
|
| 5869 |
-
if (/\b(qr\s*code|make\s+a?\s*qr|generate\s+a?\s*qr|create\s+a?\s*qr|qr\s+for)\b|क्यूआर\s*कोड/i.test(prompt)) {
|
| 5870 |
-
const qrPayload = prompt.replace(/^.*?(?:qr\s*code|qr)\s*(?:for|of|:|-)?\s*/i, "").trim() || prompt;
|
| 5871 |
-
return reply("QR_CODE", "QR Code Maker", qrPayload);
|
| 5872 |
-
}
|
| 5873 |
-
// If an image is attached:
|
| 5874 |
-
// 1) NEVER trigger EDIT_IMAGE for solve/answer/explain/read/translate/question prompts!
|
| 5875 |
-
// 2) Only trigger EDIT_IMAGE if the user explicitly gives a visual photo-editing command.
|
| 5876 |
-
// 3) For all other prompts with an image (e.g. "solve all", "explain this", "what is this"), return NORMAL_CHAT immediately!
|
| 5877 |
-
if (hasImage) {
|
| 5878 |
-
const isStudyOrSolvePrompt = /\b(solve|solve\s+all|answer|explain|read|translate|summarize|summary|calculate|find|what|why|how|who|which|question|questions|mcq|quiz|notes|homework|page|book|chapter|check|hal|batao|samjhao|padho)\b|हल|सॉल्व|बताओ|समझाओ|पढ़ो|प्रश्न|उत्तर/i.test(prompt);
|
| 5879 |
-
const isExplicitPhotoEdit = !isStudyOrSolvePrompt && /\b(edit\s+(?:this\s+|the\s+)?(?:image|photo|picture|pic)|remove\s+(?:the\s+)?background|change\s+(?:the\s+)?background|blur\s+(?:the\s+)?background|make\s+(?:it|this\s+image|this\s+photo)\s+black\s+and\s+white|recolor|colorize|retouch|inpaint)\b/i.test(prompt);
|
| 5880 |
-
if (isExplicitPhotoEdit) {
|
| 5881 |
-
return reply("EDIT_IMAGE", "Editing Image", prompt);
|
| 5882 |
-
}
|
| 5883 |
-
return reply("NORMAL_CHAT", "AI Reasoning", prompt);
|
| 5884 |
-
}
|
| 5885 |
-
|
| 5886 |
-
// Font size: Only trigger global FONT_SIZE tool if user explicitly mentions global/app/ui/overall font size.
|
| 5887 |
-
// Any request to change specific text or paragraph font size goes to NORMAL_CHAT so the AI styles that paragraph/text!
|
| 5888 |
-
const mentionsGlobalUiFont = /\b(global|app|ui|overall|everywhere|entire\s+app)\b[\s\S]{0,25}\b(font\s*size|text\s*size)\b|\b(font\s*size|text\s*size)\b[\s\S]{0,25}\b(global|app|ui|overall|everywhere)\b/i.test(prompt);
|
| 5889 |
-
if (mentionsGlobalUiFont) {
|
| 5890 |
-
const numM = prompt.match(/(\d{2})\s*(?:px)?/);
|
| 5891 |
-
let sz = numM ? numM[1] : (/small|decrease|tiny|छोटा/i.test(prompt) ? "13" : (/large|big|increase|huge|बड़ा/i.test(prompt) ? "18" : "16"));
|
| 5892 |
-
return reply("FONT_SIZE", "Changing Font Size", sz);
|
| 5893 |
-
}
|
| 5894 |
-
if (/\b(font\s*size|text\s*size|paragraph\s*size|\d{2}\s*px)\b|फॉन्ट\s*साइज/i.test(prompt)) {
|
| 5895 |
-
return reply("NORMAL_CHAT", "AI Reasoning", prompt);
|
| 5896 |
-
}
|
| 5897 |
-
|
| 5898 |
-
// Smart YouTube search detection ("search youtube for ...", "find ... on youtube", etc.)
|
| 5899 |
-
const ytSearchTopic = extractYoutubeSearchQueryServer(prompt);
|
| 5900 |
-
if (ytSearchTopic) {
|
| 5901 |
-
return reply("YOUTUBE_VIDEO", "Finding YouTube Video", ytSearchTopic);
|
| 5902 |
-
}
|
| 5903 |
-
|
| 5904 |
-
// SVG / Vector Diagram detection (routes to AI Reasoning + Gemini 4, or Both if live search is also needed)
|
| 5905 |
-
if (isSvgGenerationRequest(prompt, body)) {
|
| 5906 |
-
const alsoNeedsSearch = searchStrategy !== "off" && (searchStrategy === "always" || hasCurrentOrSearchTopic(prompt));
|
| 5907 |
-
return reply("NORMAL_CHAT", "AI Reasoning", prompt, {
|
| 5908 |
-
useGemini4: true,
|
| 5909 |
-
useWebSearch: alsoNeedsSearch,
|
| 5910 |
-
aiRoute: alsoNeedsSearch ? "both" : "gemini_4",
|
| 5911 |
-
searchQuery: alsoNeedsSearch ? sanitizeSearchQueryNo2024(prompt, prompt) : ""
|
| 5912 |
-
});
|
| 5913 |
-
}
|
| 5914 |
-
|
| 5915 |
-
// Broad Image Generation detection: catches "make a india map", "draw a...", "create a photo/image/map/poster/logo...", Hindi/Hinglish equivalents
|
| 5916 |
-
const isNotCodeOrText = !/\b(code|html|css|javascript|python|java|program|essay|paragraph|explain|what\s+is|why\s+is|how\s+to|history\s+of|summary|notes|quiz|mcq)\b/i.test(prompt);
|
| 5917 |
-
const explicitImgGen = /\b(generate|create|make|draw|paint|design|show\s+me|give\s+me|build)\b[\s\S]{0,40}\b(image|picture|photo|pic|art|drawing|sketch|illustration|wallpaper|poster|logo|banner|avatar|icon|map|diagram)\b/i.test(prompt)
|
| 5918 |
-
|| /\b(image|picture|photo|pic|wallpaper|poster|logo|map)\s+(of|for|showing)\s+[a-z0-9]/i.test(prompt)
|
| 5919 |
-
|| /\b(india\s+map|world\s+map|map\s+of\s+[a-z]+)\b/i.test(prompt) && /\b(make|draw|create|generate|show|give)\b|बनाओ|दिखाओ/i.test(prompt)
|
| 5920 |
-
|| /(?:फोटो|तस्वीर|चित्र|इमेज|नक्शा|मैप)\s*(?:बनाओ|बना\s*दो|दिखाओ|जनरेट)/i.test(prompt)
|
| 5921 |
-
|| /\b(?:photo|image|pic|tasveer|naksha|map)\s*(?:banao|bana\s*do|dikhao|generate\s*karo)\b/i.test(prompt);
|
| 5922 |
-
if (explicitImgGen && isNotCodeOrText) {
|
| 5923 |
-
return reply("IMAGE_GEN", "Image Generation", prompt);
|
| 5924 |
-
}
|
| 5925 |
-
|
| 5926 |
-
// Check if prompt has current/real-time/web-search words or if searchStrategy is "always"
|
| 5927 |
-
const isCurrentSearchTopic = searchStrategy !== "off" && hasCurrentOrSearchTopic(prompt);
|
| 5928 |
-
if (isCurrentSearchTopic) {
|
| 5929 |
-
return reply("WEB_SEARCH", "Web Search", sanitizeSearchQueryNo2024(prompt, prompt));
|
| 5930 |
-
}
|
| 5931 |
-
|
| 5932 |
-
// 2. Real Gemini Decisions API (POST /v1beta/decisions, model: "gemini-decision-1")
|
| 5933 |
-
// Evaluates tool selection + web_search (noul) + gemini_4 (noul) in ONE single forward pass (0 output tokens)!
|
| 5934 |
-
const decisionInputText = (histText ? `Recent History:\n${histText.slice(0, 450)}\n---\n` : "")
|
| 5935 |
+ `Metadata: hasImage=${hasImage}, hasPdf=${hasPdf}, searchStrategy=${searchStrategy}\n`
|
| 5936 |
+ `User Prompt: ${prompt}`;
|
| 5937 |
|
|
@@ -5943,7 +5850,7 @@ async function handleDetectToolIntent(req, res) {
|
|
| 5943 |
type: "choice",
|
| 5944 |
instructions: "Which single tool should handle this user request?",
|
| 5945 |
criteria: {
|
| 5946 |
-
NORMAL_CHAT: "General Q&A, explanations, coding, math, essays, summaries, SVG code/diagrams, live/current web questions, or styling specific paragraphs/colors.",
|
| 5947 |
YOUTUBE_VIDEO: "User explicitly wants to search, find, or watch YouTube videos.",
|
| 5948 |
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).",
|
| 5949 |
EDIT_IMAGE: "User wants to edit an attached image (ONLY when hasImage=true).",
|
|
@@ -5959,7 +5866,7 @@ async function handleDetectToolIntent(req, res) {
|
|
| 5959 |
instructions: "Does this request require live web search on the internet?",
|
| 5960 |
criteria: {
|
| 5961 |
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).",
|
| 5962 |
-
false_description: "Can be answered without web search: general knowledge, coding, math, SVG drawing,
|
| 5963 |
}
|
| 5964 |
},
|
| 5965 |
use_gemini_4: {
|
|
@@ -5967,23 +5874,23 @@ async function handleDetectToolIntent(req, res) {
|
|
| 5967 |
instructions: "Should this request be routed to Gemini 4 Hydrogen instead of the default chosen model?",
|
| 5968 |
criteria: {
|
| 5969 |
true_description: "User asks for SVG code, vector graphics, geometry/math/science SVG diagrams, or drawing a diagram/figure in SVG.",
|
| 5970 |
-
false_description: "Regular chat, normal coding without SVG, general Q&A, or standard tasks that should use the user's selected model."
|
| 5971 |
}
|
| 5972 |
}
|
| 5973 |
}
|
| 5974 |
};
|
| 5975 |
|
| 5976 |
let parsed = null;
|
| 5977 |
-
let
|
| 5978 |
-
let
|
| 5979 |
-
let
|
| 5980 |
|
| 5981 |
const decisionKeys = [
|
| 5982 |
-
{
|
| 5983 |
-
{
|
| 5984 |
-
{
|
| 5985 |
-
{
|
| 5986 |
-
{
|
| 5987 |
].filter(k => String(k.key || "").trim());
|
| 5988 |
|
| 5989 |
for (const dk of decisionKeys) {
|
|
@@ -6001,17 +5908,21 @@ async function handleDetectToolIntent(req, res) {
|
|
| 6001 |
});
|
| 6002 |
clearTimeout(tId);
|
| 6003 |
const rawText = await r.text();
|
| 6004 |
-
if (!r.ok)
|
| 6005 |
-
console.log(`⚠️ [DECISION 1] ${dk.id} (gemini-decision-1) failed (${r.status}): ${rawText.slice(0, 220)}`);
|
| 6006 |
-
continue;
|
| 6007 |
-
}
|
| 6008 |
const d = JSON.parse(rawText);
|
| 6009 |
const ans = d && d.answers ? d.answers : null;
|
| 6010 |
if (ans && ans.tool && ans.tool.choice) {
|
| 6011 |
const pickedTool = String(ans.tool.choice).toUpperCase();
|
|
|
|
| 6012 |
const webProb = Number(ans.use_web_search && ans.use_web_search.noul != null ? ans.use_web_search.noul : 0);
|
| 6013 |
const g4Prob = Number(ans.use_gemini_4 && ans.use_gemini_4.noul != null ? ans.use_gemini_4.noul : 0);
|
| 6014 |
-
const
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6015 |
const wantsG4 = g4Prob >= 0.5;
|
| 6016 |
parsed = {
|
| 6017 |
tool: (pickedTool === "NORMAL_CHAT" && wantsWeb && !wantsG4) ? "WEB_SEARCH" : pickedTool,
|
|
@@ -6020,18 +5931,28 @@ async function handleDetectToolIntent(req, res) {
|
|
| 6020 |
useGemini4: wantsG4,
|
| 6021 |
searchQuery: wantsWeb ? sanitizeSearchQueryNo2024(prompt, prompt) : ""
|
| 6022 |
};
|
| 6023 |
-
|
| 6024 |
-
|
| 6025 |
break;
|
| 6026 |
}
|
| 6027 |
-
} catch (err) {
|
| 6028 |
-
console.log(`⚠️ [DECISION 1] ${dk.id} (gemini-decision-1) error: ${err.message}`);
|
| 6029 |
-
}
|
| 6030 |
}
|
| 6031 |
|
| 6032 |
if (!parsed) {
|
| 6033 |
-
|
| 6034 |
-
return reply(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6035 |
}
|
| 6036 |
|
| 6037 |
const normMap = {
|
|
@@ -6055,24 +5976,24 @@ async function handleDetectToolIntent(req, res) {
|
|
| 6055 |
finalTool = "WEB_SEARCH";
|
| 6056 |
}
|
| 6057 |
|
| 6058 |
-
const paramOut = parsed.param || parsed.query || parsed.qrText || parsed.url || parsed.fontSize || prompt;
|
| 6059 |
const isChatOrSearch = (finalTool === "NORMAL_CHAT" || finalTool === "WEB_SEARCH");
|
| 6060 |
const decUseWeb = isChatOrSearch && searchStrategy !== "off" && (finalTool === "WEB_SEARCH" || parsed.useWebSearch === true || searchStrategy === "always");
|
| 6061 |
-
const decUseG4 = isChatOrSearch && (parsed.useGemini4 === true
|
| 6062 |
const decAiRoute = (decUseWeb && decUseG4) ? "both" : (decUseWeb ? "web_search" : (decUseG4 ? "gemini_4" : "none"));
|
| 6063 |
-
const decSearchQuery = decUseWeb ? sanitizeSearchQueryNo2024(parsed.searchQuery ||
|
|
|
|
| 6064 |
return reply(
|
| 6065 |
finalTool,
|
| 6066 |
-
finalTool === "WEB_SEARCH" ? "Web Search" :
|
| 6067 |
-
|
| 6068 |
{
|
| 6069 |
useWebSearch: decUseWeb,
|
| 6070 |
useGemini4: decUseG4,
|
| 6071 |
aiRoute: decAiRoute,
|
| 6072 |
searchQuery: decSearchQuery,
|
| 6073 |
-
|
| 6074 |
-
|
| 6075 |
-
|
| 6076 |
}
|
| 6077 |
);
|
| 6078 |
} catch (e) {
|
|
|
|
| 5773 |
const history = Array.isArray(body.history) ? body.history.slice(-6) : [];
|
| 5774 |
if (!prompt) return sendJson(res, 200, { tool: "NORMAL_CHAT", label: "AI Reasoning", param: "", query: "", suggestedTools: [] });
|
| 5775 |
|
|
|
|
|
|
|
| 5776 |
const histText = history.map((h, idx) => {
|
| 5777 |
const isLast = (idx === history.length - 1);
|
| 5778 |
+
const tag = isLast ? "[IMMEDIATELY PREVIOUS MESSAGE]" : `[Earlier Turn ${idx + 1}]`;
|
| 5779 |
return `${tag}\nUser: ${String(h.q || h.question || "").slice(0, isLast ? 450 : 220)}\nAI: ${String(h.a || h.answer || "").slice(0, isLast ? 600 : 220)}`;
|
| 5780 |
}).join("\n---\n");
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5781 |
|
| 5782 |
const reply = (tool, label, paramVal, routeOpts = {}) => {
|
| 5783 |
let p = paramVal != null ? String(paramVal) : prompt;
|
|
|
|
| 5800 |
} else if (tool === "YOUTUBE_VIDEO") {
|
| 5801 |
const cleanYt = extractYoutubeSearchQueryServer(p) || extractYoutubeSearchQueryServer(prompt) || p;
|
| 5802 |
p = !/\b2024\b/.test(prompt) ? cleanYt.replace(/\b2024\b/g, "current").trim() : cleanYt.trim();
|
| 5803 |
+
} else if (tool === "QR_CODE") {
|
| 5804 |
+
p = prompt.replace(/^.*?(?:qr\s*code|qr)\s*(?:for|of|:|-)?\s*/i, "").trim() || p;
|
| 5805 |
+
} else if (tool === "TRANSCRIPT") {
|
| 5806 |
+
p = extractYoutubeUrlFromTextServer(prompt) || extractYoutubeUrlFromTextServer(histText) || p;
|
| 5807 |
+
} else if (tool === "FONT_SIZE") {
|
| 5808 |
+
const numM = prompt.match(/(\d{2})\s*(?:px)?/);
|
| 5809 |
+
p = numM ? numM[1] : (/small|decrease|tiny|छोटा/i.test(prompt) ? "13" : (/large|big|increase|huge|बड़ा/i.test(prompt) ? "18" : "16"));
|
| 5810 |
+
}
|
| 5811 |
+
|
| 5812 |
+
const decModelUsed = routeOpts.modelUsed || "gemini-decision-1";
|
| 5813 |
+
const decApiNum = routeOpts.apiKeyNum || "N/A";
|
| 5814 |
+
const isAiReasoning = (tool === "NORMAL_CHAT" || tool === "WEB_SEARCH");
|
| 5815 |
+
const routeLabel = aiRoute === "both" ? "WEB SEARCH + GEMINI 4" : (aiRoute === "web_search" ? "WEB SEARCH" : (aiRoute === "gemini_4" ? "GEMINI 4" : "NONE"));
|
| 5816 |
+
const outputLabel = isAiReasoning ? `AI REASONING (${routeLabel})` : tool;
|
| 5817 |
+
const singleLineChances = routeOpts.singleLineChances || "N/A";
|
| 5818 |
+
|
| 5819 |
+
console.log(`INPUT: ${prompt}`);
|
| 5820 |
+
console.log(`MODEL USED: ${decModelUsed} | DECISION API NUMBER: ${decApiNum}`);
|
| 5821 |
+
console.log(`OUTPUT: ${outputLabel}`);
|
| 5822 |
+
console.log(`CONFIDENCE & CHANCES: ${singleLineChances}`);
|
| 5823 |
+
|
|
|
|
|
|
|
|
|
|
| 5824 |
return sendJson(res, 200, {
|
| 5825 |
tool,
|
| 5826 |
label,
|
|
|
|
| 5830 |
useWebSearch,
|
| 5831 |
useGemini4,
|
| 5832 |
searchQuery: searchQueryOut,
|
|
|
|
| 5833 |
qrText: tool === "QR_CODE" ? p : undefined,
|
| 5834 |
fontSize: tool === "FONT_SIZE" ? p : undefined,
|
| 5835 |
url: tool === "TRANSCRIPT" ? p : undefined,
|
|
|
|
| 5837 |
});
|
| 5838 |
};
|
| 5839 |
|
| 5840 |
+
// Always ask Gemini Decision 1 (POST /v1beta/decisions) with FULL context (history + metadata + prompt)
|
| 5841 |
+
const decisionInputText = (histText ? `Recent History:\n${histText.slice(0, 600)}\n---\n` : "")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5842 |
+ `Metadata: hasImage=${hasImage}, hasPdf=${hasPdf}, searchStrategy=${searchStrategy}\n`
|
| 5843 |
+ `User Prompt: ${prompt}`;
|
| 5844 |
|
|
|
|
| 5850 |
type: "choice",
|
| 5851 |
instructions: "Which single tool should handle this user request?",
|
| 5852 |
criteria: {
|
| 5853 |
+
NORMAL_CHAT: "General Q&A, greetings, explanations, coding, math, essays, summaries, weather, SVG code/diagrams, live/current web questions, or styling specific paragraphs/colors.",
|
| 5854 |
YOUTUBE_VIDEO: "User explicitly wants to search, find, or watch YouTube videos.",
|
| 5855 |
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).",
|
| 5856 |
EDIT_IMAGE: "User wants to edit an attached image (ONLY when hasImage=true).",
|
|
|
|
| 5866 |
instructions: "Does this request require live web search on the internet?",
|
| 5867 |
criteria: {
|
| 5868 |
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).",
|
| 5869 |
+
false_description: "Can be answered without web search: greetings, general knowledge, coding, math, SVG drawing, creative writing, weather card, or searchStrategy is off."
|
| 5870 |
}
|
| 5871 |
},
|
| 5872 |
use_gemini_4: {
|
|
|
|
| 5874 |
instructions: "Should this request be routed to Gemini 4 Hydrogen instead of the default chosen model?",
|
| 5875 |
criteria: {
|
| 5876 |
true_description: "User asks for SVG code, vector graphics, geometry/math/science SVG diagrams, or drawing a diagram/figure in SVG.",
|
| 5877 |
+
false_description: "Regular chat, greetings, normal coding without SVG, general Q&A, or standard tasks that should use the user's selected model."
|
| 5878 |
}
|
| 5879 |
}
|
| 5880 |
}
|
| 5881 |
};
|
| 5882 |
|
| 5883 |
let parsed = null;
|
| 5884 |
+
let usedApiNum = "N/A";
|
| 5885 |
+
let usedModelName = "gemini-decision-1";
|
| 5886 |
+
let singleLineChances = "N/A";
|
| 5887 |
|
| 5888 |
const decisionKeys = [
|
| 5889 |
+
{ num: "1", key: process.env.GEMINI_API_KEY_1 },
|
| 5890 |
+
{ num: "2", key: process.env.GEMINI_API_KEY_2 },
|
| 5891 |
+
{ num: "3", key: process.env.GEMINI_API_KEY_3 },
|
| 5892 |
+
{ num: "4", key: process.env.GEMINI_API_KEY_4 },
|
| 5893 |
+
{ num: "5", key: process.env.GEMINI_API_KEY_5 }
|
| 5894 |
].filter(k => String(k.key || "").trim());
|
| 5895 |
|
| 5896 |
for (const dk of decisionKeys) {
|
|
|
|
| 5908 |
});
|
| 5909 |
clearTimeout(tId);
|
| 5910 |
const rawText = await r.text();
|
| 5911 |
+
if (!r.ok) continue;
|
|
|
|
|
|
|
|
|
|
| 5912 |
const d = JSON.parse(rawText);
|
| 5913 |
const ans = d && d.answers ? d.answers : null;
|
| 5914 |
if (ans && ans.tool && ans.tool.choice) {
|
| 5915 |
const pickedTool = String(ans.tool.choice).toUpperCase();
|
| 5916 |
+
const toolConf = Number(ans.tool.confidence || 0);
|
| 5917 |
const webProb = Number(ans.use_web_search && ans.use_web_search.noul != null ? ans.use_web_search.noul : 0);
|
| 5918 |
const g4Prob = Number(ans.use_gemini_4 && ans.use_gemini_4.noul != null ? ans.use_gemini_4.noul : 0);
|
| 5919 |
+
const probsObj = ans.tool.probabilities || {};
|
| 5920 |
+
const probsStr = Object.entries(probsObj)
|
| 5921 |
+
.sort((a, b) => Number(b[1]) - Number(a[1]))
|
| 5922 |
+
.map(([k, v]) => `${k}=${(Number(v) * 100).toFixed(1)}%`)
|
| 5923 |
+
.join(", ");
|
| 5924 |
+
singleLineChances = `conf=${(toolConf * 100).toFixed(1)}% | web=${(webProb * 100).toFixed(1)}% | gemini4=${(g4Prob * 100).toFixed(1)}% | ${probsStr}`;
|
| 5925 |
+
const wantsWeb = searchStrategy !== "off" && (searchStrategy === "always" || webProb >= 0.5);
|
| 5926 |
const wantsG4 = g4Prob >= 0.5;
|
| 5927 |
parsed = {
|
| 5928 |
tool: (pickedTool === "NORMAL_CHAT" && wantsWeb && !wantsG4) ? "WEB_SEARCH" : pickedTool,
|
|
|
|
| 5931 |
useGemini4: wantsG4,
|
| 5932 |
searchQuery: wantsWeb ? sanitizeSearchQueryNo2024(prompt, prompt) : ""
|
| 5933 |
};
|
| 5934 |
+
usedApiNum = dk.num;
|
| 5935 |
+
usedModelName = "gemini-decision-1";
|
| 5936 |
break;
|
| 5937 |
}
|
| 5938 |
+
} catch (err) {}
|
|
|
|
|
|
|
| 5939 |
}
|
| 5940 |
|
| 5941 |
if (!parsed) {
|
| 5942 |
+
const fallbackWeb = searchStrategy === "always";
|
| 5943 |
+
return reply(
|
| 5944 |
+
fallbackWeb ? "WEB_SEARCH" : "NORMAL_CHAT",
|
| 5945 |
+
fallbackWeb ? "Web Search" : "AI Reasoning",
|
| 5946 |
+
fallbackWeb ? sanitizeSearchQueryNo2024(prompt, prompt) : prompt,
|
| 5947 |
+
{
|
| 5948 |
+
useWebSearch: fallbackWeb,
|
| 5949 |
+
useGemini4: false,
|
| 5950 |
+
aiRoute: fallbackWeb ? "web_search" : "none",
|
| 5951 |
+
modelUsed: "fallback",
|
| 5952 |
+
apiKeyNum: "N/A",
|
| 5953 |
+
singleLineChances: "fallback (gemini-decision-1 unreachable)"
|
| 5954 |
+
}
|
| 5955 |
+
);
|
| 5956 |
}
|
| 5957 |
|
| 5958 |
const normMap = {
|
|
|
|
| 5976 |
finalTool = "WEB_SEARCH";
|
| 5977 |
}
|
| 5978 |
|
|
|
|
| 5979 |
const isChatOrSearch = (finalTool === "NORMAL_CHAT" || finalTool === "WEB_SEARCH");
|
| 5980 |
const decUseWeb = isChatOrSearch && searchStrategy !== "off" && (finalTool === "WEB_SEARCH" || parsed.useWebSearch === true || searchStrategy === "always");
|
| 5981 |
+
const decUseG4 = isChatOrSearch && (parsed.useGemini4 === true);
|
| 5982 |
const decAiRoute = (decUseWeb && decUseG4) ? "both" : (decUseWeb ? "web_search" : (decUseG4 ? "gemini_4" : "none"));
|
| 5983 |
+
const decSearchQuery = decUseWeb ? sanitizeSearchQueryNo2024(parsed.searchQuery || prompt, prompt) : "";
|
| 5984 |
+
|
| 5985 |
return reply(
|
| 5986 |
finalTool,
|
| 5987 |
+
finalTool === "WEB_SEARCH" ? "Web Search" : "AI Reasoning",
|
| 5988 |
+
prompt,
|
| 5989 |
{
|
| 5990 |
useWebSearch: decUseWeb,
|
| 5991 |
useGemini4: decUseG4,
|
| 5992 |
aiRoute: decAiRoute,
|
| 5993 |
searchQuery: decSearchQuery,
|
| 5994 |
+
modelUsed: usedModelName,
|
| 5995 |
+
apiKeyNum: usedApiNum,
|
| 5996 |
+
singleLineChances
|
| 5997 |
}
|
| 5998 |
);
|
| 5999 |
} catch (e) {
|