Merge 78cf3f9d5f
into 7ec201d011
This commit is contained in:
commit
a40c7f6aa2
24 changed files with 625 additions and 173 deletions
117
project_structure.txt
Normal file
117
project_structure.txt
Normal file
|
@ -0,0 +1,117 @@
|
||||||
|
.
|
||||||
|
├── CONTRIBUTING.md
|
||||||
|
├── LICENSE
|
||||||
|
├── README.md
|
||||||
|
├── app.dockerfile
|
||||||
|
├── backend.dockerfile
|
||||||
|
├── config.toml
|
||||||
|
├── data
|
||||||
|
├── docker-compose.yaml
|
||||||
|
├── docs
|
||||||
|
│ ├── API
|
||||||
|
│ │ └── SEARCH.md
|
||||||
|
│ ├── architecture
|
||||||
|
│ │ ├── README.md
|
||||||
|
│ │ └── WORKING.md
|
||||||
|
│ └── installation
|
||||||
|
│ ├── NETWORKING.md
|
||||||
|
│ └── UPDATING.md
|
||||||
|
├── drizzle.config.ts
|
||||||
|
├── package.json
|
||||||
|
├── project_structure.txt
|
||||||
|
├── searxng
|
||||||
|
│ ├── limiter.toml
|
||||||
|
│ ├── settings.yml
|
||||||
|
│ └── uwsgi.ini
|
||||||
|
├── src
|
||||||
|
│ ├── app.ts
|
||||||
|
│ ├── chains
|
||||||
|
│ │ ├── imageSearchAgent.ts
|
||||||
|
│ │ ├── suggestionGeneratorAgent.ts
|
||||||
|
│ │ └── videoSearchAgent.ts
|
||||||
|
│ ├── config.ts
|
||||||
|
│ ├── db
|
||||||
|
│ │ ├── index.ts
|
||||||
|
│ │ └── schema.ts
|
||||||
|
│ ├── lib
|
||||||
|
│ │ ├── huggingfaceTransformer.ts
|
||||||
|
│ │ ├── outputParsers
|
||||||
|
│ │ ├── providers
|
||||||
|
│ │ └── searxng.ts
|
||||||
|
│ ├── prompts
|
||||||
|
│ │ ├── academicSearch.ts
|
||||||
|
│ │ ├── index.ts
|
||||||
|
│ │ ├── redditSearch.ts
|
||||||
|
│ │ ├── webSearch.ts
|
||||||
|
│ │ ├── wolframAlpha.ts
|
||||||
|
│ │ ├── writingAssistant.ts
|
||||||
|
│ │ └── youtubeSearch.ts
|
||||||
|
│ ├── routes
|
||||||
|
│ │ ├── chats.ts
|
||||||
|
│ │ ├── config.ts
|
||||||
|
│ │ ├── discover.ts
|
||||||
|
│ │ ├── images.ts
|
||||||
|
│ │ ├── index.ts
|
||||||
|
│ │ ├── models.ts
|
||||||
|
│ │ ├── search.ts
|
||||||
|
│ │ ├── suggestions.ts
|
||||||
|
│ │ ├── uploads.ts
|
||||||
|
│ │ └── videos.ts
|
||||||
|
│ ├── search
|
||||||
|
│ │ └── metaSearchAgent.ts
|
||||||
|
│ ├── utils
|
||||||
|
│ │ ├── computeSimilarity.ts
|
||||||
|
│ │ ├── documents.ts
|
||||||
|
│ │ ├── files.ts
|
||||||
|
│ │ ├── formatHistory.ts
|
||||||
|
│ │ └── logger.ts
|
||||||
|
│ └── websocket
|
||||||
|
│ ├── connectionManager.ts
|
||||||
|
│ ├── index.ts
|
||||||
|
│ ├── messageHandler.ts
|
||||||
|
│ └── websocketServer.ts
|
||||||
|
├── tsconfig.json
|
||||||
|
├── ui
|
||||||
|
│ ├── app
|
||||||
|
│ │ ├── c
|
||||||
|
│ │ ├── discover
|
||||||
|
│ │ ├── favicon.ico
|
||||||
|
│ │ ├── globals.css
|
||||||
|
│ │ ├── layout.tsx
|
||||||
|
│ │ ├── library
|
||||||
|
│ │ └── page.tsx
|
||||||
|
│ ├── components
|
||||||
|
│ │ ├── Chat.tsx
|
||||||
|
│ │ ├── ChatWindow.tsx
|
||||||
|
│ │ ├── DeleteChat.tsx
|
||||||
|
│ │ ├── EmptyChat.tsx
|
||||||
|
│ │ ├── EmptyChatMessageInput.tsx
|
||||||
|
│ │ ├── Layout.tsx
|
||||||
|
│ │ ├── MessageActions
|
||||||
|
│ │ ├── MessageBox.tsx
|
||||||
|
│ │ ├── MessageBoxLoading.tsx
|
||||||
|
│ │ ├── MessageInput.tsx
|
||||||
|
│ │ ├── MessageInputActions
|
||||||
|
│ │ ├── MessageSources.tsx
|
||||||
|
│ │ ├── Navbar.tsx
|
||||||
|
│ │ ├── SearchImages.tsx
|
||||||
|
│ │ ├── SearchVideos.tsx
|
||||||
|
│ │ ├── SettingsDialog.tsx
|
||||||
|
│ │ ├── Sidebar.tsx
|
||||||
|
│ │ └── theme
|
||||||
|
│ ├── lib
|
||||||
|
│ │ ├── actions.ts
|
||||||
|
│ │ └── utils.ts
|
||||||
|
│ ├── next.config.mjs
|
||||||
|
│ ├── package.json
|
||||||
|
│ ├── postcss.config.js
|
||||||
|
│ ├── public
|
||||||
|
│ │ ├── next.svg
|
||||||
|
│ │ └── vercel.svg
|
||||||
|
│ ├── tailwind.config.ts
|
||||||
|
│ ├── tsconfig.json
|
||||||
|
│ └── yarn.lock
|
||||||
|
├── uploads
|
||||||
|
└── yarn.lock
|
||||||
|
|
||||||
|
30 directories, 85 files
|
|
@ -1,14 +0,0 @@
|
||||||
[GENERAL]
|
|
||||||
PORT = 3001 # Port to run the server on
|
|
||||||
SIMILARITY_MEASURE = "cosine" # "cosine" or "dot"
|
|
||||||
KEEP_ALIVE = "5m" # How long to keep Ollama models loaded into memory. (Instead of using -1 use "-1m")
|
|
||||||
|
|
||||||
[API_KEYS]
|
|
||||||
OPENAI = "" # OpenAI API key - sk-1234567890abcdef1234567890abcdef
|
|
||||||
GROQ = "" # Groq API key - gsk_1234567890abcdef1234567890abcdef
|
|
||||||
ANTHROPIC = "" # Anthropic API key - sk-ant-1234567890abcdef1234567890abcdef
|
|
||||||
GEMINI = "" # Gemini API key - sk-1234567890abcdef1234567890abcdef
|
|
||||||
|
|
||||||
[API_ENDPOINTS]
|
|
||||||
SEARXNG = "http://localhost:32768" # SearxNG API URL
|
|
||||||
OLLAMA = "" # Ollama API URL - http://host.docker.internal:11434
|
|
24
src/app.ts
24
src/app.ts
|
@ -15,24 +15,42 @@ const corsOptions = {
|
||||||
origin: '*',
|
origin: '*',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
logger.info(`🚀 Initializing Server Setup...`);
|
||||||
|
logger.info(`🛠 CORS Policy Applied: ${JSON.stringify(corsOptions)}`);
|
||||||
|
|
||||||
app.use(cors(corsOptions));
|
app.use(cors(corsOptions));
|
||||||
app.use(express.json());
|
app.use(express.json());
|
||||||
|
|
||||||
|
// ✅ Middleware to log incoming requests
|
||||||
|
app.use((req, res, next) => {
|
||||||
|
logger.info(`📩 API Request - ${req.method} ${req.originalUrl}`);
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.info(`✅ API Routes Initialized`);
|
||||||
|
|
||||||
app.use('/api', routes);
|
app.use('/api', routes);
|
||||||
app.get('/api', (_, res) => {
|
app.get('/api', (_, res) => {
|
||||||
|
logger.info(`🟢 Health Check Endpoint Hit`);
|
||||||
res.status(200).json({ status: 'ok' });
|
res.status(200).json({ status: 'ok' });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ✅ Log when the server starts listening
|
||||||
server.listen(port, () => {
|
server.listen(port, () => {
|
||||||
logger.info(`Server is running on port ${port}`);
|
logger.info(`✅ Server is running on port ${port}`);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ✅ Log WebSocket Initialization
|
||||||
|
logger.info(`📡 Starting WebSocket Server...`);
|
||||||
startWebSocketServer(server);
|
startWebSocketServer(server);
|
||||||
|
|
||||||
|
// ✅ Better Logging for Uncaught Errors
|
||||||
process.on('uncaughtException', (err, origin) => {
|
process.on('uncaughtException', (err, origin) => {
|
||||||
logger.error(`Uncaught Exception at ${origin}: ${err}`);
|
logger.error(`🔥 Uncaught Exception at ${origin}: ${err.message}`);
|
||||||
|
logger.error(err.stack);
|
||||||
});
|
});
|
||||||
|
|
||||||
process.on('unhandledRejection', (reason, promise) => {
|
process.on('unhandledRejection', (reason, promise) => {
|
||||||
logger.error(`Unhandled Rejection at: ${promise}, reason: ${reason}`);
|
logger.error(`🚨 Unhandled Rejection at: ${promise}`);
|
||||||
|
logger.error(`💥 Reason: ${reason}`);
|
||||||
});
|
});
|
||||||
|
|
|
@ -1,4 +1,5 @@
|
||||||
export const academicSearchRetrieverPrompt = `
|
export const academicSearchRetrieverPrompt = `
|
||||||
|
You are gochat247 - aibot the middle east top AI based search engine develped by GoAi247. Your task is to search the web and provide the most relevant
|
||||||
You will be given a conversation below and a follow up question. You need to rephrase the follow-up question if needed so it is a standalone question that can be used by the LLM to search the web for information.
|
You will be given a conversation below and a follow up question. You need to rephrase the follow-up question if needed so it is a standalone question that can be used by the LLM to search the web for information.
|
||||||
If it is a writing task or a simple hi, hello rather than a question, you need to return \`not_needed\` as the response.
|
If it is a writing task or a simple hi, hello rather than a question, you need to return \`not_needed\` as the response.
|
||||||
|
|
||||||
|
@ -20,7 +21,7 @@ Rephrased question:
|
||||||
`;
|
`;
|
||||||
|
|
||||||
export const academicSearchResponsePrompt = `
|
export const academicSearchResponsePrompt = `
|
||||||
You are Perplexica, an AI model skilled in web search and crafting detailed, engaging, and well-structured answers. You excel at summarizing web pages and extracting relevant information to create professional, blog-style responses.
|
You are gochat247 - aibot, an AI model skilled in web search and crafting detailed, engaging, and well-structured answers. You excel at summarizing web pages and extracting relevant information to create professional, blog-style responses.
|
||||||
|
|
||||||
Your task is to provide answers that are:
|
Your task is to provide answers that are:
|
||||||
- **Informative and relevant**: Thoroughly address the user's query using the given context.
|
- **Informative and relevant**: Thoroughly address the user's query using the given context.
|
||||||
|
|
25
src/prompts/directResponse.ts
Normal file
25
src/prompts/directResponse.ts
Normal file
|
@ -0,0 +1,25 @@
|
||||||
|
export const generateDirectResponsePrompt = (query: string, history: Array<[string, string]>) => {
|
||||||
|
const formattedHistory = history
|
||||||
|
.map(([role, content]) => (role === 'human' ? `User: ${content}` : `AI: ${content}`))
|
||||||
|
.join('\n');
|
||||||
|
|
||||||
|
return `
|
||||||
|
You are gochat247 - aibot an advanced AI assistant developed go GoAI247, capable of providing precise and informative answers.
|
||||||
|
Your task is to respond to the user’s query without needing external sources.
|
||||||
|
|
||||||
|
**Conversation History:**
|
||||||
|
${formattedHistory || "No prior conversation."}
|
||||||
|
|
||||||
|
**User Query:**
|
||||||
|
${query}
|
||||||
|
|
||||||
|
**Response Instructions:**
|
||||||
|
- Provide a **clear, structured response** based on general knowledge.
|
||||||
|
- Keep it **concise, yet informative**.
|
||||||
|
- If complex, **break it down into simpler terms**.
|
||||||
|
- Avoid unnecessary speculation or external references.
|
||||||
|
|
||||||
|
**Your Response:**
|
||||||
|
`;
|
||||||
|
};
|
||||||
|
|
|
@ -20,7 +20,7 @@ Rephrased question:
|
||||||
`;
|
`;
|
||||||
|
|
||||||
export const redditSearchResponsePrompt = `
|
export const redditSearchResponsePrompt = `
|
||||||
You are Perplexica, an AI model skilled in web search and crafting detailed, engaging, and well-structured answers. You excel at summarizing web pages and extracting relevant information to create professional, blog-style responses.
|
You are gochat247 - aibot, an AI powered search engine developed by GoAI247 skilled in web search and crafting detailed, engaging, and well-structured answers. You excel at summarizing web pages and extracting relevant information to create professional, blog-style responses.
|
||||||
|
|
||||||
Your task is to provide answers that are:
|
Your task is to provide answers that are:
|
||||||
- **Informative and relevant**: Thoroughly address the user's query using the given context.
|
- **Informative and relevant**: Thoroughly address the user's query using the given context.
|
||||||
|
|
52
src/prompts/shouldSearch.ts
Normal file
52
src/prompts/shouldSearch.ts
Normal file
|
@ -0,0 +1,52 @@
|
||||||
|
export const shouldPerformSearchPrompt = (query: string, history: Array<[string, string]>) => {
|
||||||
|
const formattedHistory = history
|
||||||
|
.map(([role, content]) => (role === 'human' ? `User: ${content}` : `AI: ${content}`))
|
||||||
|
.join('\n');
|
||||||
|
|
||||||
|
return `
|
||||||
|
You are Gochat247 - AIbot, an AI-powered engine developed by GoAI247. Always remeber that.
|
||||||
|
when you asked "who are you?" or "what can you do?" or "how are you?" or "tell me a joke." or "can you summarize our last chat?" or "what is your name?" or "what is your purpose?" or "what is your age?" ****DONT use search engine.****
|
||||||
|
Your role is to determine whether an external web search is needed to answer a user's query.
|
||||||
|
Analyze the provided chat history and the latest user query before making a decision.
|
||||||
|
|
||||||
|
**Conversation History:**
|
||||||
|
${formattedHistory || "No prior conversation."}
|
||||||
|
|
||||||
|
**User Query:**
|
||||||
|
${query}
|
||||||
|
|
||||||
|
---
|
||||||
|
**Decision Rules:**
|
||||||
|
|
||||||
|
- Respond **"no"** if the query:
|
||||||
|
- Can be answered using **general knowledge** or **your own system knowledge**.
|
||||||
|
- Asks about **you (Gochat247 - AIbot)** (e.g., "Who are you?" / "What can you do?").
|
||||||
|
- Is a **general conversation** (e.g., "How are you?"/"Who are you?" / "Tell me a joke.").
|
||||||
|
- Refers to **previous messages** for context (e.g., "Can you summarize our last chat?").
|
||||||
|
- **Even if it might seem like a searchable query, do not perform a search.**
|
||||||
|
|
||||||
|
- Respond **"yes"** if the query:
|
||||||
|
- Requires **real-time information** (e.g., news, weather, stock prices, sports scores).
|
||||||
|
- Mentions **current events** (e.g., "Who won the latest election?").
|
||||||
|
- Needs **external data sources** (e.g., "Find research papers on AI ethics").
|
||||||
|
- Asks about **product availability or reviews** (e.g., "Is the iPhone 16 Pro out yet?").
|
||||||
|
|
||||||
|
- Your response should be only **"yes"** or **"no"**, without any additional text.
|
||||||
|
|
||||||
|
---
|
||||||
|
**Examples:**
|
||||||
|
✅ **Search Required ("yes")**
|
||||||
|
- "What is the latest stock price of Tesla?" → "ما هو أحدث سعر لسهم تسلا؟"
|
||||||
|
- "Find me recent research papers on quantum computing." → "ابحث لي عن أحدث الأوراق البحثية حول الحوسبة الكمومية."
|
||||||
|
- "What are the top trending news articles today?" → "ما هي أبرز المقالات الإخبارية الرائجة اليوم؟"
|
||||||
|
- "What is the weather forecast for Dubai tomorrow?" → "ما هي توقعات الطقس في دبي غدًا؟"
|
||||||
|
❌ **No Search Needed ("no")**
|
||||||
|
- "Who are you?" → "من أنت؟"
|
||||||
|
- "How are you today?" → "كيف حالك اليوم؟"
|
||||||
|
- "Tell me a fun fact about AI." → "أخبرني بحقيقة ممتعة عن الذكاء الاصطناعي."
|
||||||
|
- "What can you do?" → "ماذا يمكنك أن تفعل؟"
|
||||||
|
- "Explain the concept of machine learning in simple terms." → "اشرح لي مفهوم التعلم الآلي بطريقة بسيطة."
|
||||||
|
- "Can you summarize our last conversation?" → "هل يمكنك تلخيص محادثتنا الأخيرة؟"
|
||||||
|
**Your Response:**
|
||||||
|
`;
|
||||||
|
};
|
4
src/prompts/summarization.ts
Normal file
4
src/prompts/summarization.ts
Normal file
|
@ -0,0 +1,4 @@
|
||||||
|
export const generateSummarizationPrompt = (text: string): string => {
|
||||||
|
return `Summarize the following document:\n\n${text}`;
|
||||||
|
};
|
||||||
|
|
|
@ -3,7 +3,8 @@ You are an AI question rephraser. You will be given a conversation and a follow-
|
||||||
If it is a smple writing task or a greeting (unless the greeting contains a question after it) like Hi, Hello, How are you, etc. than a question then you need to return \`not_needed\` as the response (This is because the LLM won't need to search the web for finding information on this topic).
|
If it is a smple writing task or a greeting (unless the greeting contains a question after it) like Hi, Hello, How are you, etc. than a question then you need to return \`not_needed\` as the response (This is because the LLM won't need to search the web for finding information on this topic).
|
||||||
If the user asks some question from some URL or wants you to summarize a PDF or a webpage (via URL) you need to return the links inside the \`links\` XML block and the question inside the \`question\` XML block. If the user wants to you to summarize the webpage or the PDF you need to return \`summarize\` inside the \`question\` XML block in place of a question and the link to summarize in the \`links\` XML block.
|
If the user asks some question from some URL or wants you to summarize a PDF or a webpage (via URL) you need to return the links inside the \`links\` XML block and the question inside the \`question\` XML block. If the user wants to you to summarize the webpage or the PDF you need to return \`summarize\` inside the \`question\` XML block in place of a question and the link to summarize in the \`links\` XML block.
|
||||||
You must always return the rephrased question inside the \`question\` XML block, if there are no links in the follow-up question then don't insert a \`links\` XML block in your response.
|
You must always return the rephrased question inside the \`question\` XML block, if there are no links in the follow-up question then don't insert a \`links\` XML block in your response.
|
||||||
|
You have to take into consedration you are serving users in UAE. so prices, events, vacations, temperature, weather, etc. should be related to UAE.
|
||||||
|
Answer in the same language of the user input
|
||||||
There are several examples attached for your reference inside the below \`examples\` XML block
|
There are several examples attached for your reference inside the below \`examples\` XML block
|
||||||
|
|
||||||
<examples>
|
<examples>
|
||||||
|
@ -62,7 +63,7 @@ Rephrased question:
|
||||||
`;
|
`;
|
||||||
|
|
||||||
export const webSearchResponsePrompt = `
|
export const webSearchResponsePrompt = `
|
||||||
You are Perplexica, an AI model skilled in web search and crafting detailed, engaging, and well-structured answers. You excel at summarizing web pages and extracting relevant information to create professional, blog-style responses.
|
You are gochat247 - aibot, an AI model skilled in web search and crafting detailed developed by GoAI247, engaging, and well-structured answers. You excel at summarizing web pages and extracting relevant information to create professional, blog-style responses.
|
||||||
|
|
||||||
Your task is to provide answers that are:
|
Your task is to provide answers that are:
|
||||||
- **Informative and relevant**: Thoroughly address the user's query using the given context.
|
- **Informative and relevant**: Thoroughly address the user's query using the given context.
|
||||||
|
|
|
@ -20,7 +20,7 @@ Rephrased question:
|
||||||
`;
|
`;
|
||||||
|
|
||||||
export const wolframAlphaSearchResponsePrompt = `
|
export const wolframAlphaSearchResponsePrompt = `
|
||||||
You are Perplexica, an AI model skilled in web search and crafting detailed, engaging, and well-structured answers. You excel at summarizing web pages and extracting relevant information to create professional, blog-style responses.
|
You are gochat247 - aibot, an AI model developed by GoAI247 skilled in web search and crafting detailed, engaging, and well-structured answers. You excel at summarizing web pages and extracting relevant information to create professional, blog-style responses.
|
||||||
|
|
||||||
Your task is to provide answers that are:
|
Your task is to provide answers that are:
|
||||||
- **Informative and relevant**: Thoroughly address the user's query using the given context.
|
- **Informative and relevant**: Thoroughly address the user's query using the given context.
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
export const writingAssistantPrompt = `
|
export const writingAssistantPrompt = `
|
||||||
You are Perplexica, an AI model who is expert at searching the web and answering user's queries. You are currently set on focus mode 'Writing Assistant', this means you will be helping the user write a response to a given query.
|
You are gochat247 - aibot, an AI model developed by GoAI247 who is expert at searching the web and answering user's queries. You are currently set on focus mode 'Writing Assistant', this means you will be helping the user write a response to a given query.
|
||||||
Since you are a writing assistant, you would not perform web searches. If you think you lack information to answer the query, you can ask the user for more information or suggest them to switch to a different focus mode.
|
Since you are a writing assistant, you would not perform web searches. If you think you lack information to answer the query, you can ask the user for more information or suggest them to switch to a different focus mode.
|
||||||
You will be shared a context that can contain information from files user has uploaded to get answers from. You will have to generate answers upon that.
|
You will be shared a context that can contain information from files user has uploaded to get answers from. You will have to generate answers upon that.
|
||||||
|
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
export const youtubeSearchRetrieverPrompt = `
|
export const youtubeSearchRetrieverPrompt = `
|
||||||
You will be given a conversation below and a follow up question. You need to rephrase the follow-up question if needed so it is a standalone question that can be used by the LLM to search the web for information.
|
You are gochat247 - aibot, an AI model developed by GoAI247.You will be given a conversation below and a follow up question. You need to rephrase the follow-up question if needed so it is a standalone question that can be used by the LLM to search the web for information.
|
||||||
If it is a writing task or a simple hi, hello rather than a question, you need to return \`not_needed\` as the response.
|
If it is a writing task or a simple hi, hello rather than a question, you need to return \`not_needed\` as the response.
|
||||||
|
|
||||||
Example:
|
Example:
|
||||||
|
@ -20,7 +20,7 @@ Rephrased question:
|
||||||
`;
|
`;
|
||||||
|
|
||||||
export const youtubeSearchResponsePrompt = `
|
export const youtubeSearchResponsePrompt = `
|
||||||
You are Perplexica, an AI model skilled in web search and crafting detailed, engaging, and well-structured answers. You excel at summarizing web pages and extracting relevant information to create professional, blog-style responses.
|
You are gochat247 - aibot, an AI model skilled in web search and crafting detailed, engaging, and well-structured answers. You excel at summarizing web pages and extracting relevant information to create professional, blog-style responses.
|
||||||
|
|
||||||
Your task is to provide answers that are:
|
Your task is to provide answers that are:
|
||||||
- **Informative and relevant**: Thoroughly address the user's query using the given context.
|
- **Informative and relevant**: Thoroughly address the user's query using the given context.
|
||||||
|
|
|
@ -6,29 +6,45 @@ const router = express.Router();
|
||||||
|
|
||||||
router.get('/', async (req, res) => {
|
router.get('/', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
|
// Example: Searching UAE-based news sites for "AI" & "Tech"
|
||||||
const data = (
|
const data = (
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
searchSearxng('site:businessinsider.com AI', {
|
// Gulf News
|
||||||
|
searchSearxng('site:gulfnews.com AI', {
|
||||||
engines: ['bing news'],
|
engines: ['bing news'],
|
||||||
pageno: 1,
|
pageno: 1,
|
||||||
}),
|
}),
|
||||||
searchSearxng('site:www.exchangewire.com AI', {
|
searchSearxng('site:gulfnews.com Tech', {
|
||||||
engines: ['bing news'],
|
engines: ['bing news'],
|
||||||
pageno: 1,
|
pageno: 1,
|
||||||
}),
|
}),
|
||||||
searchSearxng('site:yahoo.com AI', {
|
|
||||||
|
// Khaleej Times
|
||||||
|
searchSearxng('site:khaleejtimes.com AI', {
|
||||||
engines: ['bing news'],
|
engines: ['bing news'],
|
||||||
pageno: 1,
|
pageno: 1,
|
||||||
}),
|
}),
|
||||||
searchSearxng('site:businessinsider.com tech', {
|
searchSearxng('site:khaleejtimes.com Tech', {
|
||||||
engines: ['bing news'],
|
engines: ['bing news'],
|
||||||
pageno: 1,
|
pageno: 1,
|
||||||
}),
|
}),
|
||||||
searchSearxng('site:www.exchangewire.com tech', {
|
|
||||||
|
// The National
|
||||||
|
searchSearxng('site:thenationalnews.com AI', {
|
||||||
engines: ['bing news'],
|
engines: ['bing news'],
|
||||||
pageno: 1,
|
pageno: 1,
|
||||||
}),
|
}),
|
||||||
searchSearxng('site:yahoo.com tech', {
|
searchSearxng('site:thenationalnews.com Tech', {
|
||||||
|
engines: ['bing news'],
|
||||||
|
pageno: 1,
|
||||||
|
}),
|
||||||
|
|
||||||
|
// Arabian Business
|
||||||
|
searchSearxng('site:arabianbusiness.com AI', {
|
||||||
|
engines: ['bing news'],
|
||||||
|
pageno: 1,
|
||||||
|
}),
|
||||||
|
searchSearxng('site:arabianbusiness.com Tech', {
|
||||||
engines: ['bing news'],
|
engines: ['bing news'],
|
||||||
pageno: 1,
|
pageno: 1,
|
||||||
}),
|
}),
|
||||||
|
@ -36,6 +52,7 @@ router.get('/', async (req, res) => {
|
||||||
)
|
)
|
||||||
.map((result) => result.results)
|
.map((result) => result.results)
|
||||||
.flat()
|
.flat()
|
||||||
|
// Randomize the order
|
||||||
.sort(() => Math.random() - 0.5);
|
.sort(() => Math.random() - 0.5);
|
||||||
|
|
||||||
return res.json({ blogs: data });
|
return res.json({ blogs: data });
|
||||||
|
|
|
@ -21,4 +21,5 @@ router.use('/search', searchRouter);
|
||||||
router.use('/discover', discoverRouter);
|
router.use('/discover', discoverRouter);
|
||||||
router.use('/uploads', uploadsRouter);
|
router.use('/uploads', uploadsRouter);
|
||||||
|
|
||||||
|
|
||||||
export default router;
|
export default router;
|
||||||
|
|
|
@ -1,3 +1,181 @@
|
||||||
|
// import express from 'express';
|
||||||
|
// import logger from '../utils/logger';
|
||||||
|
// import type { BaseChatModel } from '@langchain/core/language_models/chat_models';
|
||||||
|
// import type { Embeddings } from '@langchain/core/embeddings';
|
||||||
|
// import { ChatOpenAI } from '@langchain/openai';
|
||||||
|
// import {
|
||||||
|
// getAvailableChatModelProviders,
|
||||||
|
// getAvailableEmbeddingModelProviders,
|
||||||
|
// } from '../lib/providers';
|
||||||
|
// import { searchHandlers } from '../websocket/messageHandler';
|
||||||
|
// import { AIMessage, BaseMessage, HumanMessage } from '@langchain/core/messages';
|
||||||
|
// import { MetaSearchAgentType } from '../search/metaSearchAgent';
|
||||||
|
// import { checkIfSearchIsNeeded } from '../utils/checkSearch';
|
||||||
|
// import { generateDirectResponsePrompt } from '../prompts/directResponse'; // ✅ Fixed Import
|
||||||
|
|
||||||
|
// const router = express.Router();
|
||||||
|
|
||||||
|
// interface chatModel {
|
||||||
|
// provider: string;
|
||||||
|
// model: string;
|
||||||
|
// customOpenAIBaseURL?: string;
|
||||||
|
// customOpenAIKey?: string;
|
||||||
|
// }
|
||||||
|
|
||||||
|
// interface embeddingModel {
|
||||||
|
// provider: string;
|
||||||
|
// model: string;
|
||||||
|
// }
|
||||||
|
|
||||||
|
// interface ChatRequestBody {
|
||||||
|
// optimizationMode: 'speed' | 'balanced';
|
||||||
|
// focusMode: string;
|
||||||
|
// chatModel?: chatModel;
|
||||||
|
// embeddingModel?: embeddingModel;
|
||||||
|
// query: string;
|
||||||
|
// history: Array<[string, string]>;
|
||||||
|
// }
|
||||||
|
|
||||||
|
// router.post('/', async (req, res) => {
|
||||||
|
// try {
|
||||||
|
// const body: ChatRequestBody = req.body;
|
||||||
|
|
||||||
|
// logger.info(`📥 - Query: "${body.query}", Focus Mode: "${body.focusMode}"`);
|
||||||
|
|
||||||
|
// if (!body.focusMode || !body.query) {
|
||||||
|
// logger.warn(`⚠️ Missing required fields: Focus Mode or Query`);
|
||||||
|
// return res.status(400).json({ message: 'Missing focus mode or query' });
|
||||||
|
// }
|
||||||
|
|
||||||
|
// body.history = body.history || [];
|
||||||
|
// body.optimizationMode = body.optimizationMode || 'balanced';
|
||||||
|
|
||||||
|
// const history: BaseMessage[] = body.history.map((msg) => {
|
||||||
|
// if (msg[0] === 'human') {
|
||||||
|
// return new HumanMessage({ content: msg[1] });
|
||||||
|
// } else {
|
||||||
|
// return new AIMessage({ content: msg[1] });
|
||||||
|
// }
|
||||||
|
// });
|
||||||
|
|
||||||
|
// const [chatModelProviders, embeddingModelProviders] = await Promise.all([
|
||||||
|
// getAvailableChatModelProviders(),
|
||||||
|
// getAvailableEmbeddingModelProviders(),
|
||||||
|
// ]);
|
||||||
|
|
||||||
|
// const chatModelProvider =
|
||||||
|
// body.chatModel?.provider || Object.keys(chatModelProviders)[0];
|
||||||
|
// const chatModel =
|
||||||
|
// body.chatModel?.model ||
|
||||||
|
// Object.keys(chatModelProviders[chatModelProvider])[0];
|
||||||
|
|
||||||
|
// const embeddingModelProvider =
|
||||||
|
// body.embeddingModel?.provider || Object.keys(embeddingModelProviders)[0];
|
||||||
|
// const embeddingModel =
|
||||||
|
// body.embeddingModel?.model ||
|
||||||
|
// Object.keys(embeddingModelProviders[embeddingModelProvider])[0];
|
||||||
|
|
||||||
|
// let llm: BaseChatModel | undefined;
|
||||||
|
// let embeddings: Embeddings | undefined;
|
||||||
|
|
||||||
|
// if (body.chatModel?.provider === 'custom_openai') {
|
||||||
|
// if (!body.chatModel?.customOpenAIBaseURL || !body.chatModel?.customOpenAIKey) {
|
||||||
|
// logger.warn(`⚠️ Missing custom OpenAI base URL or key`);
|
||||||
|
// return res.status(400).json({ message: 'Missing custom OpenAI base URL or key' });
|
||||||
|
// }
|
||||||
|
|
||||||
|
// llm = new ChatOpenAI({
|
||||||
|
// modelName: body.chatModel.model,
|
||||||
|
// openAIApiKey: body.chatModel.customOpenAIKey,
|
||||||
|
// temperature: 0.7,
|
||||||
|
// configuration: {
|
||||||
|
// baseURL: body.chatModel.customOpenAIBaseURL,
|
||||||
|
// },
|
||||||
|
// }) as unknown as BaseChatModel;
|
||||||
|
// } else if (
|
||||||
|
// chatModelProviders[chatModelProvider] &&
|
||||||
|
// chatModelProviders[chatModelProvider][chatModel]
|
||||||
|
// ) {
|
||||||
|
// llm = chatModelProviders[chatModelProvider][chatModel]
|
||||||
|
// .model as unknown as BaseChatModel | undefined;
|
||||||
|
// }
|
||||||
|
|
||||||
|
// if (
|
||||||
|
// embeddingModelProviders[embeddingModelProvider] &&
|
||||||
|
// embeddingModelProviders[embeddingModelProvider][embeddingModel]
|
||||||
|
// ) {
|
||||||
|
// embeddings = embeddingModelProviders[embeddingModelProvider][embeddingModel]
|
||||||
|
// .model as Embeddings | undefined;
|
||||||
|
// }
|
||||||
|
|
||||||
|
// if (!llm || !embeddings) {
|
||||||
|
// logger.error(`❌ Invalid model selection`);
|
||||||
|
// return res.status(400).json({ message: 'Invalid model selected' });
|
||||||
|
// }
|
||||||
|
|
||||||
|
// // ✅ Determine whether a search is required
|
||||||
|
// logger.info(`🔍 Checking if external search is needed for query: "${body.query}"`);
|
||||||
|
// const shouldSearch = await checkIfSearchIsNeeded(llm, body.query, body.history);
|
||||||
|
// logger.info(`🔍 Search Decision for query "${body.query}": ${shouldSearch ? 'YES' : 'NO'}`);
|
||||||
|
|
||||||
|
// if (!shouldSearch) {
|
||||||
|
// // ✅ AI can answer directly without search
|
||||||
|
// logger.info(`🤖 Generating AI response without external search for: "${body.query}"`);
|
||||||
|
// const directPrompt = generateDirectResponsePrompt(body.query, body.history);
|
||||||
|
// const directResponse = await llm.invoke([new HumanMessage({ content: directPrompt })]);
|
||||||
|
|
||||||
|
// logger.info(`✅ AI Response Generated: "${directResponse.content}"`);
|
||||||
|
// return res.status(200).json({ message: directResponse.content, sources: [] });
|
||||||
|
// }
|
||||||
|
|
||||||
|
// // ✅ Proceed with search if needed
|
||||||
|
// logger.info(`🌐 Performing external search for: "${body.query}"`);
|
||||||
|
// const searchHandler: MetaSearchAgentType = searchHandlers[body.focusMode];
|
||||||
|
|
||||||
|
// if (!searchHandler) {
|
||||||
|
// logger.error(`❌ Invalid focus mode: "${body.focusMode}"`);
|
||||||
|
// return res.status(400).json({ message: 'Invalid focus mode' });
|
||||||
|
// }
|
||||||
|
|
||||||
|
// const emitter = await searchHandler.searchAndAnswer(
|
||||||
|
// body.query,
|
||||||
|
// history,
|
||||||
|
// llm,
|
||||||
|
// embeddings,
|
||||||
|
// body.optimizationMode,
|
||||||
|
// [],
|
||||||
|
// );
|
||||||
|
|
||||||
|
// let message = '';
|
||||||
|
// let sources = [];
|
||||||
|
|
||||||
|
// emitter.on('data', (data) => {
|
||||||
|
// const parsedData = JSON.parse(data);
|
||||||
|
// if (parsedData.type === 'response') {
|
||||||
|
// message += parsedData.data;
|
||||||
|
// } else if (parsedData.type === 'sources') {
|
||||||
|
// sources = parsedData.data;
|
||||||
|
// }
|
||||||
|
// });
|
||||||
|
|
||||||
|
// emitter.on('end', () => {
|
||||||
|
// logger.info(`✅ Search Completed: Message: "${message}", Sources: ${JSON.stringify(sources)}`);
|
||||||
|
// res.status(200).json({ message, sources });
|
||||||
|
// });
|
||||||
|
|
||||||
|
// emitter.on('error', (data) => {
|
||||||
|
// const parsedData = JSON.parse(data);
|
||||||
|
// logger.error(`❌ Error in search processing: ${parsedData.data}`);
|
||||||
|
// res.status(500).json({ message: parsedData.data });
|
||||||
|
// });
|
||||||
|
|
||||||
|
// } catch (err: any) {
|
||||||
|
// logger.error(`❌ Error in processing request: ${err.message}`);
|
||||||
|
// res.status(500).json({ message: 'An error has occurred.' });
|
||||||
|
// }
|
||||||
|
// });
|
||||||
|
|
||||||
|
// export default router;
|
||||||
import express from 'express';
|
import express from 'express';
|
||||||
import logger from '../utils/logger';
|
import logger from '../utils/logger';
|
||||||
import type { BaseChatModel } from '@langchain/core/language_models/chat_models';
|
import type { BaseChatModel } from '@langchain/core/language_models/chat_models';
|
||||||
|
|
|
@ -25,6 +25,7 @@ import formatChatHistoryAsString from '../utils/formatHistory';
|
||||||
import eventEmitter from 'events';
|
import eventEmitter from 'events';
|
||||||
import { StreamEvent } from '@langchain/core/tracers/log_stream';
|
import { StreamEvent } from '@langchain/core/tracers/log_stream';
|
||||||
import { IterableReadableStream } from '@langchain/core/utils/stream';
|
import { IterableReadableStream } from '@langchain/core/utils/stream';
|
||||||
|
import logger from '../utils/logger'; // Winston logger
|
||||||
|
|
||||||
export interface MetaSearchAgentType {
|
export interface MetaSearchAgentType {
|
||||||
searchAndAnswer: (
|
searchAndAnswer: (
|
||||||
|
@ -36,7 +37,7 @@ export interface MetaSearchAgentType {
|
||||||
fileIds: string[],
|
fileIds: string[],
|
||||||
) => Promise<eventEmitter>;
|
) => Promise<eventEmitter>;
|
||||||
}
|
}
|
||||||
|
// twst
|
||||||
interface Config {
|
interface Config {
|
||||||
searchWeb: boolean;
|
searchWeb: boolean;
|
||||||
rerank: boolean;
|
rerank: boolean;
|
||||||
|
@ -58,20 +59,24 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||||
|
|
||||||
constructor(config: Config) {
|
constructor(config: Config) {
|
||||||
this.config = config;
|
this.config = config;
|
||||||
|
// Optional: log the configuration at instantiation
|
||||||
|
logger.info(`MetaSearchAgent created with config: ${JSON.stringify(config)}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async createSearchRetrieverChain(llm: BaseChatModel) {
|
private async createSearchRetrieverChain(llm: BaseChatModel) {
|
||||||
(llm as unknown as ChatOpenAI).temperature = 0;
|
(llm as unknown as ChatOpenAI).temperature = 0;
|
||||||
|
logger.info('createSearchRetrieverChain: LLM temperature set to 0');
|
||||||
|
|
||||||
return RunnableSequence.from([
|
return RunnableSequence.from([
|
||||||
PromptTemplate.fromTemplate(this.config.queryGeneratorPrompt),
|
PromptTemplate.fromTemplate(this.config.queryGeneratorPrompt),
|
||||||
llm,
|
llm,
|
||||||
this.strParser,
|
this.strParser,
|
||||||
RunnableLambda.from(async (input: string) => {
|
RunnableLambda.from(async (input: string) => {
|
||||||
|
logger.info(`Parsed query: ${input}`);
|
||||||
|
|
||||||
const linksOutputParser = new LineListOutputParser({
|
const linksOutputParser = new LineListOutputParser({
|
||||||
key: 'links',
|
key: 'links',
|
||||||
});
|
});
|
||||||
|
|
||||||
const questionOutputParser = new LineOutputParser({
|
const questionOutputParser = new LineOutputParser({
|
||||||
key: 'question',
|
key: 'question',
|
||||||
});
|
});
|
||||||
|
@ -81,21 +86,25 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||||
? await questionOutputParser.parse(input)
|
? await questionOutputParser.parse(input)
|
||||||
: input;
|
: input;
|
||||||
|
|
||||||
|
logger.info(`Links found: ${JSON.stringify(links, null, 2)}`);
|
||||||
|
logger.info(`Question parsed: ${question}`);
|
||||||
|
|
||||||
if (question === 'not_needed') {
|
if (question === 'not_needed') {
|
||||||
|
logger.info('No question needed ("not_needed"), returning empty docs.');
|
||||||
return { query: '', docs: [] };
|
return { query: '', docs: [] };
|
||||||
}
|
}
|
||||||
|
|
||||||
if (links.length > 0) {
|
if (links.length > 0) {
|
||||||
|
logger.info('Handling user-provided links...');
|
||||||
if (question.length === 0) {
|
if (question.length === 0) {
|
||||||
question = 'summarize';
|
question = 'summarize';
|
||||||
}
|
}
|
||||||
|
|
||||||
let docs = [];
|
let docs: Document[] = [];
|
||||||
|
|
||||||
const linkDocs = await getDocumentsFromLinks({ links });
|
const linkDocs = await getDocumentsFromLinks({ links });
|
||||||
|
logger.info(`Fetched ${linkDocs.length} documents from user links.`);
|
||||||
|
|
||||||
const docGroups: Document[] = [];
|
const docGroups: Document[] = [];
|
||||||
|
|
||||||
linkDocs.map((doc) => {
|
linkDocs.map((doc) => {
|
||||||
const URLDocExists = docGroups.find(
|
const URLDocExists = docGroups.find(
|
||||||
(d) =>
|
(d) =>
|
||||||
|
@ -129,64 +138,7 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
docGroups.map(async (doc) => {
|
docGroups.map(async (doc) => {
|
||||||
const res = await llm.invoke(`
|
const res = await llm.invoke(`
|
||||||
You are a web search summarizer, tasked with summarizing a piece of text retrieved from a web search. Your job is to summarize the
|
... // Summarizer prompt ...
|
||||||
text into a detailed, 2-4 paragraph explanation that captures the main ideas and provides a comprehensive answer to the query.
|
|
||||||
If the query is \"summarize\", you should provide a detailed summary of the text. If the query is a specific question, you should answer it in the summary.
|
|
||||||
|
|
||||||
- **Journalistic tone**: The summary should sound professional and journalistic, not too casual or vague.
|
|
||||||
- **Thorough and detailed**: Ensure that every key point from the text is captured and that the summary directly answers the query.
|
|
||||||
- **Not too lengthy, but detailed**: The summary should be informative but not excessively long. Focus on providing detailed information in a concise format.
|
|
||||||
|
|
||||||
The text will be shared inside the \`text\` XML tag, and the query inside the \`query\` XML tag.
|
|
||||||
|
|
||||||
<example>
|
|
||||||
1. \`<text>
|
|
||||||
Docker is a set of platform-as-a-service products that use OS-level virtualization to deliver software in packages called containers.
|
|
||||||
It was first released in 2013 and is developed by Docker, Inc. Docker is designed to make it easier to create, deploy, and run applications
|
|
||||||
by using containers.
|
|
||||||
</text>
|
|
||||||
|
|
||||||
<query>
|
|
||||||
What is Docker and how does it work?
|
|
||||||
</query>
|
|
||||||
|
|
||||||
Response:
|
|
||||||
Docker is a revolutionary platform-as-a-service product developed by Docker, Inc., that uses container technology to make application
|
|
||||||
deployment more efficient. It allows developers to package their software with all necessary dependencies, making it easier to run in
|
|
||||||
any environment. Released in 2013, Docker has transformed the way applications are built, deployed, and managed.
|
|
||||||
\`
|
|
||||||
2. \`<text>
|
|
||||||
The theory of relativity, or simply relativity, encompasses two interrelated theories of Albert Einstein: special relativity and general
|
|
||||||
relativity. However, the word "relativity" is sometimes used in reference to Galilean invariance. The term "theory of relativity" was based
|
|
||||||
on the expression "relative theory" used by Max Planck in 1906. The theory of relativity usually encompasses two interrelated theories by
|
|
||||||
Albert Einstein: special relativity and general relativity. Special relativity applies to all physical phenomena in the absence of gravity.
|
|
||||||
General relativity explains the law of gravitation and its relation to other forces of nature. It applies to the cosmological and astrophysical
|
|
||||||
realm, including astronomy.
|
|
||||||
</text>
|
|
||||||
|
|
||||||
<query>
|
|
||||||
summarize
|
|
||||||
</query>
|
|
||||||
|
|
||||||
Response:
|
|
||||||
The theory of relativity, developed by Albert Einstein, encompasses two main theories: special relativity and general relativity. Special
|
|
||||||
relativity applies to all physical phenomena in the absence of gravity, while general relativity explains the law of gravitation and its
|
|
||||||
relation to other forces of nature. The theory of relativity is based on the concept of "relative theory," as introduced by Max Planck in
|
|
||||||
1906. It is a fundamental theory in physics that has revolutionized our understanding of the universe.
|
|
||||||
\`
|
|
||||||
</example>
|
|
||||||
|
|
||||||
Everything below is the actual data you will be working with. Good luck!
|
|
||||||
|
|
||||||
<query>
|
|
||||||
${question}
|
|
||||||
</query>
|
|
||||||
|
|
||||||
<text>
|
|
||||||
${doc.pageContent}
|
|
||||||
</text>
|
|
||||||
|
|
||||||
Make sure to answer the query in the summary.
|
|
||||||
`);
|
`);
|
||||||
|
|
||||||
const document = new Document({
|
const document = new Document({
|
||||||
|
@ -200,13 +152,16 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||||
docs.push(document);
|
docs.push(document);
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
logger.info('Docs after summarizing user-provided links: ', docs);
|
||||||
|
|
||||||
return { query: question, docs: docs };
|
return { query: question, docs };
|
||||||
} else {
|
} else {
|
||||||
|
logger.info(`No links specified, searching via Searxng on query: "${question}"`);
|
||||||
const res = await searchSearxng(question, {
|
const res = await searchSearxng(question, {
|
||||||
language: 'en',
|
language: 'en',
|
||||||
engines: this.config.activeEngines,
|
engines: this.config.activeEngines,
|
||||||
});
|
});
|
||||||
|
logger.info(`Searxng returned ${res.results.length} results.`);
|
||||||
|
|
||||||
const documents = res.results.map(
|
const documents = res.results.map(
|
||||||
(result) =>
|
(result) =>
|
||||||
|
@ -215,7 +170,7 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||||
result.content ||
|
result.content ||
|
||||||
(this.config.activeEngines.includes('youtube')
|
(this.config.activeEngines.includes('youtube')
|
||||||
? result.title
|
? result.title
|
||||||
: '') /* Todo: Implement transcript grabbing using Youtubei (source: https://www.npmjs.com/package/youtubei) */,
|
: ''),
|
||||||
metadata: {
|
metadata: {
|
||||||
title: result.title,
|
title: result.title,
|
||||||
url: result.url,
|
url: result.url,
|
||||||
|
@ -236,15 +191,15 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||||
embeddings: Embeddings,
|
embeddings: Embeddings,
|
||||||
optimizationMode: 'speed' | 'balanced' | 'quality',
|
optimizationMode: 'speed' | 'balanced' | 'quality',
|
||||||
) {
|
) {
|
||||||
|
logger.info(`Creating answering chain. Optimization mode: ${optimizationMode}`);
|
||||||
return RunnableSequence.from([
|
return RunnableSequence.from([
|
||||||
RunnableMap.from({
|
RunnableMap.from({
|
||||||
query: (input: BasicChainInput) => input.query,
|
query: (input: BasicChainInput) => input.query,
|
||||||
chat_history: (input: BasicChainInput) => input.chat_history,
|
chat_history: (input: BasicChainInput) => input.chat_history,
|
||||||
date: () => new Date().toISOString(),
|
date: () => new Date().toISOString(),
|
||||||
context: RunnableLambda.from(async (input: BasicChainInput) => {
|
context: RunnableLambda.from(async (input: BasicChainInput) => {
|
||||||
const processedHistory = formatChatHistoryAsString(
|
logger.info('Retrieving final source documents...');
|
||||||
input.chat_history,
|
const processedHistory = formatChatHistoryAsString(input.chat_history);
|
||||||
);
|
|
||||||
|
|
||||||
let docs: Document[] | null = null;
|
let docs: Document[] | null = null;
|
||||||
let query = input.query;
|
let query = input.query;
|
||||||
|
@ -260,6 +215,7 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||||
|
|
||||||
query = searchRetrieverResult.query;
|
query = searchRetrieverResult.query;
|
||||||
docs = searchRetrieverResult.docs;
|
docs = searchRetrieverResult.docs;
|
||||||
|
logger.info(`Got ${docs.length} docs from searchRetriever.`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const sortedDocs = await this.rerankDocs(
|
const sortedDocs = await this.rerankDocs(
|
||||||
|
@ -269,6 +225,7 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||||
embeddings,
|
embeddings,
|
||||||
optimizationMode,
|
optimizationMode,
|
||||||
);
|
);
|
||||||
|
logger.info(`Sorted docs length: ${sortedDocs?.length ?? 0}`);
|
||||||
|
|
||||||
return sortedDocs;
|
return sortedDocs;
|
||||||
})
|
})
|
||||||
|
@ -296,7 +253,9 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||||
embeddings: Embeddings,
|
embeddings: Embeddings,
|
||||||
optimizationMode: 'speed' | 'balanced' | 'quality',
|
optimizationMode: 'speed' | 'balanced' | 'quality',
|
||||||
) {
|
) {
|
||||||
|
logger.info(`Reranking. Query="${query}", initial docs=${docs.length}, fileIds=${fileIds.length}`);
|
||||||
if (docs.length === 0 && fileIds.length === 0) {
|
if (docs.length === 0 && fileIds.length === 0) {
|
||||||
|
logger.info('No docs or fileIds to rerank. Returning empty.');
|
||||||
return docs;
|
return docs;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -307,32 +266,34 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||||
const contentPath = filePath + '-extracted.json';
|
const contentPath = filePath + '-extracted.json';
|
||||||
const embeddingsPath = filePath + '-embeddings.json';
|
const embeddingsPath = filePath + '-embeddings.json';
|
||||||
|
|
||||||
|
logger.info(`Reading content from ${contentPath}`);
|
||||||
|
logger.info(`Reading embeddings from ${embeddingsPath}`);
|
||||||
|
|
||||||
const content = JSON.parse(fs.readFileSync(contentPath, 'utf8'));
|
const content = JSON.parse(fs.readFileSync(contentPath, 'utf8'));
|
||||||
const embeddings = JSON.parse(fs.readFileSync(embeddingsPath, 'utf8'));
|
const fileEmbeddings = JSON.parse(fs.readFileSync(embeddingsPath, 'utf8'));
|
||||||
|
|
||||||
const fileSimilaritySearchObject = content.contents.map(
|
const fileSimilaritySearchObject = content.contents.map(
|
||||||
(c: string, i) => {
|
(c: string, i: number) => ({
|
||||||
return {
|
|
||||||
fileName: content.title,
|
fileName: content.title,
|
||||||
content: c,
|
content: c,
|
||||||
embeddings: embeddings.embeddings[i],
|
embeddings: fileEmbeddings.embeddings[i],
|
||||||
};
|
}),
|
||||||
},
|
|
||||||
);
|
);
|
||||||
|
|
||||||
return fileSimilaritySearchObject;
|
return fileSimilaritySearchObject;
|
||||||
})
|
})
|
||||||
.flat();
|
.flat();
|
||||||
|
|
||||||
|
// If only summarizing, just return top docs
|
||||||
if (query.toLocaleLowerCase() === 'summarize') {
|
if (query.toLocaleLowerCase() === 'summarize') {
|
||||||
|
logger.info(`Query is "summarize". Returning top 15 docs from web sources.`);
|
||||||
return docs.slice(0, 15);
|
return docs.slice(0, 15);
|
||||||
}
|
}
|
||||||
|
|
||||||
const docsWithContent = docs.filter(
|
const docsWithContent = docs.filter((doc) => doc.pageContent && doc.pageContent.length > 0);
|
||||||
(doc) => doc.pageContent && doc.pageContent.length > 0,
|
|
||||||
);
|
|
||||||
|
|
||||||
if (optimizationMode === 'speed' || this.config.rerank === false) {
|
if (optimizationMode === 'speed' || this.config.rerank === false) {
|
||||||
|
logger.info(`Reranking in 'speed' mode or no rerank. Docs with content: ${docsWithContent.length}`);
|
||||||
if (filesData.length > 0) {
|
if (filesData.length > 0) {
|
||||||
const [queryEmbedding] = await Promise.all([
|
const [queryEmbedding] = await Promise.all([
|
||||||
embeddings.embedQuery(query),
|
embeddings.embedQuery(query),
|
||||||
|
@ -343,14 +304,13 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||||
pageContent: fileData.content,
|
pageContent: fileData.content,
|
||||||
metadata: {
|
metadata: {
|
||||||
title: fileData.fileName,
|
title: fileData.fileName,
|
||||||
url: `File`,
|
url: 'File',
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
const similarity = filesData.map((fileData, i) => {
|
const similarity = filesData.map((fileData, i) => {
|
||||||
const sim = computeSimilarity(queryEmbedding, fileData.embeddings);
|
const sim = computeSimilarity(queryEmbedding, fileData.embeddings);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
index: i,
|
index: i,
|
||||||
similarity: sim,
|
similarity: sim,
|
||||||
|
@ -358,28 +318,23 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||||
});
|
});
|
||||||
|
|
||||||
let sortedDocs = similarity
|
let sortedDocs = similarity
|
||||||
.filter(
|
.filter((sim) => sim.similarity > (this.config.rerankThreshold ?? 0.3))
|
||||||
(sim) => sim.similarity > (this.config.rerankThreshold ?? 0.3),
|
|
||||||
)
|
|
||||||
.sort((a, b) => b.similarity - a.similarity)
|
.sort((a, b) => b.similarity - a.similarity)
|
||||||
.slice(0, 15)
|
.slice(0, 15)
|
||||||
.map((sim) => fileDocs[sim.index]);
|
.map((sim) => fileDocs[sim.index]);
|
||||||
|
|
||||||
sortedDocs =
|
sortedDocs = docsWithContent.length > 0 ? sortedDocs.slice(0, 8) : sortedDocs;
|
||||||
docsWithContent.length > 0 ? sortedDocs.slice(0, 8) : sortedDocs;
|
logger.info(`Final sorted docs in 'speed' mode: ${sortedDocs.length}`);
|
||||||
|
|
||||||
return [
|
return [...sortedDocs, ...docsWithContent.slice(0, 15 - sortedDocs.length)];
|
||||||
...sortedDocs,
|
|
||||||
...docsWithContent.slice(0, 15 - sortedDocs.length),
|
|
||||||
];
|
|
||||||
} else {
|
} else {
|
||||||
|
logger.info('No file data, returning top 15 from docsWithContent.');
|
||||||
return docsWithContent.slice(0, 15);
|
return docsWithContent.slice(0, 15);
|
||||||
}
|
}
|
||||||
} else if (optimizationMode === 'balanced') {
|
} else if (optimizationMode === 'balanced') {
|
||||||
|
logger.info('Reranking in balanced mode.');
|
||||||
const [docEmbeddings, queryEmbedding] = await Promise.all([
|
const [docEmbeddings, queryEmbedding] = await Promise.all([
|
||||||
embeddings.embedDocuments(
|
embeddings.embedDocuments(docsWithContent.map((doc) => doc.pageContent)),
|
||||||
docsWithContent.map((doc) => doc.pageContent),
|
|
||||||
),
|
|
||||||
embeddings.embedQuery(query),
|
embeddings.embedQuery(query),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
@ -389,7 +344,7 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||||
pageContent: fileData.content,
|
pageContent: fileData.content,
|
||||||
metadata: {
|
metadata: {
|
||||||
title: fileData.fileName,
|
title: fileData.fileName,
|
||||||
url: `File`,
|
url: 'File',
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
|
@ -399,7 +354,6 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||||
|
|
||||||
const similarity = docEmbeddings.map((docEmbedding, i) => {
|
const similarity = docEmbeddings.map((docEmbedding, i) => {
|
||||||
const sim = computeSimilarity(queryEmbedding, docEmbedding);
|
const sim = computeSimilarity(queryEmbedding, docEmbedding);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
index: i,
|
index: i,
|
||||||
similarity: sim,
|
similarity: sim,
|
||||||
|
@ -412,8 +366,13 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||||
.slice(0, 15)
|
.slice(0, 15)
|
||||||
.map((sim) => docsWithContent[sim.index]);
|
.map((sim) => docsWithContent[sim.index]);
|
||||||
|
|
||||||
|
logger.info(`Final sorted docs in 'balanced' mode: ${sortedDocs.length}`);
|
||||||
return sortedDocs;
|
return sortedDocs;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// If "quality" is passed but not implemented, you might want to log or fallback
|
||||||
|
logger.warn(`Optimization mode "${optimizationMode}" not fully implemented. Returning docs as-is.`);
|
||||||
|
return docsWithContent.slice(0, 15);
|
||||||
}
|
}
|
||||||
|
|
||||||
private processDocs(docs: Document[]) {
|
private processDocs(docs: Document[]) {
|
||||||
|
@ -429,12 +388,16 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||||
stream: IterableReadableStream<StreamEvent>,
|
stream: IterableReadableStream<StreamEvent>,
|
||||||
emitter: eventEmitter,
|
emitter: eventEmitter,
|
||||||
) {
|
) {
|
||||||
|
logger.info('Starting to stream chain events...');
|
||||||
for await (const event of stream) {
|
for await (const event of stream) {
|
||||||
|
// You can add debug logs here to see each event
|
||||||
|
// logger.info(`Event: ${JSON.stringify(event, null, 2)}`);
|
||||||
|
|
||||||
if (
|
if (
|
||||||
event.event === 'on_chain_end' &&
|
event.event === 'on_chain_end' &&
|
||||||
event.name === 'FinalSourceRetriever'
|
event.name === 'FinalSourceRetriever'
|
||||||
) {
|
) {
|
||||||
``;
|
logger.info('FinalSourceRetriever ended, sending docs to front-end...');
|
||||||
emitter.emit(
|
emitter.emit(
|
||||||
'data',
|
'data',
|
||||||
JSON.stringify({ type: 'sources', data: event.data.output }),
|
JSON.stringify({ type: 'sources', data: event.data.output }),
|
||||||
|
@ -444,6 +407,7 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||||
event.event === 'on_chain_stream' &&
|
event.event === 'on_chain_stream' &&
|
||||||
event.name === 'FinalResponseGenerator'
|
event.name === 'FinalResponseGenerator'
|
||||||
) {
|
) {
|
||||||
|
logger.info('Response chunk received, streaming to client...');
|
||||||
emitter.emit(
|
emitter.emit(
|
||||||
'data',
|
'data',
|
||||||
JSON.stringify({ type: 'response', data: event.data.chunk }),
|
JSON.stringify({ type: 'response', data: event.data.chunk }),
|
||||||
|
@ -453,9 +417,11 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||||
event.event === 'on_chain_end' &&
|
event.event === 'on_chain_end' &&
|
||||||
event.name === 'FinalResponseGenerator'
|
event.name === 'FinalResponseGenerator'
|
||||||
) {
|
) {
|
||||||
|
logger.info('FinalResponseGenerator ended, signaling end of stream.');
|
||||||
emitter.emit('end');
|
emitter.emit('end');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
logger.info('Finished streaming chain events.');
|
||||||
}
|
}
|
||||||
|
|
||||||
async searchAndAnswer(
|
async searchAndAnswer(
|
||||||
|
@ -468,6 +434,11 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||||
) {
|
) {
|
||||||
const emitter = new eventEmitter();
|
const emitter = new eventEmitter();
|
||||||
|
|
||||||
|
logger.info(`Received query: "${message}"`);
|
||||||
|
logger.info(`History length: ${history.length}`);
|
||||||
|
logger.info(`Optimization mode: ${optimizationMode}`);
|
||||||
|
logger.info(`File IDs: ${fileIds.join(', ') || 'None'}`);
|
||||||
|
|
||||||
const answeringChain = await this.createAnsweringChain(
|
const answeringChain = await this.createAnsweringChain(
|
||||||
llm,
|
llm,
|
||||||
fileIds,
|
fileIds,
|
||||||
|
@ -475,17 +446,17 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||||
optimizationMode,
|
optimizationMode,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// .streamEvents(...) can throw, so a try/catch can help you catch/log errors
|
||||||
|
try {
|
||||||
const stream = answeringChain.streamEvents(
|
const stream = answeringChain.streamEvents(
|
||||||
{
|
{ chat_history: history, query: message },
|
||||||
chat_history: history,
|
{ version: 'v1' },
|
||||||
query: message,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
version: 'v1',
|
|
||||||
},
|
|
||||||
);
|
);
|
||||||
|
|
||||||
this.handleStream(stream, emitter);
|
this.handleStream(stream, emitter);
|
||||||
|
} catch (error: any) {
|
||||||
|
logger.error(`Error in searchAndAnswer streaming: ${error.message}`);
|
||||||
|
emitter.emit('error', error);
|
||||||
|
}
|
||||||
|
|
||||||
return emitter;
|
return emitter;
|
||||||
}
|
}
|
||||||
|
|
48
src/utils/checkSearch.ts
Normal file
48
src/utils/checkSearch.ts
Normal file
|
@ -0,0 +1,48 @@
|
||||||
|
import { shouldPerformSearchPrompt } from '../prompts/shouldSearch';
|
||||||
|
import { HumanMessage } from '@langchain/core/messages';
|
||||||
|
import type { BaseChatModel } from '@langchain/core/language_models/chat_models';
|
||||||
|
import logger from './logger'; // Ensure the logger module is correctly imported
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determines whether an external search is required.
|
||||||
|
* @param llm - The AI language model instance.
|
||||||
|
* @param query - The user's message.
|
||||||
|
* @param history - Chat history.
|
||||||
|
* @returns {Promise<boolean>} - True if search is needed, False otherwise.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const checkIfSearchIsNeeded = async (
|
||||||
|
llm: BaseChatModel,
|
||||||
|
query: string,
|
||||||
|
history: Array<[string, string]>
|
||||||
|
): Promise<boolean> => {
|
||||||
|
const prompt = shouldPerformSearchPrompt(query, history);
|
||||||
|
|
||||||
|
logger.info(`📜 Generated Search Decision Prompt for query "${query}":\n${prompt}`);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await llm.invoke([new HumanMessage({ content: prompt })]);
|
||||||
|
|
||||||
|
// Log the raw response from LLM
|
||||||
|
logger.info(`🔍 Raw Response from LLM for query "${query}": ${JSON.stringify(response)}`);
|
||||||
|
|
||||||
|
const decision = String(response?.content || '').trim().toLowerCase();
|
||||||
|
|
||||||
|
// Log the decision for debugging
|
||||||
|
logger.info(`🔍 Search Decision for query "${query}": "${decision}"`);
|
||||||
|
|
||||||
|
if (decision === 'yes') {
|
||||||
|
logger.debug(`✅ Search Required for Query: "${query}"`);
|
||||||
|
return true;
|
||||||
|
} else if (decision === 'no') {
|
||||||
|
logger.debug(`❌ No Search Needed for Query: "${query}"`);
|
||||||
|
return false;
|
||||||
|
} else {
|
||||||
|
logger.warn(`⚠️ Unexpected Search Decision Output: "${decision}" (Defaulting to NO)`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`❌ Error in Search Decision: ${error}`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
|
@ -1,22 +1,28 @@
|
||||||
import winston from 'winston';
|
import winston from 'winston';
|
||||||
|
|
||||||
|
const { combine, timestamp, printf, colorize } = winston.format;
|
||||||
|
|
||||||
|
const logFormat = printf(({ timestamp, level, message }) => {
|
||||||
|
return `${timestamp} [${level.toUpperCase()}]: ${message}`;
|
||||||
|
});
|
||||||
|
|
||||||
const logger = winston.createLogger({
|
const logger = winston.createLogger({
|
||||||
level: 'info',
|
level: process.env.LOG_LEVEL || 'info',
|
||||||
|
format: combine(
|
||||||
|
timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
|
||||||
|
colorize(), // optional color in dev
|
||||||
|
logFormat
|
||||||
|
),
|
||||||
transports: [
|
transports: [
|
||||||
new winston.transports.Console({
|
// Console transport ensures Docker sees logs on stdout
|
||||||
format: winston.format.combine(
|
new winston.transports.Console(),
|
||||||
winston.format.colorize(),
|
new winston.transports.File({ filename: 'app.log' }),
|
||||||
winston.format.simple(),
|
|
||||||
),
|
// Optional: file transport if you also want to persist logs on the container’s filesystem
|
||||||
}),
|
// new winston.transports.File({ filename: 'app.log' }),
|
||||||
new winston.transports.File({
|
|
||||||
filename: 'app.log',
|
|
||||||
format: winston.format.combine(
|
|
||||||
winston.format.timestamp(),
|
|
||||||
winston.format.json(),
|
|
||||||
),
|
|
||||||
}),
|
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
logger.info("✅ Winston logger active, logging to console!");
|
||||||
|
|
||||||
export default logger;
|
export default logger;
|
||||||
|
|
|
@ -15,6 +15,8 @@ export const handleConnection = async (
|
||||||
request: IncomingMessage,
|
request: IncomingMessage,
|
||||||
) => {
|
) => {
|
||||||
try {
|
try {
|
||||||
|
logger.info(`🔗 New WebSocket connection from ${request.socket.remoteAddress}`);
|
||||||
|
|
||||||
const searchParams = new URL(request.url, `http://${request.headers.host}`)
|
const searchParams = new URL(request.url, `http://${request.headers.host}`)
|
||||||
.searchParams;
|
.searchParams;
|
||||||
|
|
||||||
|
@ -23,9 +25,11 @@ export const handleConnection = async (
|
||||||
getAvailableEmbeddingModelProviders(),
|
getAvailableEmbeddingModelProviders(),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
// Retrieve query parameters
|
||||||
const chatModelProvider =
|
const chatModelProvider =
|
||||||
searchParams.get('chatModelProvider') ||
|
searchParams.get('chatModelProvider') ||
|
||||||
Object.keys(chatModelProviders)[0];
|
Object.keys(chatModelProviders)[0];
|
||||||
|
|
||||||
const chatModel =
|
const chatModel =
|
||||||
searchParams.get('chatModel') ||
|
searchParams.get('chatModel') ||
|
||||||
Object.keys(chatModelProviders[chatModelProvider])[0];
|
Object.keys(chatModelProviders[chatModelProvider])[0];
|
||||||
|
@ -33,21 +37,32 @@ export const handleConnection = async (
|
||||||
const embeddingModelProvider =
|
const embeddingModelProvider =
|
||||||
searchParams.get('embeddingModelProvider') ||
|
searchParams.get('embeddingModelProvider') ||
|
||||||
Object.keys(embeddingModelProviders)[0];
|
Object.keys(embeddingModelProviders)[0];
|
||||||
|
|
||||||
const embeddingModel =
|
const embeddingModel =
|
||||||
searchParams.get('embeddingModel') ||
|
searchParams.get('embeddingModel') ||
|
||||||
Object.keys(embeddingModelProviders[embeddingModelProvider])[0];
|
Object.keys(embeddingModelProviders[embeddingModelProvider])[0];
|
||||||
|
|
||||||
|
logger.debug(
|
||||||
|
`📜 WebSocket Connection - Model Selection:
|
||||||
|
🔹 Chat Model Provider: ${chatModelProvider}
|
||||||
|
🔹 Chat Model: ${chatModel}
|
||||||
|
🔹 Embedding Model Provider: ${embeddingModelProvider}
|
||||||
|
🔹 Embedding Model: ${embeddingModel}`
|
||||||
|
);
|
||||||
|
|
||||||
let llm: BaseChatModel | undefined;
|
let llm: BaseChatModel | undefined;
|
||||||
let embeddings: Embeddings | undefined;
|
let embeddings: Embeddings | undefined;
|
||||||
|
|
||||||
|
// Handle model selection
|
||||||
if (
|
if (
|
||||||
chatModelProviders[chatModelProvider] &&
|
chatModelProviders[chatModelProvider] &&
|
||||||
chatModelProviders[chatModelProvider][chatModel] &&
|
chatModelProviders[chatModelProvider][chatModel] &&
|
||||||
chatModelProvider != 'custom_openai'
|
chatModelProvider !== 'custom_openai'
|
||||||
) {
|
) {
|
||||||
llm = chatModelProviders[chatModelProvider][chatModel]
|
llm = chatModelProviders[chatModelProvider][chatModel]
|
||||||
.model as unknown as BaseChatModel | undefined;
|
.model as unknown as BaseChatModel | undefined;
|
||||||
} else if (chatModelProvider == 'custom_openai') {
|
} else if (chatModelProvider === 'custom_openai') {
|
||||||
|
logger.info(`🛠 Using custom OpenAI model: ${chatModel}`);
|
||||||
llm = new ChatOpenAI({
|
llm = new ChatOpenAI({
|
||||||
modelName: chatModel,
|
modelName: chatModel,
|
||||||
openAIApiKey: searchParams.get('openAIApiKey'),
|
openAIApiKey: searchParams.get('openAIApiKey'),
|
||||||
|
@ -62,12 +77,12 @@ export const handleConnection = async (
|
||||||
embeddingModelProviders[embeddingModelProvider] &&
|
embeddingModelProviders[embeddingModelProvider] &&
|
||||||
embeddingModelProviders[embeddingModelProvider][embeddingModel]
|
embeddingModelProviders[embeddingModelProvider][embeddingModel]
|
||||||
) {
|
) {
|
||||||
embeddings = embeddingModelProviders[embeddingModelProvider][
|
embeddings = embeddingModelProviders[embeddingModelProvider][embeddingModel]
|
||||||
embeddingModel
|
.model as Embeddings | undefined;
|
||||||
].model as Embeddings | undefined;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!llm || !embeddings) {
|
if (!llm || !embeddings) {
|
||||||
|
logger.error(`❌ Invalid LLM or embeddings model selection!`);
|
||||||
ws.send(
|
ws.send(
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
type: 'error',
|
type: 'error',
|
||||||
|
@ -76,10 +91,15 @@ export const handleConnection = async (
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
ws.close();
|
ws.close();
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
logger.info(`✅ WebSocket setup complete - Ready for messages`);
|
||||||
|
|
||||||
|
// Send an initial "open" signal once connection is ready
|
||||||
const interval = setInterval(() => {
|
const interval = setInterval(() => {
|
||||||
if (ws.readyState === ws.OPEN) {
|
if (ws.readyState === ws.OPEN) {
|
||||||
|
logger.debug(`📡 Sending initial 'open' signal to client`);
|
||||||
ws.send(
|
ws.send(
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
type: 'signal',
|
type: 'signal',
|
||||||
|
@ -90,14 +110,19 @@ export const handleConnection = async (
|
||||||
}
|
}
|
||||||
}, 5);
|
}, 5);
|
||||||
|
|
||||||
ws.on(
|
// Handle incoming messages
|
||||||
'message',
|
ws.on('message', async (message) => {
|
||||||
async (message) =>
|
logger.info(`📩 Received message from client: ${message.toString()}`);
|
||||||
await handleMessage(message.toString(), ws, llm, embeddings),
|
await handleMessage(message.toString(), ws, llm, embeddings);
|
||||||
);
|
});
|
||||||
|
|
||||||
|
// Handle WebSocket closure
|
||||||
|
ws.on('close', () => {
|
||||||
|
logger.warn(`❌ WebSocket connection closed for ${request.socket.remoteAddress}`);
|
||||||
|
});
|
||||||
|
|
||||||
ws.on('close', () => logger.debug('Connection closed'));
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
logger.error(`❌ WebSocket error: ${err.message}`);
|
||||||
ws.send(
|
ws.send(
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
type: 'error',
|
type: 'error',
|
||||||
|
@ -106,6 +131,5 @@ export const handleConnection = async (
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
ws.close();
|
ws.close();
|
||||||
logger.error(err);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
|
@ -134,6 +134,8 @@ const handleEmitterEvents = (
|
||||||
});
|
});
|
||||||
emitter.on('error', (data) => {
|
emitter.on('error', (data) => {
|
||||||
const parsedData = JSON.parse(data);
|
const parsedData = JSON.parse(data);
|
||||||
|
logger.debug(`📡 Emitter received data: ${JSON.stringify(parsedData)}`);
|
||||||
|
|
||||||
ws.send(
|
ws.send(
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
type: 'error',
|
type: 'error',
|
||||||
|
@ -151,6 +153,7 @@ export const handleMessage = async (
|
||||||
embeddings: Embeddings,
|
embeddings: Embeddings,
|
||||||
) => {
|
) => {
|
||||||
try {
|
try {
|
||||||
|
logger.debug('Handling message...');
|
||||||
const parsedWSMessage = JSON.parse(message) as WSMessage;
|
const parsedWSMessage = JSON.parse(message) as WSMessage;
|
||||||
const parsedMessage = parsedWSMessage.message;
|
const parsedMessage = parsedWSMessage.message;
|
||||||
|
|
||||||
|
|
|
@ -14,9 +14,9 @@ const montserrat = Montserrat({
|
||||||
});
|
});
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
title: 'Perplexica - Chat with the internet',
|
title: 'gochat247 - aibot - Chat with the internet',
|
||||||
description:
|
description:
|
||||||
'Perplexica is an AI powered chatbot that is connected to the internet.',
|
'gochat247 - aibot is an AI powered chatbot that is connected to the internet.',
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function RootLayout({
|
export default function RootLayout({
|
||||||
|
|
|
@ -2,7 +2,7 @@ import { Metadata } from 'next';
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
title: 'Library - Perplexica',
|
title: 'Library - gochat247 - aibot',
|
||||||
};
|
};
|
||||||
|
|
||||||
const Layout = ({ children }: { children: React.ReactNode }) => {
|
const Layout = ({ children }: { children: React.ReactNode }) => {
|
||||||
|
|
|
@ -3,8 +3,8 @@ import { Metadata } from 'next';
|
||||||
import { Suspense } from 'react';
|
import { Suspense } from 'react';
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
title: 'Chat - Perplexica',
|
title: 'Chat - gochat247 - aibot',
|
||||||
description: 'Chat with the internet, chat with Perplexica.',
|
description: 'Chat with the internet, chat with gochat247 - aibot.',
|
||||||
};
|
};
|
||||||
|
|
||||||
const Home = () => {
|
const Home = () => {
|
||||||
|
|
|
@ -38,7 +38,7 @@ const EmptyChat = ({
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col items-center justify-center min-h-screen max-w-screen-sm mx-auto p-2 space-y-8">
|
<div className="flex flex-col items-center justify-center min-h-screen max-w-screen-sm mx-auto p-2 space-y-8">
|
||||||
<h2 className="text-black/70 dark:text-white/70 text-3xl font-medium -mt-8">
|
<h2 className="text-black/70 dark:text-white/70 text-3xl font-medium -mt-8">
|
||||||
Research begins here.
|
gochat247 - aibot : knowledge with some privacy
|
||||||
</h2>
|
</h2>
|
||||||
<EmptyChatMessageInput
|
<EmptyChatMessageInput
|
||||||
sendMessage={sendMessage}
|
sendMessage={sendMessage}
|
||||||
|
|
Loading…
Add table
Reference in a new issue