From 5e19d00a800a8b45ab645309f398b516d0632ddc Mon Sep 17 00:00:00 2001 From: Raven Date: Sat, 3 Aug 2024 15:55:48 -0400 Subject: [PATCH] Allow AI to Search Google. --- backend-server/backend-server.js | 42 ++++++++++++++++++++++++++++++++ backend-server/package.json | 1 + 2 files changed, 43 insertions(+) diff --git a/backend-server/backend-server.js b/backend-server/backend-server.js index 2a987b4..46ef39c 100644 --- a/backend-server/backend-server.js +++ b/backend-server/backend-server.js @@ -5,6 +5,8 @@ import cmd from 'cmd-promise'; import cors from 'cors'; import cheerio from 'cheerio'; import llamaTokenizer from 'llama-tokenizer-js'; +import googleIt from 'google-it'; + const prompt = process.env.PROMPT const app = express(); const port = 3000; @@ -421,6 +423,46 @@ app.post('/api/v1/chat', async (req, res) => { await sendRand(errorMessages); } } + + const searchRegex = /\bsearch\s+(.+)\b/i; + const searchMatch = userMessage.match(searchRegex); + + if (searchMatch) { + const searchQuery = searchMatch[1]; + console.log(`${getTimestamp()} [INFO] Detected search query in user message: ${searchQuery}`); + + try { + googleIt({ 'query': searchQuery }).then(results => { + let searchResponse = `Search Query: ${searchQuery}\n`; + searchResponse += `Top Google search results:\n`; + + results.forEach((result, index) => { + searchResponse += `${index + 1}. ${result.title} - ${result.link}\n`; + }); + + const lastMessageIndex = conversationHistory[ip].length - 1; + if (lastMessageIndex >= 0) { + conversationHistory[ip][lastMessageIndex].content += "\n" + searchResponse; + console.log(`${getTimestamp()} [INFO] Processed search query: ${searchQuery}, response: ${searchResponse}`); + } else { + console.error(`${getTimestamp()} [ERROR] Conversation history is unexpectedly empty for: ${ip}`); + } + }).catch(err => { + console.error(`${getTimestamp()} [ERROR] Failed to perform Google search: ${searchQuery}`, err); + return res.status(500).json({ + message: "An error occurred while performing Google search", + error: err.message + }); + }); + } catch (err) { + console.error(`${getTimestamp()} [ERROR] An unexpected error occurred:`, err); + return res.status(500).json({ + message: "An unexpected error occurred", + error: err.message + }); + } + } + // End Plugins --- console.log(`${getTimestamp()} [INFO] Sending request to llama API for response`); diff --git a/backend-server/package.json b/backend-server/package.json index 11da4cd..81c7217 100644 --- a/backend-server/package.json +++ b/backend-server/package.json @@ -16,6 +16,7 @@ "cors": "^2.8.5", "dotenv": "^16.4.5", "express": "^4.19.2", + "google-it": "^1.6.4", "llama-tokenizer-js": "^1.2.2" } }